blob: d19694f225ef4c566f3ddbd47cb7e2f7e3376703 [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()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800222 mBuiltinDisplays(),
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
Jesse Hall6c913be2013-08-08 12:15:49 -0700430void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
431 Mutex::Autolock _l(mStateLock);
432
433 ssize_t idx = mCurrentState.displays.indexOfKey(display);
434 if (idx < 0) {
435 ALOGW("destroyDisplay: invalid display token");
436 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 }
Jesse Hall692c7232012-11-08 15:41:56 -0800454 return mBuiltinDisplays[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
Dan Stoza7f7da322014-05-02 15:26:25 -0700811status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
812 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800813 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700814 return BAD_VALUE;
815 }
816
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500817 if (!display.get())
818 return NAME_NOT_FOUND;
819
Jesse Hall692c7232012-11-08 15:41:56 -0800820 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700821 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800822 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700823 type = i;
824 break;
825 }
826 }
827
828 if (type < 0) {
829 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700830 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700831
Mathias Agopian8b736f12012-08-13 17:54:26 -0700832 // TODO: Not sure if display density should handled by SF any longer
833 class Density {
834 static int getDensityFromProperty(char const* propName) {
835 char property[PROPERTY_VALUE_MAX];
836 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800837 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700838 density = atoi(property);
839 }
840 return density;
841 }
842 public:
843 static int getEmuDensity() {
844 return getDensityFromProperty("qemu.sf.lcd_density"); }
845 static int getBuildDensity() {
846 return getDensityFromProperty("ro.sf.lcd_density"); }
847 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700848
Dan Stoza7f7da322014-05-02 15:26:25 -0700849 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700850
Steven Thomas6d8110b2017-08-31 18:24:21 -0700851 ConditionalLock _l(mStateLock,
852 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800853 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700854 DisplayInfo info = DisplayInfo();
855
Dan Stoza9e56aa02015-11-02 13:00:03 -0800856 float xdpi = hwConfig->getDpiX();
857 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700858
859 if (type == DisplayDevice::DISPLAY_PRIMARY) {
860 // The density of the device is provided by a build property
861 float density = Density::getBuildDensity() / 160.0f;
862 if (density == 0) {
863 // the build doesn't provide a density -- this is wrong!
864 // use xdpi instead
865 ALOGE("ro.sf.lcd_density must be defined as a build property");
866 density = xdpi / 160.0f;
867 }
868 if (Density::getEmuDensity()) {
869 // if "qemu.sf.lcd_density" is specified, it overrides everything
870 xdpi = ydpi = density = Density::getEmuDensity();
871 density /= 160.0f;
872 }
873 info.density = density;
874
875 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700876 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800877 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700878 } else {
879 // TODO: where should this value come from?
880 static const int TV_DENSITY = 213;
881 info.density = TV_DENSITY / 160.0f;
882 info.orientation = 0;
883 }
884
Dan Stoza9e56aa02015-11-02 13:00:03 -0800885 info.w = hwConfig->getWidth();
886 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700887 info.xdpi = xdpi;
888 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800889 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900890 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800891
Andy McFadden91b2ca82014-06-13 14:04:23 -0700892 // This is how far in advance a buffer must be queued for
893 // presentation at a given time. If you want a buffer to appear
894 // on the screen at time N, you must submit the buffer before
895 // (N - presentationDeadline).
896 //
897 // Normally it's one full refresh period (to give SF a chance to
898 // latch the buffer), but this can be reduced by configuring a
899 // DispSync offset. Any additional delays introduced by the hardware
900 // composer or panel must be accounted for here.
901 //
902 // We add an additional 1ms to allow for processing time and
903 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800904 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800905 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700906
907 // All non-virtual displays are currently considered secure.
908 info.secure = true;
909
Iris Chang7501ed62018-04-30 14:45:42 +0800910 if (type == DisplayDevice::DISPLAY_PRIMARY &&
911 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
912 std::swap(info.w, info.h);
913 }
914
Michael Wright28f24d02016-07-12 13:30:53 -0700915 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700916 }
917
Dan Stoza7f7da322014-05-02 15:26:25 -0700918 return NO_ERROR;
919}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700920
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800921status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700922 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800923 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700924 return BAD_VALUE;
925 }
926
927 // FIXME for now we always return stats for the primary display
928 memset(stats, 0, sizeof(*stats));
929 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
930 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
931 return NO_ERROR;
932}
933
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700934int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800935 if (display == nullptr) {
936 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800937 return BAD_VALUE;
938 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700939
940 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800941 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700942 return device->getActiveConfig();
943 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700944
Dan Stoza24a42e92015-03-09 10:04:11 -0700945 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700946}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700947
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700948void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
949 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
950 this);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700951 int currentMode = hw->getActiveConfig();
952
953 if (mode == currentMode) {
954 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
955 return;
956 }
957
Dominik Laskowski281644e2018-04-19 15:47:35 -0700958 if (hw->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700959 ALOGW("Trying to set config for virtual display");
960 return;
961 }
962
963 hw->setActiveConfig(mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -0700964 getHwComposer().setActiveConfig(hw->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700965}
966
967status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
968 class MessageSetActiveConfig: public MessageBase {
969 SurfaceFlinger& mFlinger;
970 sp<IBinder> mDisplay;
971 int mMode;
972 public:
973 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
974 int mode) :
975 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
976 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700977 Vector<DisplayInfo> configs;
978 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700979 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700980 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700981 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700982 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700983 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700984 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800985 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700986 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700987 mMode, mDisplay.get());
Dominik Laskowski281644e2018-04-19 15:47:35 -0700988 } else if (hw->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700989 ALOGW("Attempt to set active config = %d for virtual display",
990 mMode);
991 } else {
992 mFlinger.setActiveConfigInternal(hw, mMode);
993 }
994 return true;
995 }
996 };
997 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
998 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700999 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001000}
Michael Wright28f24d02016-07-12 13:30:53 -07001001status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001002 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001003 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
1004 return BAD_VALUE;
1005 }
1006
1007 if (!display.get()) {
1008 return NAME_NOT_FOUND;
1009 }
1010
1011 int32_t type = NAME_NOT_FOUND;
1012 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
1013 if (display == mBuiltinDisplays[i]) {
1014 type = i;
1015 break;
1016 }
1017 }
1018
1019 if (type < 0) {
1020 return type;
1021 }
1022
Peiyong Lina52f0292018-03-14 17:26:31 -07001023 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001024 {
1025 ConditionalLock _l(mStateLock,
1026 std::this_thread::get_id() != mMainThreadId);
1027 modes = getHwComposer().getColorModes(type);
1028 }
Michael Wright28f24d02016-07-12 13:30:53 -07001029 outColorModes->clear();
1030 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1031
1032 return NO_ERROR;
1033}
1034
Peiyong Lina52f0292018-03-14 17:26:31 -07001035ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001036 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -07001037 if (device != nullptr) {
1038 return device->getActiveColorMode();
1039 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001040 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001041}
1042
1043void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001044 ColorMode mode, Dataspace dataSpace,
1045 RenderIntent renderIntent) {
Peiyong Lina52f0292018-03-14 17:26:31 -07001046 ColorMode currentMode = hw->getActiveColorMode();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001047 Dataspace currentDataSpace = hw->getCompositionDataSpace();
Peiyong Lin38e9a562018-04-10 16:24:20 -07001048 RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001049
Peiyong Lin38e9a562018-04-10 16:24:20 -07001050 if (mode == currentMode && dataSpace == currentDataSpace &&
1051 renderIntent == currentRenderIntent) {
1052 return;
1053 }
1054
Dominik Laskowski281644e2018-04-19 15:47:35 -07001055 if (hw->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001056 ALOGW("Trying to set config for virtual display");
1057 return;
1058 }
1059
1060 hw->setActiveColorMode(mode);
1061 hw->setCompositionDataSpace(dataSpace);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001062 hw->setActiveRenderIntent(renderIntent);
Dominik Laskowski281644e2018-04-19 15:47:35 -07001063 getHwComposer().setActiveColorMode(hw->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001064
1065 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1066 decodeColorMode(mode).c_str(), mode,
1067 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1068 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001069}
1070
1071
1072status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001073 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001074 class MessageSetActiveColorMode: public MessageBase {
1075 SurfaceFlinger& mFlinger;
1076 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001077 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001078 public:
1079 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001080 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001081 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1082 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001083 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001084 mFlinger.getDisplayColorModes(mDisplay, &modes);
1085 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001086 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001087 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1088 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001089 return true;
1090 }
1091 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1092 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001093 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1094 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Dominik Laskowski281644e2018-04-19 15:47:35 -07001095 } else if (hw->isVirtual()) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001096 ALOGW("Attempt to set active color mode %s %d for virtual display",
1097 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001098 } else {
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001099 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN,
1100 RenderIntent::COLORIMETRIC);
Michael Wright28f24d02016-07-12 13:30:53 -07001101 }
1102 return true;
1103 }
1104 };
1105 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1106 postMessageSync(msg);
1107 return NO_ERROR;
1108}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001109
Svetoslavd85084b2014-03-20 10:28:31 -07001110status_t SurfaceFlinger::clearAnimationFrameStats() {
1111 Mutex::Autolock _l(mStateLock);
1112 mAnimFrameTracker.clearStats();
1113 return NO_ERROR;
1114}
1115
1116status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1117 Mutex::Autolock _l(mStateLock);
1118 mAnimFrameTracker.getStats(outStats);
1119 return NO_ERROR;
1120}
1121
Dan Stozac4f471e2016-03-24 09:31:08 -07001122status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1123 HdrCapabilities* outCapabilities) const {
1124 Mutex::Autolock _l(mStateLock);
1125
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001126 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001127 if (displayDevice == nullptr) {
1128 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1129 return BAD_VALUE;
1130 }
1131
Peiyong Linfb069302018-04-25 14:34:31 -07001132 // At this point the DisplayDeivce should already be set up,
1133 // meaning the luminance information is already queried from
1134 // hardware composer and stored properly.
1135 const HdrCapabilities& capabilities = displayDevice->getHdrCapabilities();
1136 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1137 capabilities.getDesiredMaxLuminance(),
1138 capabilities.getDesiredMaxAverageLuminance(),
1139 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001140
1141 return NO_ERROR;
1142}
1143
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001144status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001145 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1146 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001147
Chia-I Wu90f669f2017-10-05 14:24:41 -07001148 if (mInjectVSyncs == enable) {
1149 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001150 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001151
1152 if (enable) {
1153 ALOGV("VSync Injections enabled");
1154 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001155 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001156 mInjectorEventThread = std::make_unique<
1157 impl::EventThread>(mVSyncInjector.get(),
1158 [this]() { resyncWithRateLimit(); },
1159 impl::EventThread::InterceptVSyncsCallback(),
1160 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001161 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001162 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001163 } else {
1164 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001165 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001166 }
1167
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001168 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001169 });
1170 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001171 return NO_ERROR;
1172}
1173
1174status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001175 Mutex::Autolock _l(mStateLock);
1176
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001177 if (!mInjectVSyncs) {
1178 ALOGE("VSync Injections not enabled");
1179 return BAD_VALUE;
1180 }
1181 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1182 ALOGV("Injecting VSync inside SurfaceFlinger");
1183 mVSyncInjector->onInjectSyncEvent(when);
1184 }
1185 return NO_ERROR;
1186}
1187
Lloyd Pique755e3192018-01-31 16:46:15 -08001188status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1189 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001190 IPCThreadState* ipc = IPCThreadState::self();
1191 const int pid = ipc->getCallingPid();
1192 const int uid = ipc->getCallingUid();
1193 if ((uid != AID_SHELL) &&
1194 !PermissionCache::checkPermission(sDump, pid, uid)) {
1195 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1196 return PERMISSION_DENIED;
1197 }
1198
1199 // Try to acquire a lock for 1s, fail gracefully
1200 const status_t err = mStateLock.timedLock(s2ns(1));
1201 const bool locked = (err == NO_ERROR);
1202 if (!locked) {
1203 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1204 return TIMED_OUT;
1205 }
1206
1207 outLayers->clear();
1208 mCurrentState.traverseInZOrder([&](Layer* layer) {
1209 outLayers->push_back(layer->getLayerDebugInfo());
1210 });
1211
1212 mStateLock.unlock();
1213 return NO_ERROR;
1214}
1215
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001216// ----------------------------------------------------------------------------
1217
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001218sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1219 ISurfaceComposer::VsyncSource vsyncSource) {
1220 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1221 return mSFEventThread->createEventConnection();
1222 } else {
1223 return mEventThread->createEventConnection();
1224 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001225}
1226
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001227// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001228
1229void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001230 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001231}
1232
1233void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001234 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001235}
1236
1237void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001238 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001239}
1240
1241void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001242 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001243 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001244}
1245
1246status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001247 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001248 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001249}
1250
1251status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001252 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001253 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001254 if (res == NO_ERROR) {
1255 msg->wait();
1256 }
1257 return res;
1258}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001259
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001260void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001261 do {
1262 waitForEvent();
1263 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001264}
1265
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001266void SurfaceFlinger::enableHardwareVsync() {
1267 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001268 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001269 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001270 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1271 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001272 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001273 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001274}
1275
Jesse Hall948fe0c2013-10-14 12:56:09 -07001276void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001277 Mutex::Autolock _l(mHWVsyncLock);
1278
Jesse Hall948fe0c2013-10-14 12:56:09 -07001279 if (makeAvailable) {
1280 mHWVsyncAvailable = true;
1281 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001282 // Hardware vsync is not currently available, so abort the resync
1283 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001284 return;
1285 }
1286
David Sodman105b7dc2017-11-04 20:28:14 -07001287 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001288 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001289
1290 mPrimaryDispSync.reset();
1291 mPrimaryDispSync.setPeriod(period);
1292
1293 if (!mPrimaryHWVsyncEnabled) {
1294 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001295 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1296 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001297 mPrimaryHWVsyncEnabled = true;
1298 }
1299}
1300
Jesse Hall948fe0c2013-10-14 12:56:09 -07001301void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001302 Mutex::Autolock _l(mHWVsyncLock);
1303 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001304 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1305 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001306 mPrimaryDispSync.endResync();
1307 mPrimaryHWVsyncEnabled = false;
1308 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001309 if (makeUnavailable) {
1310 mHWVsyncAvailable = false;
1311 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001312}
1313
Tim Murray4a4e4a22016-04-19 16:29:23 +00001314void SurfaceFlinger::resyncWithRateLimit() {
1315 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001316
1317 // No explicit locking is needed here since EventThread holds a lock while calling this method
1318 static nsecs_t sLastResyncAttempted = 0;
1319 const nsecs_t now = systemTime();
1320 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001321 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001322 }
Dan Stoza57164302017-05-08 14:03:54 -07001323 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001324}
1325
Steven Thomasb02664d2017-07-26 18:48:28 -07001326void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1327 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001328 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001329 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001330 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001331 return;
1332 }
1333
1334 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001335 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001336 return;
1337 }
1338
Jamie Gennisd1700752013-10-14 12:22:52 -07001339 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001340
Jamie Gennisd1700752013-10-14 12:22:52 -07001341 { // Scope for the lock
1342 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001343 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001344 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001345 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001346 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001347
1348 if (needsHwVsync) {
1349 enableHardwareVsync();
1350 } else {
1351 disableHardwareVsync(false);
1352 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001353}
1354
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001355void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001356 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1357 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001358}
1359
Lloyd Pique715a2c12017-12-14 17:18:08 -08001360void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1361 HWC2::Connection connection) {
1362 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1363 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001364
Lloyd Piqueba04e622017-12-14 17:11:26 -08001365 // Ignore events that do not have the right sequenceId.
1366 if (sequenceId != getBE().mComposerSequenceId) {
1367 return;
1368 }
1369
Steven Thomasb02664d2017-07-26 18:48:28 -07001370 // Only lock if we're not on the main thread. This function is normally
1371 // called on a hwbinder thread, but for the primary display it's called on
1372 // the main thread with the state lock already held, so don't attempt to
1373 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001374 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001375
Lloyd Pique715a2c12017-12-14 17:18:08 -08001376 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001377
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001378 if (std::this_thread::get_id() == mMainThreadId) {
1379 // Process all pending hot plug events immediately if we are on the main thread.
1380 processDisplayHotplugEventsLocked();
1381 }
1382
Lloyd Piqueba04e622017-12-14 17:11:26 -08001383 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001384}
1385
Steven Thomasb02664d2017-07-26 18:48:28 -07001386void SurfaceFlinger::onRefreshReceived(int sequenceId,
1387 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001388 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001389 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001390 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001391 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001392 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001393}
1394
Dan Stoza9e56aa02015-11-02 13:00:03 -08001395void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001396 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001397 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001398 getHwComposer().setVsyncEnabled(disp,
1399 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001400}
1401
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001402// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001403void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001404 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001405 // Clear the drawing state so that the logic inside of
1406 // handleTransactionLocked will fire. It will determine the delta between
1407 // mCurrentState and mDrawingState and re-apply all changes when we make the
1408 // transition.
1409 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001410 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001411 mDisplays.clear();
1412}
1413
Steven Thomas050b2c82017-03-06 11:45:16 -08001414void SurfaceFlinger::updateVrFlinger() {
1415 if (!mVrFlinger)
1416 return;
1417 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001418 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001419 return;
1420 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001421
David Sodman105b7dc2017-11-04 20:28:14 -07001422 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001423 ALOGE("Vr flinger is only supported for remote hardware composer"
1424 " service connections. Ignoring request to transition to vr"
1425 " flinger.");
1426 mVrFlingerRequestsDisplay = false;
1427 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001428 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001429
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001430 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001431
Steven Thomasb02664d2017-07-26 18:48:28 -07001432 int currentDisplayPowerMode = getDisplayDeviceLocked(
1433 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001434
Steven Thomasb02664d2017-07-26 18:48:28 -07001435 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001436 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001437 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001438
Steven Thomasb02664d2017-07-26 18:48:28 -07001439 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001440 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001441 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1442 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001443 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001444
David Sodman105b7dc2017-11-04 20:28:14 -07001445 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1446 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001447
1448 if (vrFlingerRequestsDisplay) {
1449 mVrFlinger->GrantDisplayOwnership();
1450 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001451 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001452 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001453
1454 mVisibleRegionsDirty = true;
1455 invalidateHwcGeometry();
1456
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001457 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001458 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1459 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1460 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001461
Steven Thomasb02664d2017-07-26 18:48:28 -07001462 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001463 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001464 const nsecs_t period = activeConfig->getVsyncPeriod();
1465 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001466
Steven Thomasb02664d2017-07-26 18:48:28 -07001467 // Use phase of 0 since phase is not known.
1468 // Use latency of 0, which will snap to the ideal latency.
1469 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001470
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001471 android_atomic_or(1, &mRepaintEverything);
1472 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001473}
1474
Mathias Agopian4fec8732012-06-29 14:12:52 -07001475void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001476 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001477 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001478 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001479 bool frameMissed = !mHadClientComposition &&
1480 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001481 (mPreviousPresentFence->getSignalTime() ==
1482 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001483 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001484 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001485 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001486 mTimeStats.incrementMissedFrames();
1487 if (mPropagateBackpressure) {
1488 signalLayerUpdate();
1489 break;
1490 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001491 }
Dan Stoza50182882016-07-08 12:02:20 -07001492
Steven Thomas050b2c82017-03-06 11:45:16 -08001493 // Now that we're going to make it to the handleMessageTransaction()
1494 // call below it's safe to call updateVrFlinger(), which will
1495 // potentially trigger a display handoff.
1496 updateVrFlinger();
1497
Dan Stoza6b9454d2014-11-07 16:00:59 -08001498 bool refreshNeeded = handleMessageTransaction();
1499 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001500 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001501 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001502 // Signal a refresh if a transaction modified the window state,
1503 // a new buffer was latched, or if HWC has requested a full
1504 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001505 signalRefresh();
1506 }
1507 break;
1508 }
1509 case MessageQueue::REFRESH: {
1510 handleMessageRefresh();
1511 break;
1512 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001513 }
1514}
1515
Dan Stoza6b9454d2014-11-07 16:00:59 -08001516bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001517 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001518 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001519 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001520 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001521 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001522 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001523}
1524
Dan Stoza6b9454d2014-11-07 16:00:59 -08001525bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001526 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001527 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001528}
1529
1530void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001531 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001532
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001533 mRefreshPending = false;
1534
Chia-I Wu30505fb2018-03-26 16:20:31 -07001535 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001536
Chia-I Wu30505fb2018-03-26 16:20:31 -07001537 preComposition(refreshStartTime);
1538 rebuildLayerStacks();
1539 setUpHWComposer();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001540 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001541 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001542 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001543 doComposition();
Chia-I Wu30505fb2018-03-26 16:20:31 -07001544 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001545
David Sodman105b7dc2017-11-04 20:28:14 -07001546 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001547
1548 mHadClientComposition = false;
1549 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1550 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1551 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001552 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001553 }
Dan Stoza84d619e2018-03-28 17:07:36 -07001554 mVsyncModulator.setLastFrameUsedRenderEngine(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001555
Dan Stoza9e56aa02015-11-02 13:00:03 -08001556 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001557}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001558
Mathias Agopiancd60f992012-08-16 16:28:27 -07001559void SurfaceFlinger::doDebugFlashRegions()
1560{
1561 // is debugging enabled
1562 if (CC_LIKELY(!mDebugRegion))
1563 return;
1564
1565 const bool repaintEverything = mRepaintEverything;
1566 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1567 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001568 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001569 // transform the dirty region into this screen's coordinate space
1570 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1571 if (!dirtyRegion.isEmpty()) {
1572 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001573 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001574
1575 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001576 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001577 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001578 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1579
Mathias Agopianda27af92012-09-13 18:17:13 -07001580 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001581 }
1582 }
1583 }
1584
1585 postFramebuffer();
1586
1587 if (mDebugRegion > 1) {
1588 usleep(mDebugRegion * 1000);
1589 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001590
Dan Stoza9e56aa02015-11-02 13:00:03 -08001591 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001592 auto& displayDevice = mDisplays[displayId];
1593 if (!displayDevice->isDisplayOn()) {
1594 continue;
1595 }
1596
David Sodman105b7dc2017-11-04 20:28:14 -07001597 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1598 ALOGE_IF(result != NO_ERROR,
1599 "prepareFrame for display %zd failed:"
1600 " %d (%s)",
1601 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001602 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001603}
1604
Adrian Roos1e1a1282017-11-01 19:05:31 +01001605void SurfaceFlinger::doTracing(const char* where) {
1606 ATRACE_CALL();
1607 ATRACE_NAME(where);
1608 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001609 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001610 }
1611}
1612
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001613void SurfaceFlinger::logLayerStats() {
1614 ATRACE_CALL();
1615 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1616 int32_t hwcId = -1;
1617 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1618 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1619 if (displayDevice->isPrimary()) {
1620 hwcId = displayDevice->getHwcDisplayId();
1621 break;
1622 }
1623 }
1624 if (hwcId < 0) {
1625 ALOGE("LayerStats: Hmmm, no primary display?");
1626 return;
1627 }
1628 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1629 }
1630}
1631
Chia-I Wu30505fb2018-03-26 16:20:31 -07001632void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001633{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001634 ATRACE_CALL();
1635 ALOGV("preComposition");
1636
Mathias Agopiancd60f992012-08-16 16:28:27 -07001637 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001638 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001639 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001640 needExtraInvalidate = true;
1641 }
Robert Carr2047fae2016-11-28 14:09:09 -08001642 });
1643
Mathias Agopiancd60f992012-08-16 16:28:27 -07001644 if (needExtraInvalidate) {
1645 signalLayerUpdate();
1646 }
1647}
1648
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001649void SurfaceFlinger::updateCompositorTiming(
1650 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1651 std::shared_ptr<FenceTime>& presentFenceTime) {
1652 // Update queue of past composite+present times and determine the
1653 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001654 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001655 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001656 while (!getBE().mCompositePresentTimes.empty()) {
1657 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001658 // Cached values should have been updated before calling this method,
1659 // which helps avoid duplicate syscalls.
1660 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1661 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1662 break;
1663 }
1664 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001665 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001666 }
1667
1668 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001669 while (getBE().mCompositePresentTimes.size() > 16) {
1670 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001671 }
1672
Brian Andersond0010582017-03-07 13:20:31 -08001673 setCompositorTimingSnapped(
1674 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1675}
1676
1677void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1678 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001679 // Integer division and modulo round toward 0 not -inf, so we need to
1680 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001681 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001682 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1683 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1684
Brian Andersond0010582017-03-07 13:20:31 -08001685 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1686 if (idealLatency <= 0) {
1687 idealLatency = vsyncInterval;
1688 }
1689
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001690 // Snap the latency to a value that removes scheduling jitter from the
1691 // composition and present times, which often have >1ms of jitter.
1692 // Reducing jitter is important if an app attempts to extrapolate
1693 // something (such as user input) to an accurate diasplay time.
1694 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1695 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001696 nsecs_t bias = vsyncInterval / 2;
1697 int64_t extraVsyncs =
1698 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1699 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1700 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001701
David Sodman99974d22017-11-28 12:04:33 -08001702 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1703 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1704 getBE().mCompositorTiming.interval = vsyncInterval;
1705 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001706}
1707
Chia-I Wu30505fb2018-03-26 16:20:31 -07001708void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001709{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001710 ATRACE_CALL();
1711 ALOGV("postComposition");
1712
Brian Anderson3546a3f2016-07-14 11:51:14 -07001713 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001714 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001715 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001716 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001717 }
1718
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001719 // |mStateLock| not needed as we are on the main thread
1720 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001721
David Sodman73beded2017-11-15 11:56:06 -08001722 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001723 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001724 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001725 glCompositionDoneFenceTime =
1726 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001727 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001728 } else {
1729 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1730 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001731
David Sodman73beded2017-11-15 11:56:06 -08001732 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001733 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001734 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001735 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001736
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001737 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1738 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1739
Chia-I Wu30505fb2018-03-26 16:20:31 -07001740 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001741 // when we started doing work for this frame, but that should be okay
1742 // since updateCompositorTiming has snapping logic.
1743 updateCompositorTiming(
Chia-I Wu30505fb2018-03-26 16:20:31 -07001744 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001745 CompositorTiming compositorTiming;
1746 {
David Sodman99974d22017-11-28 12:04:33 -08001747 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1748 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001749 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001750
Robert Carr2047fae2016-11-28 14:09:09 -08001751 mDrawingState.traverseInZOrder([&](Layer* layer) {
1752 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001753 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001754 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001755 recordBufferingStats(layer->getName().string(),
1756 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001757 }
Robert Carr2047fae2016-11-28 14:09:09 -08001758 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001759
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001760 if (presentFenceTime->isValid()) {
1761 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001762 enableHardwareVsync();
1763 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001764 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001765 }
1766 }
1767
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001768 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001769 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001770 enableHardwareVsync();
1771 }
1772 }
1773
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001774 if (mAnimCompositionPending) {
1775 mAnimCompositionPending = false;
1776
Brian Anderson4e606e32017-03-16 15:34:57 -07001777 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001778 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001779 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001780 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001781 // The HWC doesn't support present fences, so use the refresh
1782 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001783 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001784 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001785 mAnimFrameTracker.setActualPresentTime(presentTime);
1786 }
1787 mAnimFrameTracker.advanceFrame();
1788 }
Dan Stozab90cf072015-03-05 11:05:59 -08001789
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001790 mTimeStats.incrementTotalFrames();
1791 if (mHadClientComposition) {
1792 mTimeStats.incrementClientCompositionFrames();
1793 }
1794
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001795 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1796 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001797 return;
1798 }
1799
1800 nsecs_t currentTime = systemTime();
1801 if (mHasPoweredOff) {
1802 mHasPoweredOff = false;
1803 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001804 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001805 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001806 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1807 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001808 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001809 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001810 }
David Sodman4a36e932017-11-07 14:29:47 -08001811 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001812 }
David Sodman4a36e932017-11-07 14:29:47 -08001813 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001814}
1815
1816void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001817 ATRACE_CALL();
1818 ALOGV("rebuildLayerStacks");
1819
Mathias Agopiancd60f992012-08-16 16:28:27 -07001820 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001821 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001822 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001823 mVisibleRegionsDirty = false;
1824 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001825
Jeff Sharkey76488112017-02-27 14:15:18 -07001826 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1827 Region opaqueRegion;
1828 Region dirtyRegion;
1829 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001830 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001831 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1832 const Transform& tr(displayDevice->getTransform());
1833 const Rect bounds(displayDevice->getBounds());
1834 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001835 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001836
Jeff Sharkey76488112017-02-27 14:15:18 -07001837 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001838 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001839 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1840 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001841 Region drawRegion(tr.transform(
1842 layer->visibleNonTransparentRegion));
1843 drawRegion.andSelf(bounds);
1844 if (!drawRegion.isEmpty()) {
1845 layersSortedByZ.add(layer);
1846 } else {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001847 // Clear out the HWC layer if this layer was
1848 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001849 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001850 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001851 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001852 } else {
1853 // WM changes displayDevice->layerStack upon sleep/awake.
1854 // Here we make sure we delete the HWC layers even if
1855 // WM changed their layer stack.
1856 hwcLayerDestroyed = layer->destroyHwcLayer(
1857 displayDevice->getHwcDisplayId());
Chia-I Wu83806892017-11-16 10:50:20 -08001858 }
1859
1860 // If a layer is not going to get a release fence because
1861 // it is invisible, but it is also going to release its
1862 // old buffer, add it to the list of layers needing
1863 // fences.
1864 if (hwcLayerDestroyed) {
1865 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1866 mLayersWithQueuedFrames.cend(), layer);
1867 if (found != mLayersWithQueuedFrames.cend()) {
1868 layersNeedingFences.add(layer);
1869 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001870 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001871 });
1872 }
1873 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001874 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001875 displayDevice->undefinedRegion.set(bounds);
1876 displayDevice->undefinedRegion.subtractSelf(
1877 tr.transform(opaqueRegion));
1878 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001879 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001880 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001881}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001882
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001883// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001884// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001885// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001886// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001887// The returned HDR data space is one of
1888// - Dataspace::UNKNOWN
1889// - Dataspace::BT2020_HLG
1890// - Dataspace::BT2020_PQ
1891Dataspace SurfaceFlinger::getBestDataspace(
1892 const sp<const DisplayDevice>& displayDevice, Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001893 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001894 *outHdrDataSpace = Dataspace::UNKNOWN;
1895
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001896 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001897 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001898 case Dataspace::V0_SCRGB:
1899 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001900 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001901 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001902 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001903 case Dataspace::BT2020_PQ:
1904 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001905 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001906 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001907 case Dataspace::BT2020_HLG:
1908 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001909 // When there's mixed PQ content and HLG content, we set the HDR
1910 // data space to be BT2020_PQ and convert HLG to PQ.
1911 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1912 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001913 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001914 break;
1915 default:
1916 break;
1917 }
Romain Guy54f154a2017-10-24 21:40:32 +01001918 }
1919
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001920 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001921}
1922
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001923// Pick the ColorMode / Dataspace for the display device.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001924void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001925 ColorMode* outMode, Dataspace* outDataSpace,
1926 RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001927 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1928 *outMode = ColorMode::NATIVE;
1929 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001930 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001931 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001932 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001933
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001934 Dataspace hdrDataSpace;
1935 Dataspace bestDataSpace = getBestDataspace(displayDevice, &hdrDataSpace);
1936
Chia-I Wu0d711262018-05-21 15:19:35 -07001937 RenderIntent intent;
1938 switch (mDisplayColorSetting) {
1939 case DisplayColorSetting::MANAGED:
1940 case DisplayColorSetting::UNMANAGED:
1941 intent = RenderIntent::COLORIMETRIC;
1942 break;
1943 case DisplayColorSetting::ENHANCED:
1944 intent = RenderIntent::ENHANCE;
1945 break;
1946 default: // vendor display color setting
1947 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1948 break;
1949 }
Chia-I Wube02ec02018-05-18 10:59:36 -07001950
1951 // respect hdrDataSpace only when there is modern HDR support
1952 if (hdrDataSpace != Dataspace::UNKNOWN && displayDevice->hasModernHdrSupport(hdrDataSpace)) {
1953 bestDataSpace = hdrDataSpace;
1954 intent = mDisplayColorSetting == DisplayColorSetting::ENHANCED ?
1955 RenderIntent::TONE_MAP_ENHANCE : RenderIntent::TONE_MAP_COLORIMETRIC;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001956 }
1957
Chia-I Wube02ec02018-05-18 10:59:36 -07001958 displayDevice->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001959}
1960
Chia-I Wu30505fb2018-03-26 16:20:31 -07001961void SurfaceFlinger::setUpHWComposer() {
1962 ATRACE_CALL();
1963 ALOGV("setUpHWComposer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001964
Jesse Hall028dc8f2013-08-20 16:35:32 -07001965 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07001966 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07001967 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1968 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1969
1970 // If nothing has changed (!dirty), don't recompose.
1971 // If something changed, but we don't currently have any visible layers,
1972 // and didn't when we last did a composition, then skip it this time.
1973 // The second rule does two things:
1974 // - When all layers are removed from a display, we'll emit one black
1975 // frame, then nothing more until we get new layers.
1976 // - When a display is created with a private layer stack, we won't
1977 // emit any black frames until a layer is added to the layer stack.
1978 bool mustRecompose = dirty && !(empty && wasEmpty);
1979
Dominik Laskowski281644e2018-04-19 15:47:35 -07001980 ALOGV_IF(mDisplays[dpy]->isVirtual(),
Jesse Hallb7a05492014-08-14 15:45:06 -07001981 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1982 mustRecompose ? "doing" : "skipping",
1983 dirty ? "+" : "-",
1984 empty ? "+" : "-",
1985 wasEmpty ? "+" : "-");
1986
Dan Stoza71433162014-02-04 16:22:36 -08001987 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001988
1989 if (mustRecompose) {
1990 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1991 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001992 }
1993
Chia-I Wu30505fb2018-03-26 16:20:31 -07001994 // build the h/w work list
1995 if (CC_UNLIKELY(mGeometryInvalid)) {
1996 mGeometryInvalid = false;
1997 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1998 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1999 const auto hwcId = displayDevice->getHwcDisplayId();
2000 if (hwcId >= 0) {
2001 const Vector<sp<Layer>>& currentLayers(
2002 displayDevice->getVisibleLayersSortedByZ());
2003 for (size_t i = 0; i < currentLayers.size(); i++) {
2004 const auto& layer = currentLayers[i];
2005 if (!layer->hasHwcLayer(hwcId)) {
2006 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
2007 layer->forceClientComposition(hwcId);
2008 continue;
2009 }
2010 }
2011
2012 layer->setGeometry(displayDevice, i);
2013 if (mDebugDisableHWC || mDebugRegion) {
2014 layer->forceClientComposition(hwcId);
2015 }
2016 }
2017 }
2018 }
2019 }
2020
Chia-I Wu30505fb2018-03-26 16:20:31 -07002021 // Set the per-frame data
2022 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2023 auto& displayDevice = mDisplays[displayId];
2024 const auto hwcId = displayDevice->getHwcDisplayId();
2025
2026 if (hwcId < 0) {
2027 continue;
2028 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07002029 if (mDrawingState.colorMatrixChanged) {
2030 displayDevice->setColorTransform(mDrawingState.colorMatrix);
2031 status_t result = getBE().mHwc->setColorTransform(hwcId, mDrawingState.colorMatrix);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002032 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2033 "display %zd: %d", displayId, result);
2034 }
2035 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002036 if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2037 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002038 !displayDevice->hasHDR10Support()) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07002039 layer->forceClientComposition(hwcId);
2040 }
Chia-I Wu01591c92018-05-22 12:03:00 -07002041 if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2042 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Peiyong Linf59a7192018-04-25 11:19:31 -07002043 !displayDevice->hasHLGSupport()) {
2044 layer->forceClientComposition(hwcId);
2045 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002046
2047 if (layer->getForceClientComposition(hwcId)) {
2048 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2049 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2050 continue;
2051 }
2052
2053 layer->setPerFrameData(displayDevice);
2054 }
2055
2056 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002057 ColorMode colorMode;
2058 Dataspace dataSpace;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002059 RenderIntent renderIntent;
2060 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
2061 setActiveColorModeInternal(displayDevice, colorMode, dataSpace, renderIntent);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002062 }
2063 }
2064
Chia-I Wu28f320b2018-05-03 11:02:56 -07002065 mDrawingState.colorMatrixChanged = false;
Chia-I Wu30505fb2018-03-26 16:20:31 -07002066
Dan Stoza9e56aa02015-11-02 13:00:03 -08002067 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002068 auto& displayDevice = mDisplays[displayId];
2069 if (!displayDevice->isDisplayOn()) {
2070 continue;
2071 }
2072
David Sodman105b7dc2017-11-04 20:28:14 -07002073 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002074 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2075 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002076 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002077}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002078
Mathias Agopiancd60f992012-08-16 16:28:27 -07002079void SurfaceFlinger::doComposition() {
2080 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002081 ALOGV("doComposition");
2082
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002083 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002084 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002085 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002086 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002087 // transform the dirty region into this screen's coordinate space
2088 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002089
2090 // repaint the framebuffer (if needed)
2091 doDisplayComposition(hw, dirtyRegion);
2092
Mathias Agopiancd60f992012-08-16 16:28:27 -07002093 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002094 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002095 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002096 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002097 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002098}
2099
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002100void SurfaceFlinger::postFramebuffer()
2101{
Mathias Agopian841cde52012-03-01 15:44:37 -08002102 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002103 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002104
Mathias Agopiana44b0412011-10-16 18:46:35 -07002105 const nsecs_t now = systemTime();
2106 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002107
Dan Stoza9e56aa02015-11-02 13:00:03 -08002108 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2109 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002110 if (!displayDevice->isDisplayOn()) {
2111 continue;
2112 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002113 const auto hwcId = displayDevice->getHwcDisplayId();
2114 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002115 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002116 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002117 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002118 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002119 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002120 // The layer buffer from the previous frame (if any) is released
2121 // by HWC only when the release fence from this frame (if any) is
2122 // signaled. Always get the release fence from HWC first.
2123 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002124 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002125
2126 // If the layer was client composited in the previous frame, we
2127 // need to merge with the previous client target acquire fence.
2128 // Since we do not track that, always merge with the current
2129 // client target acquire fence when it is available, even though
2130 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002131 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002132 releaseFence = Fence::merge("LayerRelease", releaseFence,
2133 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002134 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002135
David Sodmanb8af7922017-12-21 15:17:55 -08002136 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002137 }
Chia-I Wu83806892017-11-16 10:50:20 -08002138
2139 // We've got a list of layers needing fences, that are disjoint with
2140 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2141 // supply them with the present fence.
2142 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002143 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002144 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002145 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002146 }
2147 }
2148
Dan Stoza9e56aa02015-11-02 13:00:03 -08002149 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002150 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002151 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002152 }
2153
Mathias Agopiana44b0412011-10-16 18:46:35 -07002154 mLastSwapBufferTime = systemTime() - now;
2155 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002156
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002157 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002158 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2159 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2160 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2161 logFrameStats();
2162 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002163 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002164}
2165
Mathias Agopian87baae12012-07-31 12:38:26 -07002166void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002167{
Mathias Agopian841cde52012-03-01 15:44:37 -08002168 ATRACE_CALL();
2169
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002170 // here we keep a copy of the drawing state (that is the state that's
2171 // going to be overwritten by handleTransactionLocked()) outside of
2172 // mStateLock so that the side-effects of the State assignment
2173 // don't happen with mStateLock held (which can cause deadlocks).
2174 State drawingState(mDrawingState);
2175
Mathias Agopianca4d3602011-05-19 15:38:14 -07002176 Mutex::Autolock _l(mStateLock);
2177 const nsecs_t now = systemTime();
2178 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002179
Mathias Agopianca4d3602011-05-19 15:38:14 -07002180 // Here we're guaranteed that some transaction flags are set
2181 // so we can call handleTransactionLocked() unconditionally.
2182 // We call getTransactionFlags(), which will also clear the flags,
2183 // with mStateLock held to guarantee that mCurrentState won't change
2184 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002185
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002186 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002187 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002188 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002189
Mathias Agopianca4d3602011-05-19 15:38:14 -07002190 mLastTransactionTime = systemTime() - now;
2191 mDebugInTransaction = 0;
2192 invalidateHwcGeometry();
2193 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002194}
2195
Lloyd Pique715a2c12017-12-14 17:18:08 -08002196DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002197 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002198 // Figure out whether the event is for the primary display or an
2199 // external display by matching the Hwc display id against one for a
2200 // connected display. If we did not find a match, we then check what
2201 // displays are not already connected to determine the type. If we don't
2202 // have a connected primary display, we assume the new display is meant to
2203 // be the primary display, and then if we don't have an external display,
2204 // we assume it is that.
2205 const auto primaryDisplayId =
2206 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2207 const auto externalDisplayId =
2208 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2209 if (primaryDisplayId && primaryDisplayId == display) {
2210 return DisplayDevice::DISPLAY_PRIMARY;
2211 } else if (externalDisplayId && externalDisplayId == display) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002212 return DisplayDevice::DISPLAY_EXTERNAL;
Lloyd Pique715a2c12017-12-14 17:18:08 -08002213 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2214 return DisplayDevice::DISPLAY_PRIMARY;
2215 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2216 return DisplayDevice::DISPLAY_EXTERNAL;
2217 }
2218
2219 return DisplayDevice::DISPLAY_ID_INVALID;
2220}
2221
Lloyd Piqueba04e622017-12-14 17:11:26 -08002222void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2223 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002224 auto displayType = determineDisplayType(event.display, event.connection);
2225 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2226 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2227 continue;
2228 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002229
2230 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2231 ALOGE("External displays are not supported by the vr hardware composer.");
2232 continue;
2233 }
2234
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002235 const auto displayId =
2236 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
2237 if (displayId) {
2238 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.display, *displayId);
2239 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002240
2241 if (event.connection == HWC2::Connection::Connected) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002242 if (!mBuiltinDisplays[displayType].get()) {
2243 ALOGV("Creating built in display %d", displayType);
2244 mBuiltinDisplays[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002245 DisplayDeviceState info;
2246 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002247 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2248 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002249 info.isSecure = true; // All physical displays are currently considered secure.
Steven Thomaseb6d2052018-03-20 15:40:48 -07002250 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
2251 mInterceptor->saveDisplayCreation(info);
2252 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002253 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002254 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002255
Lloyd Piquefcd86612017-12-14 17:15:36 -08002256 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2257 if (idx >= 0) {
2258 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002259 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002260 mCurrentState.displays.removeItemsAt(idx);
2261 }
2262 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002263 }
2264
2265 processDisplayChangesLocked();
2266 }
2267
2268 mPendingHotplugEvents.clear();
2269}
2270
Lloyd Pique99d3da52018-01-22 17:48:03 -08002271sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2272 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2273 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002274 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002275 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002276
Lloyd Pique99d3da52018-01-22 17:48:03 -08002277 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002278 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002279 for (ColorMode colorMode : modes) {
2280 switch (colorMode) {
2281 case ColorMode::DISPLAY_P3:
2282 case ColorMode::ADOBE_RGB:
2283 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002284 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002285 break;
2286 default:
2287 break;
2288 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002289
2290 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2291 colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002292 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002293 }
2294 }
2295
Peiyong Lin62665892018-04-16 11:07:44 -07002296 HdrCapabilities hdrCapabilities;
2297 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002298
2299 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2300 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2301
2302 /*
2303 * Create our display's surface
2304 */
2305 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2306 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002307 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002308 renderSurface->setNativeWindow(nativeWindow.get());
2309 const int displayWidth = renderSurface->queryWidth();
2310 const int displayHeight = renderSurface->queryHeight();
2311
2312 // Make sure that composition can never be stalled by a virtual display
2313 // consumer that isn't processing buffers fast enough. We have to do this
2314 // in two places:
2315 // * Here, in case the display is composed entirely by HWC.
2316 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2317 // window's swap interval in eglMakeCurrent, so they'll override the
2318 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002319 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002320 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2321 }
2322
2323 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002324 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002325
2326 sp<DisplayDevice> hw =
2327 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2328 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin0ac5f4e2018-04-19 22:06:34 -07002329 hasWideColorGamut, hdrCapabilities,
2330 getHwComposer().getSupportedPerFrameMetadata(hwcId),
Chia-I Wube02ec02018-05-18 10:59:36 -07002331 hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002332
2333 if (maxFrameBufferAcquiredBuffers >= 3) {
2334 nativeWindowSurface->preallocateBuffers();
2335 }
2336
2337 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002338 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2339 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002340 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002341 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002342 }
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002343 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace,
2344 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002345 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
2346 hw->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
2347 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002348 hw->setLayerStack(state.layerStack);
2349 hw->setProjection(state.orientation, state.viewport, state.frame);
2350 hw->setDisplayName(state.displayName);
2351
2352 return hw;
2353}
2354
Lloyd Pique347200f2017-12-14 17:00:15 -08002355void SurfaceFlinger::processDisplayChangesLocked() {
2356 // here we take advantage of Vector's copy-on-write semantics to
2357 // improve performance by skipping the transaction entirely when
2358 // know that the lists are identical
2359 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2360 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2361 if (!curr.isIdenticalTo(draw)) {
2362 mVisibleRegionsDirty = true;
2363 const size_t cc = curr.size();
2364 size_t dc = draw.size();
2365
2366 // find the displays that were removed
2367 // (ie: in drawing state but not in current state)
2368 // also handle displays that changed
2369 // (ie: displays that are in both lists)
2370 for (size_t i = 0; i < dc;) {
2371 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2372 if (j < 0) {
2373 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002374 // Call makeCurrent() on the primary display so we can
2375 // be sure that nothing associated with this display
2376 // is current.
2377 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2378 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2379 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2380 if (hw != nullptr) hw->disconnect(getHwComposer());
2381 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2382 mEventThread->onHotplugReceived(draw[i].type, false);
2383 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002384 } else {
2385 // this display is in both lists. see if something changed.
2386 const DisplayDeviceState& state(curr[j]);
2387 const wp<IBinder>& display(curr.keyAt(j));
2388 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2389 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2390 if (state_binder != draw_binder) {
2391 // changing the surface is like destroying and
2392 // recreating the DisplayDevice, so we just remove it
2393 // from the drawing state, so that it get re-added
2394 // below.
2395 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2396 if (hw != nullptr) hw->disconnect(getHwComposer());
2397 mDisplays.removeItem(display);
2398 mDrawingState.displays.removeItemsAt(i);
2399 dc--;
2400 // at this point we must loop to the next item
2401 continue;
2402 }
2403
2404 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2405 if (disp != nullptr) {
2406 if (state.layerStack != draw[i].layerStack) {
2407 disp->setLayerStack(state.layerStack);
2408 }
2409 if ((state.orientation != draw[i].orientation) ||
2410 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2411 disp->setProjection(state.orientation, state.viewport, state.frame);
2412 }
2413 if (state.width != draw[i].width || state.height != draw[i].height) {
2414 disp->setDisplaySize(state.width, state.height);
2415 }
2416 }
2417 }
2418 ++i;
2419 }
2420
2421 // find displays that were added
2422 // (ie: in current state but not in drawing state)
2423 for (size_t i = 0; i < cc; i++) {
2424 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2425 const DisplayDeviceState& state(curr[i]);
2426
2427 sp<DisplaySurface> dispSurface;
2428 sp<IGraphicBufferProducer> producer;
2429 sp<IGraphicBufferProducer> bqProducer;
2430 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002431 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002432
2433 int32_t hwcId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002434 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002435 // Virtual displays without a surface are dormant:
2436 // they have external state (layer stack, projection,
2437 // etc.) but no internal state (i.e. a DisplayDevice).
2438 if (state.surface != nullptr) {
2439 // Allow VR composer to use virtual displays.
2440 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2441 int width = 0;
2442 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2443 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2444 int height = 0;
2445 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2446 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2447 int intFormat = 0;
2448 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2449 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002450 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002451
2452 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2453 }
2454
2455 // TODO: Plumb requested format back up to consumer
2456
2457 sp<VirtualDisplaySurface> vds =
2458 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2459 bqProducer, bqConsumer,
2460 state.displayName);
2461
2462 dispSurface = vds;
2463 producer = vds;
2464 }
2465 } else {
2466 ALOGE_IF(state.surface != nullptr,
2467 "adding a supported display, but rendering "
2468 "surface is provided (%p), ignoring it",
2469 state.surface.get());
2470
2471 hwcId = state.type;
2472 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2473 producer = bqProducer;
2474 }
2475
2476 const wp<IBinder>& display(curr.keyAt(i));
2477 if (dispSurface != nullptr) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002478 mDisplays.add(display,
2479 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2480 producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002481 if (!state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002482 mEventThread->onHotplugReceived(state.type, true);
2483 }
2484 }
2485 }
2486 }
2487 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002488
2489 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002490}
2491
Mathias Agopian87baae12012-07-31 12:38:26 -07002492void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002493{
Dan Stoza7dde5992015-05-22 09:51:44 -07002494 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002495 mCurrentState.traverseInZOrder([](Layer* layer) {
2496 layer->notifyAvailableFrames();
2497 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002498
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002499 /*
2500 * Traversal of the children
2501 * (perform the transaction for each of them if needed)
2502 */
2503
Mathias Agopian3559b072012-08-15 13:46:03 -07002504 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002505 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002506 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002507 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002508
2509 const uint32_t flags = layer->doTransaction(0);
2510 if (flags & Layer::eVisibleRegion)
2511 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002512 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002513 }
2514
2515 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002516 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002517 */
2518
Mathias Agopiane57f2922012-08-09 16:29:12 -07002519 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002520 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002521 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002522 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002523
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002524 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002525 // The transform hint might have changed for some layers
2526 // (either because a display has changed, or because a layer
2527 // as changed).
2528 //
2529 // Walk through all the layers in currentLayers,
2530 // and update their transform hint.
2531 //
2532 // If a layer is visible only on a single display, then that
2533 // display is used to calculate the hint, otherwise we use the
2534 // default display.
2535 //
2536 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2537 // the hint is set before we acquire a buffer from the surface texture.
2538 //
2539 // NOTE: layer transactions have taken place already, so we use their
2540 // drawing state. However, SurfaceFlinger's own transaction has not
2541 // happened yet, so we must use the current state layer list
2542 // (soon to become the drawing state list).
2543 //
2544 sp<const DisplayDevice> disp;
2545 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002546 bool first = true;
2547 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002548 // NOTE: we rely on the fact that layers are sorted by
2549 // layerStack first (so we don't have to traverse the list
2550 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002551 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002552 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002553 currentlayerStack = layerStack;
2554 // figure out if this layerstack is mirrored
2555 // (more than one display) if so, pick the default display,
2556 // if not, pick the only display it's on.
2557 disp.clear();
2558 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2559 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002560 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002561 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002562 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002563 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002564 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002565 break;
2566 }
2567 }
2568 }
2569 }
Chet Haase91d25932013-04-11 15:24:55 -07002570
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002571 if (disp == nullptr) {
2572 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2573 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002574
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002575 // could be null when this layer is using a layerStack
2576 // that is not visible on any display. Also can occur at
2577 // screen off/on times.
2578 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002579 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002580
2581 // disp can be null if there is no display available at all to get
2582 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002583 if (disp != nullptr) {
2584 layer->updateTransformHint(disp);
2585 }
Robert Carr2047fae2016-11-28 14:09:09 -08002586
2587 first = false;
2588 });
Mathias Agopian84300952012-11-21 16:02:13 -08002589 }
2590
2591
Mathias Agopian3559b072012-08-15 13:46:03 -07002592 /*
2593 * Perform our own transaction if needed
2594 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002595
2596 if (mLayersAdded) {
2597 mLayersAdded = false;
2598 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002599 mVisibleRegionsDirty = true;
2600 }
2601
2602 // some layers might have been removed, so
2603 // we need to update the regions they're exposing.
2604 if (mLayersRemoved) {
2605 mLayersRemoved = false;
2606 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002607 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002608 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002609 // this layer is not visible anymore
2610 // TODO: we could traverse the tree from front to back and
2611 // compute the actual visible region
2612 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002613 Region visibleReg;
2614 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002615 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002616 }
Robert Carr2047fae2016-11-28 14:09:09 -08002617 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002618 }
2619
2620 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002621
2622 updateCursorAsync();
2623}
2624
2625void SurfaceFlinger::updateCursorAsync()
2626{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002627 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2628 auto& displayDevice = mDisplays[displayId];
2629 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002630 continue;
2631 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002632
2633 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2634 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002635 }
2636 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002637}
2638
2639void SurfaceFlinger::commitTransaction()
2640{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002641 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002642 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002643 for (const auto& l : mLayersPendingRemoval) {
2644 recordBufferingStats(l->getName().string(),
2645 l->getOccupancyHistory(true));
2646 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002647 }
2648 mLayersPendingRemoval.clear();
2649 }
2650
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002651 // If this transaction is part of a window animation then the next frame
2652 // we composite should be considered an animation as well.
2653 mAnimCompositionPending = mAnimTransactionPending;
2654
Mathias Agopian4fec8732012-06-29 14:12:52 -07002655 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002656 // clear the "changed" flags in current state
2657 mCurrentState.colorMatrixChanged = false;
2658
Robert Carr1f0a16a2016-10-24 16:27:39 -07002659 mDrawingState.traverseInZOrder([](Layer* layer) {
2660 layer->commitChildList();
2661 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002662 mTransactionPending = false;
2663 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002664 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002665}
2666
Chia-I Wuab0c3192017-08-01 11:29:00 -07002667void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002668 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002669{
Mathias Agopian841cde52012-03-01 15:44:37 -08002670 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002671 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002672
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002673 Region aboveOpaqueLayers;
2674 Region aboveCoveredLayers;
2675 Region dirty;
2676
Mathias Agopian87baae12012-07-31 12:38:26 -07002677 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002678
Robert Carr2047fae2016-11-28 14:09:09 -08002679 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002680 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002681 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002682
Jesse Hall01e29052013-02-19 16:13:35 -08002683 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002684 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002685 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002686
Mathias Agopianab028732010-03-16 16:41:46 -07002687 /*
2688 * opaqueRegion: area of a surface that is fully opaque.
2689 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002690 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002691
2692 /*
2693 * visibleRegion: area of a surface that is visible on screen
2694 * and not fully transparent. This is essentially the layer's
2695 * footprint minus the opaque regions above it.
2696 * Areas covered by a translucent surface are considered visible.
2697 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002698 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002699
2700 /*
2701 * coveredRegion: area of a surface that is covered by all
2702 * visible regions above it (which includes the translucent areas).
2703 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002704 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002705
Jesse Halla8026d22012-09-25 13:25:04 -07002706 /*
2707 * transparentRegion: area of a surface that is hinted to be completely
2708 * transparent. This is only used to tell when the layer has no visible
2709 * non-transparent regions and can be removed from the layer list. It
2710 * does not affect the visibleRegion of this layer or any layers
2711 * beneath it. The hint may not be correct if apps don't respect the
2712 * SurfaceView restrictions (which, sadly, some don't).
2713 */
2714 Region transparentRegion;
2715
Mathias Agopianab028732010-03-16 16:41:46 -07002716
2717 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002718 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002719 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002720 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002721 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002722 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002723 if (!visibleRegion.isEmpty()) {
2724 // Remove the transparent area from the visible region
2725 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002726 if (tr.preserveRects()) {
2727 // transform the transparent region
2728 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002729 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002730 // transformation too complex, can't do the
2731 // transparent region optimization.
2732 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002733 }
Mathias Agopianab028732010-03-16 16:41:46 -07002734 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002735
Mathias Agopianab028732010-03-16 16:41:46 -07002736 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002737 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002738 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002739 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2740 // the opaque region is the layer's footprint
2741 opaqueRegion = visibleRegion;
2742 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002743 }
2744 }
2745
Robert Carre5f4f692018-01-12 13:12:28 -08002746 if (visibleRegion.isEmpty()) {
2747 layer->clearVisibilityRegions();
2748 return;
2749 }
2750
Mathias Agopianab028732010-03-16 16:41:46 -07002751 // Clip the covered region to the visible region
2752 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2753
2754 // Update aboveCoveredLayers for next (lower) layer
2755 aboveCoveredLayers.orSelf(visibleRegion);
2756
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002757 // subtract the opaque region covered by the layers above us
2758 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002759
2760 // compute this layer's dirty region
2761 if (layer->contentDirty) {
2762 // we need to invalidate the whole region
2763 dirty = visibleRegion;
2764 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002765 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002766 layer->contentDirty = false;
2767 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002768 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002769 * the exposed region consists of two components:
2770 * 1) what's VISIBLE now and was COVERED before
2771 * 2) what's EXPOSED now less what was EXPOSED before
2772 *
2773 * note that (1) is conservative, we start with the whole
2774 * visible region but only keep what used to be covered by
2775 * something -- which mean it may have been exposed.
2776 *
2777 * (2) handles areas that were not covered by anything but got
2778 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002779 */
Mathias Agopianab028732010-03-16 16:41:46 -07002780 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002781 const Region oldVisibleRegion = layer->visibleRegion;
2782 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002783 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2784 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002785 }
2786 dirty.subtractSelf(aboveOpaqueLayers);
2787
2788 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002789 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002790
Mathias Agopianab028732010-03-16 16:41:46 -07002791 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002792 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002793
Jesse Halla8026d22012-09-25 13:25:04 -07002794 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002795 layer->setVisibleRegion(visibleRegion);
2796 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002797 layer->setVisibleNonTransparentRegion(
2798 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002799 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002800
Mathias Agopian87baae12012-07-31 12:38:26 -07002801 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002802}
2803
Chia-I Wuab0c3192017-08-01 11:29:00 -07002804void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002805 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002806 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002807 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002808 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002809 }
2810 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002811}
2812
Dan Stoza6b9454d2014-11-07 16:00:59 -08002813bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002814{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002815 ALOGV("handlePageFlip");
2816
Brian Andersond6927fb2016-07-23 23:37:30 -07002817 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002818
Mathias Agopian4fec8732012-06-29 14:12:52 -07002819 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002820 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002821 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002822
2823 // Store the set of layers that need updates. This set must not change as
2824 // buffers are being latched, as this could result in a deadlock.
2825 // Example: Two producers share the same command stream and:
2826 // 1.) Layer 0 is latched
2827 // 2.) Layer 0 gets a new frame
2828 // 2.) Layer 1 gets a new frame
2829 // 3.) Layer 1 is latched.
2830 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2831 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002832 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002833 if (layer->hasQueuedFrame()) {
2834 frameQueued = true;
2835 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002836 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002837 } else {
2838 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002839 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002840 } else {
2841 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002842 }
Robert Carr2047fae2016-11-28 14:09:09 -08002843 });
2844
Dan Stoza9e56aa02015-11-02 13:00:03 -08002845 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002846 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002847 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002848 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002849 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002850 newDataLatched = true;
2851 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002852 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002853
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002854 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002855
2856 // If we will need to wake up at some time in the future to deal with a
2857 // queued frame that shouldn't be displayed during this vsync period, wake
2858 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002859 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002860 signalLayerUpdate();
2861 }
2862
2863 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002864 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002865}
2866
Mathias Agopianad456f92011-01-13 17:53:01 -08002867void SurfaceFlinger::invalidateHwcGeometry()
2868{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002869 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002870}
2871
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002872
Fabien Sanglard830b8472016-11-30 16:35:58 -08002873void SurfaceFlinger::doDisplayComposition(
2874 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002875 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002876{
Dan Stoza71433162014-02-04 16:22:36 -08002877 // We only need to actually compose the display if:
2878 // 1) It is being handled by hardware composer, which may need this to
2879 // keep its virtual display state machine in sync, or
2880 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002881 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002882 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002883 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002884 return;
2885 }
2886
Dan Stoza9e56aa02015-11-02 13:00:03 -08002887 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002888 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002889
2890 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002891 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002892}
2893
Chia-I Wub02087d2017-11-09 10:19:54 -08002894bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002895{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002896 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002897
Chia-I Wub02087d2017-11-09 10:19:54 -08002898 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002899 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002900 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002901 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002902 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002903
Chia-I Wu8e50e692018-05-04 10:12:37 -07002904 bool applyColorMatrix = false;
Peiyong Lin00f9c022018-05-09 15:35:33 -07002905 bool needsLegacyColorMatrix = false;
2906 bool legacyColorMatrixApplied = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002907
Dan Stoza9e56aa02015-11-02 13:00:03 -08002908 if (hasClientComposition) {
2909 ALOGV("hasClientComposition");
2910
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002911 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002912 if (displayDevice->hasWideColorGamut()) {
2913 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002914 }
2915 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002916 getBE().mRenderEngine->setDisplayMaxLuminance(
2917 displayDevice->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002918
Chia-I Wu8e50e692018-05-04 10:12:37 -07002919 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2920 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2921 HWC2::Capability::SkipClientColorTransform);
2922
2923 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2924 if (applyColorMatrix) {
Peiyong Lin00f9c022018-05-09 15:35:33 -07002925 getRenderEngine().setupColorTransform(mDrawingState.colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002926 }
2927
Chia-I Wubbb44462018-05-21 15:33:27 -07002928 needsLegacyColorMatrix =
Chia-I Wu0d711262018-05-21 15:19:35 -07002929 (displayDevice->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
Chia-I Wubbb44462018-05-21 15:33:27 -07002930 outputDataspace != Dataspace::UNKNOWN &&
2931 outputDataspace != Dataspace::SRGB);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002932
Chia-I Wu7f402902017-11-09 12:51:10 -08002933 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002934 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskibf170d92018-04-19 15:08:05 -07002935 displayDevice->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002936 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002937
2938 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002939 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002940 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2941 }
2942 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002943 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002944
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002945 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002946 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002947 // when using overlays, we assume a fully transparent framebuffer
2948 // NOTE: we could reduce how much we need to clear, for instance
2949 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002950 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002951 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002952 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002953 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002954 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002955 // we're left with the letterbox region
2956 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002957 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002958
2959 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002960 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002961
Mathias Agopianb9494d52012-04-18 02:28:45 -07002962 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002963 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002964 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002965 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002966 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002967 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002968
Dominik Laskowski281644e2018-04-19 15:47:35 -07002969 if (!displayDevice->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002970 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002971 // scissor on the main display. It should never be needed
2972 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002973 const Rect& bounds(displayDevice->getBounds());
2974 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002975 if (scissor != bounds) {
2976 // scissor doesn't match the screen's dimensions, so we
2977 // need to clear everything outside of it and enable
2978 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002979
Mathias Agopianf45c5102012-10-24 16:29:17 -07002980 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002981 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002982 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002983 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002984 }
2985 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002986 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002987
Mathias Agopian85d751c2012-08-29 16:59:24 -07002988 /*
2989 * and then, render the layers targeted at the framebuffer
2990 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002991
Dan Stoza9e56aa02015-11-02 13:00:03 -08002992 ALOGV("Rendering client layers");
2993 const Transform& displayTransform = displayDevice->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002994 bool firstLayer = true;
2995 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2996 const Region clip(bounds.intersect(
2997 displayTransform.transform(layer->visibleRegion)));
2998 ALOGV("Layer: %s", layer->getName().string());
2999 ALOGV(" Composition type: %s",
3000 to_string(layer->getCompositionType(hwcId)).c_str());
3001 if (!clip.isEmpty()) {
3002 switch (layer->getCompositionType(hwcId)) {
3003 case HWC2::Composition::Cursor:
3004 case HWC2::Composition::Device:
3005 case HWC2::Composition::Sideband:
3006 case HWC2::Composition::SolidColor: {
3007 const Layer::State& state(layer->getDrawingState());
3008 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
3009 layer->isOpaque(state) && (state.color.a == 1.0f)
3010 && hasClientComposition) {
3011 // never clear the very first layer since we're
3012 // guaranteed the FB is already cleared
3013 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003014 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003015 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003016 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003017 case HWC2::Composition::Client: {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003018 // switch color matrices lazily
Peiyong Lin00f9c022018-05-09 15:35:33 -07003019 if (layer->isLegacyDataSpace() && needsLegacyColorMatrix) {
3020 if (!legacyColorMatrixApplied) {
3021 getRenderEngine().setSaturationMatrix(mLegacySrgbSaturationMatrix);
3022 legacyColorMatrixApplied = true;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003023 }
Peiyong Lin00f9c022018-05-09 15:35:33 -07003024 } else if (legacyColorMatrixApplied) {
3025 getRenderEngine().setSaturationMatrix(mat4());
3026 legacyColorMatrixApplied = false;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003027 }
Chia-I Wu8e50e692018-05-04 10:12:37 -07003028
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003029 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003030 break;
3031 }
3032 default:
3033 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003034 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003035 } else {
3036 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003037 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003038 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003039 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003040
Peiyong Lin00f9c022018-05-09 15:35:33 -07003041 if (applyColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003042 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003043 }
Peiyong Lin00f9c022018-05-09 15:35:33 -07003044 if (needsLegacyColorMatrix && legacyColorMatrixApplied) {
3045 getRenderEngine().setSaturationMatrix(mat4());
3046 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003047
Mathias Agopianf45c5102012-10-24 16:29:17 -07003048 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003049 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003050 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003051}
3052
Fabien Sanglard830b8472016-11-30 16:35:58 -08003053void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3054 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003055 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003056 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003057}
3058
Dan Stoza7d89d062015-04-30 13:29:25 -07003059status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003060 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003061 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003062 const sp<Layer>& lbc,
3063 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003064{
Dan Stoza7d89d062015-04-30 13:29:25 -07003065 // add this layer to the current state list
3066 {
3067 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003068 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003069 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3070 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003071 return NO_MEMORY;
3072 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003073 if (parent == nullptr) {
3074 mCurrentState.layersSortedByZ.add(lbc);
3075 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003076 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003077 ALOGE("addClientLayer called with a removed parent");
3078 return NAME_NOT_FOUND;
3079 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003080 parent->addChild(lbc);
3081 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003082
Yiwei Zhang243b3782018-05-15 17:40:04 -07003083 if (gbc != nullptr) {
3084 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3085 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3086 mMaxGraphicBufferProducerListSize,
3087 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3088 mGraphicBufferProducerList.size(),
3089 mMaxGraphicBufferProducerListSize, mNumLayers);
3090 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003091 mLayersAdded = true;
3092 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003093 }
3094
Mathias Agopian96f08192010-06-02 23:28:45 -07003095 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003096 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003097
Dan Stoza7d89d062015-04-30 13:29:25 -07003098 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003099}
3100
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003101status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003102 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003103 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3104}
Robert Carr7f9b8992017-03-10 11:08:39 -08003105
chaviwca27f252018-02-06 16:46:39 -08003106status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3107 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003108 if (layer->isPendingRemoval()) {
3109 return NO_ERROR;
3110 }
3111
Robert Carr1f0a16a2016-10-24 16:27:39 -07003112 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003113 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003114 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003115 if (topLevelOnly) {
3116 return NO_ERROR;
3117 }
3118
Chia-I Wu98f1c102017-05-30 14:54:08 -07003119 sp<Layer> ancestor = p;
3120 while (ancestor->getParent() != nullptr) {
3121 ancestor = ancestor->getParent();
3122 }
3123 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3124 ALOGE("removeLayer called with a layer whose parent has been removed");
3125 return NAME_NOT_FOUND;
3126 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003127
3128 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003129 } else {
3130 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003131 }
3132
Robert Carr136e2f62017-02-08 17:54:29 -08003133 // As a matter of normal operation, the LayerCleaner will produce a second
3134 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3135 // so we will succeed in promoting it, but it's already been removed
3136 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3137 // otherwise something has gone wrong and we are leaking the layer.
3138 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003139 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3140 layer->getName().string(),
3141 (p != nullptr) ? p->getName().string() : "no-parent");
3142 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003143 } else if (index < 0) {
3144 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003145 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003146
Chia-I Wuc6657022017-08-15 11:18:17 -07003147 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003148 mLayersPendingRemoval.add(layer);
3149 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003150 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003151 setTransactionFlags(eTransactionNeeded);
3152 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003153}
3154
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003155uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003156 return android_atomic_release_load(&mTransactionFlags);
3157}
3158
Mathias Agopian3f844832013-08-07 21:24:32 -07003159uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003160 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3161}
3162
Mathias Agopian3f844832013-08-07 21:24:32 -07003163uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003164 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3165}
3166
3167uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3168 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003169 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003170 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003171 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003172 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003173 }
3174 return old;
3175}
3176
chaviwca27f252018-02-06 16:46:39 -08003177bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3178 for (const ComposerState& state : states) {
3179 // Here we need to check that the interface we're given is indeed
3180 // one of our own. A malicious client could give us a nullptr
3181 // IInterface, or one of its own or even one of our own but a
3182 // different type. All these situations would cause us to crash.
3183 if (state.client == nullptr) {
3184 return true;
3185 }
3186
3187 sp<IBinder> binder = IInterface::asBinder(state.client);
3188 if (binder == nullptr) {
3189 return true;
3190 }
3191
3192 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3193 return true;
3194 }
3195 }
3196 return false;
3197}
3198
Mathias Agopian8b33f032012-07-24 20:43:54 -07003199void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003200 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003201 const Vector<DisplayState>& displays,
3202 uint32_t flags)
3203{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003204 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003205 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003206 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003207
chaviwca27f252018-02-06 16:46:39 -08003208 if (containsAnyInvalidClientState(states)) {
3209 return;
3210 }
3211
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003212 if (flags & eAnimation) {
3213 // For window updates that are part of an animation we must wait for
3214 // previous animation "frames" to be handled.
3215 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003216 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003217 if (CC_UNLIKELY(err != NO_ERROR)) {
3218 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003219 // caller after a few seconds.
3220 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3221 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003222 mAnimTransactionPending = false;
3223 break;
3224 }
3225 }
3226 }
3227
chaviwca27f252018-02-06 16:46:39 -08003228 for (const DisplayState& display : displays) {
3229 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003230 }
3231
chaviwca27f252018-02-06 16:46:39 -08003232 for (const ComposerState& state : states) {
3233 transactionFlags |= setClientStateLocked(state);
3234 }
3235
3236 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3237 // as destroyed should only occur after setting all other states. This is to allow for a
3238 // child re-parent to happen before marking its original parent as destroyed (which would
3239 // then mark the child as destroyed).
3240 for (const ComposerState& state : states) {
3241 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003242 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003243
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003244 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3245 // anyway. This can be used as a flush mechanism for previous async transactions.
3246 // Empty animation transaction can be used to simulate back-pressure, so also force a
3247 // transaction for empty animation transactions.
3248 if (transactionFlags == 0 &&
3249 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003250 transactionFlags = eTransactionNeeded;
3251 }
3252
Mathias Agopian386aa982011-11-07 21:58:03 -08003253 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003254 if (mInterceptor->isEnabled()) {
3255 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003256 }
Irvel468051e2016-06-13 16:44:44 -07003257
Mathias Agopian386aa982011-11-07 21:58:03 -08003258 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003259 const auto start = (flags & eEarlyWakeup)
3260 ? VSyncModulator::TransactionStart::EARLY
3261 : VSyncModulator::TransactionStart::NORMAL;
3262 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003263
3264 // if this is a synchronous transaction, wait for it to take effect
3265 // before returning.
3266 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003267 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003268 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003269 if (flags & eAnimation) {
3270 mAnimTransactionPending = true;
3271 }
3272 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003273 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3274 if (CC_UNLIKELY(err != NO_ERROR)) {
3275 // just in case something goes wrong in SF, return to the
3276 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003277 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3278 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003279 break;
3280 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003281 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003282 }
3283}
3284
Mathias Agopiane57f2922012-08-09 16:29:12 -07003285uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3286{
Jesse Hall9a143922012-10-04 16:29:19 -07003287 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3288 if (dpyIdx < 0)
3289 return 0;
3290
Mathias Agopiane57f2922012-08-09 16:29:12 -07003291 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003292 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003293 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003294 const uint32_t what = s.what;
3295 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003296 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003297 disp.surface = s.surface;
3298 flags |= eDisplayTransactionNeeded;
3299 }
3300 }
3301 if (what & DisplayState::eLayerStackChanged) {
3302 if (disp.layerStack != s.layerStack) {
3303 disp.layerStack = s.layerStack;
3304 flags |= eDisplayTransactionNeeded;
3305 }
3306 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003307 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003308 if (disp.orientation != s.orientation) {
3309 disp.orientation = s.orientation;
3310 flags |= eDisplayTransactionNeeded;
3311 }
3312 if (disp.frame != s.frame) {
3313 disp.frame = s.frame;
3314 flags |= eDisplayTransactionNeeded;
3315 }
3316 if (disp.viewport != s.viewport) {
3317 disp.viewport = s.viewport;
3318 flags |= eDisplayTransactionNeeded;
3319 }
3320 }
Michael Lentine47e45402014-07-18 15:34:25 -07003321 if (what & DisplayState::eDisplaySizeChanged) {
3322 if (disp.width != s.width) {
3323 disp.width = s.width;
3324 flags |= eDisplayTransactionNeeded;
3325 }
3326 if (disp.height != s.height) {
3327 disp.height = s.height;
3328 flags |= eDisplayTransactionNeeded;
3329 }
3330 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003331 }
3332 return flags;
3333}
3334
chaviwca27f252018-02-06 16:46:39 -08003335uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3336 const layer_state_t& s = composerState.state;
3337 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3338
Mathias Agopian13127d82013-03-05 17:47:11 -08003339 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003340 if (layer == nullptr) {
3341 return 0;
3342 }
3343
3344 if (layer->isPendingRemoval()) {
3345 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3346 return 0;
3347 }
3348
3349 uint32_t flags = 0;
3350
3351 const uint32_t what = s.what;
3352 bool geometryAppliesWithResize =
3353 what & layer_state_t::eGeometryAppliesWithResize;
3354 if (what & layer_state_t::ePositionChanged) {
3355 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3356 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003357 }
chaviw8b3871a2017-11-01 17:41:01 -07003358 }
3359 if (what & layer_state_t::eLayerChanged) {
3360 // NOTE: index needs to be calculated before we update the state
3361 const auto& p = layer->getParent();
3362 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003363 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003364 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003365 mCurrentState.layersSortedByZ.removeAt(idx);
3366 mCurrentState.layersSortedByZ.add(layer);
3367 // we need traversal (state changed)
3368 // AND transaction (list changed)
3369 flags |= eTransactionNeeded|eTraversalNeeded;
3370 }
chaviw8b3871a2017-11-01 17:41:01 -07003371 } else {
3372 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003373 flags |= eTransactionNeeded|eTraversalNeeded;
3374 }
3375 }
chaviw8b3871a2017-11-01 17:41:01 -07003376 }
3377 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003378 // NOTE: index needs to be calculated before we update the state
3379 const auto& p = layer->getParent();
3380 if (p == nullptr) {
3381 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3382 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3383 mCurrentState.layersSortedByZ.removeAt(idx);
3384 mCurrentState.layersSortedByZ.add(layer);
3385 // we need traversal (state changed)
3386 // AND transaction (list changed)
3387 flags |= eTransactionNeeded|eTraversalNeeded;
3388 }
3389 } else {
3390 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3391 flags |= eTransactionNeeded|eTraversalNeeded;
3392 }
chaviw8b3871a2017-11-01 17:41:01 -07003393 }
3394 }
3395 if (what & layer_state_t::eSizeChanged) {
3396 if (layer->setSize(s.w, s.h)) {
3397 flags |= eTraversalNeeded;
3398 }
3399 }
3400 if (what & layer_state_t::eAlphaChanged) {
3401 if (layer->setAlpha(s.alpha))
3402 flags |= eTraversalNeeded;
3403 }
3404 if (what & layer_state_t::eColorChanged) {
3405 if (layer->setColor(s.color))
3406 flags |= eTraversalNeeded;
3407 }
3408 if (what & layer_state_t::eMatrixChanged) {
3409 if (layer->setMatrix(s.matrix))
3410 flags |= eTraversalNeeded;
3411 }
3412 if (what & layer_state_t::eTransparentRegionChanged) {
3413 if (layer->setTransparentRegionHint(s.transparentRegion))
3414 flags |= eTraversalNeeded;
3415 }
3416 if (what & layer_state_t::eFlagsChanged) {
3417 if (layer->setFlags(s.flags, s.mask))
3418 flags |= eTraversalNeeded;
3419 }
3420 if (what & layer_state_t::eCropChanged) {
3421 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3422 flags |= eTraversalNeeded;
3423 }
3424 if (what & layer_state_t::eFinalCropChanged) {
3425 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3426 flags |= eTraversalNeeded;
3427 }
3428 if (what & layer_state_t::eLayerStackChanged) {
3429 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3430 // We only allow setting layer stacks for top level layers,
3431 // everything else inherits layer stack from its parent.
3432 if (layer->hasParent()) {
3433 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3434 layer->getName().string());
3435 } else if (idx < 0) {
3436 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3437 "that also does not appear in the top level layer list. Something"
3438 " has gone wrong.", layer->getName().string());
3439 } else if (layer->setLayerStack(s.layerStack)) {
3440 mCurrentState.layersSortedByZ.removeAt(idx);
3441 mCurrentState.layersSortedByZ.add(layer);
3442 // we need traversal (state changed)
3443 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003444 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003445 }
3446 }
3447 if (what & layer_state_t::eDeferTransaction) {
3448 if (s.barrierHandle != nullptr) {
3449 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3450 } else if (s.barrierGbp != nullptr) {
3451 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3452 if (authenticateSurfaceTextureLocked(gbp)) {
3453 const auto& otherLayer =
3454 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3455 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3456 } else {
3457 ALOGE("Attempt to defer transaction to to an"
3458 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003459 }
3460 }
chaviw8b3871a2017-11-01 17:41:01 -07003461 // We don't trigger a traversal here because if no other state is
3462 // changed, we don't want this to cause any more work
3463 }
3464 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003465 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003466 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003467 if (!hadParent) {
3468 mCurrentState.layersSortedByZ.remove(layer);
3469 }
chaviw8b3871a2017-11-01 17:41:01 -07003470 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003471 }
chaviw8b3871a2017-11-01 17:41:01 -07003472 }
3473 if (what & layer_state_t::eReparentChildren) {
3474 if (layer->reparentChildren(s.reparentHandle)) {
3475 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003476 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003477 }
chaviw8b3871a2017-11-01 17:41:01 -07003478 if (what & layer_state_t::eDetachChildren) {
3479 layer->detachChildren();
3480 }
3481 if (what & layer_state_t::eOverrideScalingModeChanged) {
3482 layer->setOverrideScalingMode(s.overrideScalingMode);
3483 // We don't trigger a traversal here because if no other state is
3484 // changed, we don't want this to cause any more work
3485 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003486 return flags;
3487}
3488
chaviwca27f252018-02-06 16:46:39 -08003489void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3490 const layer_state_t& state = composerState.state;
3491 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3492
3493 sp<Layer> layer(client->getLayerUser(state.surface));
3494 if (layer == nullptr) {
3495 return;
3496 }
3497
3498 if (layer->isPendingRemoval()) {
3499 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3500 return;
3501 }
3502
3503 if (state.what & layer_state_t::eDestroySurface) {
3504 removeLayerLocked(mStateLock, layer);
3505 }
3506}
3507
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003508status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003509 const String8& name,
3510 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003511 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003512 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003513 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003514{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003515 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003516 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003517 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003518 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003519 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003520
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003521 status_t result = NO_ERROR;
3522
3523 sp<Layer> layer;
3524
Cody Northropbc755282017-03-31 12:00:08 -06003525 String8 uniqueName = getUniqueLayerName(name);
3526
Mathias Agopian3165cc22012-08-08 19:42:09 -07003527 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3528 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003529 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003530 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003531 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003532
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003533 break;
chaviw13fdc492017-06-27 12:40:18 -07003534 case ISurfaceComposerClient::eFXSurfaceColor:
3535 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003536 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003537 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003538 break;
3539 default:
3540 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003541 break;
3542 }
3543
Dan Stoza7d89d062015-04-30 13:29:25 -07003544 if (result != NO_ERROR) {
3545 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003546 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003547
Chia-I Wuab0c3192017-08-01 11:29:00 -07003548 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3549 // TODO b/64227542
3550 if (windowType == 441731) {
3551 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3552 layer->setPrimaryDisplayOnly();
3553 }
3554
Albert Chaulk479c60c2017-01-27 14:21:34 -05003555 layer->setInfo(windowType, ownerUid);
3556
Robert Carr1f0a16a2016-10-24 16:27:39 -07003557 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003558 if (result != NO_ERROR) {
3559 return result;
3560 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003561 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003562
3563 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003564 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003565}
3566
Cody Northropbc755282017-03-31 12:00:08 -06003567String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3568{
3569 bool matchFound = true;
3570 uint32_t dupeCounter = 0;
3571
3572 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3573 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3574
3575 // Loop over layers until we're sure there is no matching name
3576 while (matchFound) {
3577 matchFound = false;
3578 mDrawingState.traverseInZOrder([&](Layer* layer) {
3579 if (layer->getName() == uniqueName) {
3580 matchFound = true;
3581 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3582 }
3583 });
3584 }
3585
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003586 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3587 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003588
3589 return uniqueName;
3590}
3591
David Sodman0c69cad2017-08-21 12:12:51 -07003592status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003593 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3594 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003595{
3596 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003597 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003598 case PIXEL_FORMAT_TRANSPARENT:
3599 case PIXEL_FORMAT_TRANSLUCENT:
3600 format = PIXEL_FORMAT_RGBA_8888;
3601 break;
3602 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003603 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003604 break;
3605 }
3606
David Sodman0c69cad2017-08-21 12:12:51 -07003607 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3608 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003609 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003610 *handle = layer->getHandle();
3611 *gbp = layer->getProducer();
3612 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003613 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003614
David Sodman0c69cad2017-08-21 12:12:51 -07003615 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003616 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003617}
3618
chaviw13fdc492017-06-27 12:40:18 -07003619status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003620 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003621 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003622{
chaviw13fdc492017-06-27 12:40:18 -07003623 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003624 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003625 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003626}
3627
Mathias Agopianac9fa422013-02-11 16:40:36 -08003628status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003629{
Robert Carr9524cb32017-02-13 11:32:32 -08003630 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003631 status_t err = NO_ERROR;
3632 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003633 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003634 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003635 err = removeLayer(l);
3636 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3637 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003638 }
3639 return err;
3640}
3641
Mathias Agopian13127d82013-03-05 17:47:11 -08003642status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003643{
Mathias Agopian67106042013-03-14 19:18:13 -07003644 // called by ~LayerCleaner() when all references to the IBinder (handle)
3645 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003646 sp<Layer> l = layer.promote();
3647 if (l == nullptr) {
3648 // The layer has already been removed, carry on
3649 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003650 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003651 // If we have a parent, then we can continue to live as long as it does.
3652 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003653}
3654
Mathias Agopianb60314a2012-04-10 22:09:54 -07003655// ---------------------------------------------------------------------------
3656
Andy McFadden13a082e2012-08-24 10:16:42 -07003657void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003658 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003659 Vector<ComposerState> state;
3660 Vector<DisplayState> displays;
3661 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003662 d.what = DisplayState::eDisplayProjectionChanged |
3663 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003664 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003665 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003666 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003667 d.frame.makeInvalid();
3668 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003669 d.width = 0;
3670 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003671 displays.add(d);
3672 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003673 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3674 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003675
David Sodman105b7dc2017-11-04 20:28:14 -07003676 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003677 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003678 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003679
Brian Andersond0010582017-03-07 13:20:31 -08003680 // Use phase of 0 since phase is not known.
3681 // Use latency of 0, which will snap to the ideal latency.
3682 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003683}
3684
3685void SurfaceFlinger::initializeDisplays() {
3686 class MessageScreenInitialized : public MessageBase {
3687 SurfaceFlinger* flinger;
3688 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003689 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003690 virtual bool handler() {
3691 flinger->onInitializeDisplays();
3692 return true;
3693 }
3694 };
3695 sp<MessageBase> msg = new MessageScreenInitialized(this);
3696 postMessageAsync(msg); // we may be called from main thread, use async message
3697}
3698
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003699void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003700 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003701 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3702 this);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003703 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003704
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003705 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003706 return;
3707 }
3708
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003709 hw->setPowerMode(mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -07003710 if (hw->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003711 ALOGW("Trying to set power mode for virtual display");
3712 return;
3713 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003714
Lloyd Pique4dccc412018-01-22 17:21:36 -08003715 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003716 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003717 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3718 if (idx < 0) {
3719 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3720 return;
3721 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003722 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003723 }
3724
Dominik Laskowski281644e2018-04-19 15:47:35 -07003725 int32_t type = hw->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003726 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003727 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003728 getHwComposer().setPowerMode(type, mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -07003729 if (hw->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003730 // FIXME: eventthread only knows about the main display right now
3731 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003732 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003733 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003734
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003735 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003736 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003737 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003738
3739 struct sched_param param = {0};
3740 param.sched_priority = 1;
3741 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3742 ALOGW("Couldn't set SCHED_FIFO on display on");
3743 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003744 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003745 // Turn off the display
3746 struct sched_param param = {0};
3747 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3748 ALOGW("Couldn't set SCHED_OTHER on display off");
3749 }
3750
Dominik Laskowski281644e2018-04-19 15:47:35 -07003751 if (hw->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003752 disableHardwareVsync(true); // also cancels any in-progress resync
3753
Mathias Agopiancde87a32012-09-13 14:09:01 -07003754 // FIXME: eventthread only knows about the main display right now
3755 mEventThread->onScreenReleased();
3756 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003757
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003758 getHwComposer().setPowerMode(type, mode);
3759 mVisibleRegionsDirty = true;
3760 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003761 } else if (mode == HWC_POWER_MODE_DOZE ||
3762 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003763 // Update display while dozing
3764 getHwComposer().setPowerMode(type, mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -07003765 if (hw->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003766 // FIXME: eventthread only knows about the main display right now
3767 mEventThread->onScreenAcquired();
3768 resyncToHardwareVsync(true);
3769 }
3770 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3771 // Leave display going to doze
Dominik Laskowski281644e2018-04-19 15:47:35 -07003772 if (hw->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003773 disableHardwareVsync(true); // also cancels any in-progress resync
3774 // FIXME: eventthread only knows about the main display right now
3775 mEventThread->onScreenReleased();
3776 }
3777 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003778 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003779 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003780 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003781 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003782 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003783}
3784
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003785void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3786 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003787 SurfaceFlinger& mFlinger;
3788 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003789 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003790 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003791 MessageSetPowerMode(SurfaceFlinger& flinger,
3792 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3793 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003794 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003795 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003796 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003797 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003798 mMode, mDisplay.get());
Dominik Laskowski281644e2018-04-19 15:47:35 -07003799 } else if (hw->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003800 ALOGW("Attempt to set power mode = %d for virtual display",
3801 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003802 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003803 mFlinger.setPowerModeInternal(
3804 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003805 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003806 return true;
3807 }
3808 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003809 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003810 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003811}
3812
3813// ---------------------------------------------------------------------------
3814
Lloyd Pique755e3192018-01-31 16:46:15 -08003815status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3816 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003817 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003818
Mathias Agopianbd115332013-04-18 16:41:04 -07003819 IPCThreadState* ipc = IPCThreadState::self();
3820 const int pid = ipc->getCallingPid();
3821 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003822
Mathias Agopianbd115332013-04-18 16:41:04 -07003823 if ((uid != AID_SHELL) &&
3824 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003825 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003826 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003827 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003828 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003829 // (this would indicate SF is stuck, but we want to be able to
3830 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003831 status_t err = mStateLock.timedLock(s2ns(1));
3832 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003833 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003834 result.appendFormat(
3835 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3836 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003837 }
3838
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003839 bool dumpAll = true;
3840 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003841 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003842
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003843 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003844 if ((index < numArgs) &&
3845 (args[index] == String16("--list"))) {
3846 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003847 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003848 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003849 }
3850
3851 if ((index < numArgs) &&
3852 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003853 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003854 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003855 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003856 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003857
3858 if ((index < numArgs) &&
3859 (args[index] == String16("--latency-clear"))) {
3860 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003861 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003862 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003863 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003864
3865 if ((index < numArgs) &&
3866 (args[index] == String16("--dispsync"))) {
3867 index++;
3868 mPrimaryDispSync.dump(result);
3869 dumpAll = false;
3870 }
Dan Stozab90cf072015-03-05 11:05:59 -08003871
3872 if ((index < numArgs) &&
3873 (args[index] == String16("--static-screen"))) {
3874 index++;
3875 dumpStaticScreenStats(result);
3876 dumpAll = false;
3877 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003878
3879 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003880 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003881 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003882 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003883 dumpAll = false;
3884 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003885
3886 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3887 index++;
3888 dumpWideColorInfo(result);
3889 dumpAll = false;
3890 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003891
3892 if ((index < numArgs) &&
3893 (args[index] == String16("--enable-layer-stats"))) {
3894 index++;
3895 mLayerStats.enable();
3896 dumpAll = false;
3897 }
3898
3899 if ((index < numArgs) &&
3900 (args[index] == String16("--disable-layer-stats"))) {
3901 index++;
3902 mLayerStats.disable();
3903 dumpAll = false;
3904 }
3905
3906 if ((index < numArgs) &&
3907 (args[index] == String16("--clear-layer-stats"))) {
3908 index++;
3909 mLayerStats.clear();
3910 dumpAll = false;
3911 }
3912
3913 if ((index < numArgs) &&
3914 (args[index] == String16("--dump-layer-stats"))) {
3915 index++;
3916 mLayerStats.dump(result);
3917 dumpAll = false;
3918 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003919
3920 if ((index < numArgs) &&
3921 (args[index] == String16("--display-identification"))) {
3922 index++;
3923 dumpDisplayIdentificationData(result);
3924 dumpAll = false;
3925 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003926
3927 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3928 index++;
3929 mTimeStats.parseArgs(asProto, args, index, result);
3930 dumpAll = false;
3931 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003932 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003933
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003934 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003935 if (asProto) {
3936 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3937 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3938 } else {
3939 dumpAllLocked(args, index, result);
3940 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003941 }
3942
Mathias Agopian9795c422009-08-26 16:36:26 -07003943 if (locked) {
3944 mStateLock.unlock();
3945 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003946 }
3947 write(fd, result.string(), result.size());
3948 return NO_ERROR;
3949}
3950
Dan Stozac7014012014-02-14 15:03:43 -08003951void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3952 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003953{
Robert Carr2047fae2016-11-28 14:09:09 -08003954 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003955 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003956 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003957}
3958
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003959void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003960 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003961{
3962 String8 name;
3963 if (index < args.size()) {
3964 name = String8(args[index]);
3965 index++;
3966 }
3967
David Sodman105b7dc2017-11-04 20:28:14 -07003968 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003969 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003970 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003971
3972 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003973 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003974 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003975 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003976 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003977 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003978 }
Robert Carr2047fae2016-11-28 14:09:09 -08003979 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003980 }
3981}
3982
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003983void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003984 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003985{
3986 String8 name;
3987 if (index < args.size()) {
3988 name = String8(args[index]);
3989 index++;
3990 }
3991
Robert Carr2047fae2016-11-28 14:09:09 -08003992 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003993 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003994 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003995 }
Robert Carr2047fae2016-11-28 14:09:09 -08003996 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003997
Svetoslavd85084b2014-03-20 10:28:31 -07003998 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003999}
4000
Jamie Gennis6547ff42013-07-16 20:12:42 -07004001// This should only be called from the main thread. Otherwise it would need
4002// the lock and should use mCurrentState rather than mDrawingState.
4003void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004004 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004005 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004006 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004007
4008 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4009}
4010
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004011void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004012{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004013 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004014
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004015 if (isLayerTripleBufferingDisabled())
4016 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004017
4018 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004019 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004020 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004021 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004022 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4023 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004024 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004025}
4026
Dan Stozab90cf072015-03-05 11:05:59 -08004027void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4028{
4029 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004030 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4031 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004032 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004033 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004034 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4035 b + 1, bucketTimeSec, percent);
4036 }
David Sodman4a36e932017-11-07 14:29:47 -08004037 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004038 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004039 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004040 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004041 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004042}
4043
Dan Stozae77c7662016-05-13 11:37:28 -07004044void SurfaceFlinger::recordBufferingStats(const char* layerName,
4045 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004046 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4047 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004048 for (const auto& segment : history) {
4049 if (!segment.usedThirdBuffer) {
4050 stats.twoBufferTime += segment.totalTime;
4051 }
4052 if (segment.occupancyAverage < 1.0f) {
4053 stats.doubleBufferedTime += segment.totalTime;
4054 } else if (segment.occupancyAverage < 2.0f) {
4055 stats.tripleBufferedTime += segment.totalTime;
4056 }
4057 ++stats.numSegments;
4058 stats.totalTime += segment.totalTime;
4059 }
4060}
4061
Brian Andersond6927fb2016-07-23 23:37:30 -07004062void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4063 result.appendFormat("Layer frame timestamps:\n");
4064
4065 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4066 const size_t count = currentLayers.size();
4067 for (size_t i=0 ; i<count ; i++) {
4068 currentLayers[i]->dumpFrameEvents(result);
4069 }
4070}
4071
Dan Stozae77c7662016-05-13 11:37:28 -07004072void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4073 result.append("Buffering stats:\n");
4074 result.append(" [Layer name] <Active time> <Two buffer> "
4075 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004076 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004077 typedef std::tuple<std::string, float, float, float> BufferTuple;
4078 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004079 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004080 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004081 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004082 if (stats.numSegments == 0) {
4083 continue;
4084 }
4085 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4086 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4087 stats.totalTime;
4088 float doubleBufferRatio = static_cast<float>(
4089 stats.doubleBufferedTime) / stats.totalTime;
4090 float tripleBufferRatio = static_cast<float>(
4091 stats.tripleBufferedTime) / stats.totalTime;
4092 sorted.insert({activeTime, {name, twoBufferRatio,
4093 doubleBufferRatio, tripleBufferRatio}});
4094 }
4095 for (const auto& sortedPair : sorted) {
4096 float activeTime = sortedPair.first;
4097 const BufferTuple& values = sortedPair.second;
4098 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4099 std::get<0>(values).c_str(), activeTime,
4100 std::get<1>(values), std::get<2>(values),
4101 std::get<3>(values));
4102 }
4103 result.append("\n");
4104}
4105
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004106void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
4107 for (size_t d = 0; d < mDisplays.size(); d++) {
4108 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4109 const int32_t hwcId = displayDevice->getHwcDisplayId();
4110 const auto displayId = getHwComposer().getHwcDisplayId(hwcId);
4111 if (!displayId) {
4112 continue;
4113 }
4114
4115 result.appendFormat("Display %d: ", hwcId);
4116 uint8_t port;
4117 DisplayIdentificationData data;
4118 if (!getHwComposer().getDisplayIdentificationData(*displayId, &port, &data)) {
4119 result.append("no identification data\n");
4120 continue;
4121 }
4122
4123 if (!isEdid(data)) {
4124 result.append("unknown identification data: ");
4125 for (uint8_t byte : data) {
4126 result.appendFormat("%x ", byte);
4127 }
4128 result.append("\n");
4129 continue;
4130 }
4131
4132 const auto edid = parseEdid(data);
4133 if (!edid) {
4134 result.append("invalid EDID: ");
4135 for (uint8_t byte : data) {
4136 result.appendFormat("%x ", byte);
4137 }
4138 result.append("\n");
4139 continue;
4140 }
4141
4142 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4143 result.append(edid->displayName.data(), edid->displayName.length());
4144 result.append("\"\n");
4145 }
4146 result.append("\n");
4147}
4148
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004149void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4150 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004151 result.appendFormat("DisplayColorSetting: %s\n",
4152 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004153
4154 // TODO: print out if wide-color mode is active or not
4155
4156 for (size_t d = 0; d < mDisplays.size(); d++) {
4157 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4158 int32_t hwcId = displayDevice->getHwcDisplayId();
4159 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4160 continue;
4161 }
4162
4163 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004164 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004165 for (auto&& mode : modes) {
4166 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4167 }
4168
Peiyong Lina52f0292018-03-14 17:26:31 -07004169 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004170 result.appendFormat(" Current color mode: %s (%d)\n",
4171 decodeColorMode(currentMode).c_str(), currentMode);
4172 }
4173 result.append("\n");
4174}
4175
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004176LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004177 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004178 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4179 const State& state = useDrawing ? mDrawingState : mCurrentState;
4180 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004181 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004182 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004183 });
4184
4185 return layersProto;
4186}
4187
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004188LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4189 LayersProto layersProto;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004190 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004191
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004192 SizeProto* resolution = layersProto.mutable_resolution();
4193 resolution->set_w(displayDevice->getWidth());
4194 resolution->set_h(displayDevice->getHeight());
4195
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004196 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4197 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4198 layersProto.set_global_transform(
4199 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4200
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004201 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004202 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004203 LayerProto* layerProto = layersProto.add_layers();
4204 layer->writeToProto(layerProto, hwcId);
4205 }
4206 });
4207
4208 return layersProto;
4209}
4210
Mathias Agopian74d211a2013-04-22 16:55:35 +02004211void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4212 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004213{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004214 bool colorize = false;
4215 if (index < args.size()
4216 && (args[index] == String16("--color"))) {
4217 colorize = true;
4218 index++;
4219 }
4220
4221 Colorizer colorizer(colorize);
4222
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004223 // figure out if we're stuck somewhere
4224 const nsecs_t now = systemTime();
4225 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4226 const nsecs_t inTransaction(mDebugInTransaction);
4227 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4228 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4229
4230 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004231 * Dump library configuration.
4232 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004233
4234 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004235 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004236 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004237 appendSfConfigString(result);
4238 appendUiConfigString(result);
4239 appendGuiConfigString(result);
4240 result.append("\n");
4241
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004242 result.append("\nDisplay identification data:\n");
4243 dumpDisplayIdentificationData(result);
4244
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004245 result.append("\nWide-Color information:\n");
4246 dumpWideColorInfo(result);
4247
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004248 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004249 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004250 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004251 result.append(SyncFeatures::getInstance().toString());
4252 result.append("\n");
4253
David Sodman105b7dc2017-11-04 20:28:14 -07004254 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004255
Andy McFadden41d67d72014-04-25 16:58:34 -07004256 colorizer.bold(result);
4257 result.append("DispSync configuration: ");
4258 colorizer.reset(result);
Dan Stoza84d619e2018-03-28 17:07:36 -07004259 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4260 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4261 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004262 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004263 result.append("\n");
4264
Dan Stozab90cf072015-03-05 11:05:59 -08004265 // Dump static screen stats
4266 result.append("\n");
4267 dumpStaticScreenStats(result);
4268 result.append("\n");
4269
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004270 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4271
Dan Stozae77c7662016-05-13 11:37:28 -07004272 dumpBufferingStats(result);
4273
Andy McFadden4803b742012-09-24 19:07:20 -07004274 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004275 * Dump the visible layer list
4276 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004277 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004278 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004279 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4280 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004281 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004282
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004283 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004284 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004285 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004286 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004287
4288 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004289 * Dump Display state
4290 */
4291
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004292 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004293 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004294 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004295 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4296 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004297 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004298 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004299 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004300
4301 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004302 * Dump SurfaceFlinger global state
4303 */
4304
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004305 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004306 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004307 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004308
Mathias Agopian888c8222012-08-04 21:10:38 -07004309 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004310 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004311
David Sodmanbc815282017-11-05 18:57:52 -08004312 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004313
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004314 if (hw) {
4315 hw->undefinedRegion.dump(result, "undefinedRegion");
4316 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4317 hw->getOrientation(), hw->isDisplayOn());
4318 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004319 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004320 " last eglSwapBuffers() time: %f us\n"
4321 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004322 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004323 " refresh-rate : %f fps\n"
4324 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004325 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004326 " gpu_to_cpu_unsupported : %d\n"
4327 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004328 mLastSwapBufferTime/1000.0,
4329 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004330 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004331 1e9 / activeConfig->getVsyncPeriod(),
4332 activeConfig->getDpiX(),
4333 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004334 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004335
Mathias Agopian74d211a2013-04-22 16:55:35 +02004336 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004337 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004338
Mathias Agopian74d211a2013-04-22 16:55:35 +02004339 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004340 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004341
4342 /*
4343 * VSYNC state
4344 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004345 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004346 result.append("\n");
4347
4348 /*
4349 * HWC layer minidump
4350 */
4351 for (size_t d = 0; d < mDisplays.size(); d++) {
4352 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4353 int32_t hwcId = displayDevice->getHwcDisplayId();
4354 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4355 continue;
4356 }
4357
4358 result.appendFormat("Display %d HWC layers:\n", hwcId);
4359 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004360 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004361 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004362 });
Dan Stozae22aec72016-08-01 13:20:59 -07004363 result.append("\n");
4364 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004365
4366 /*
4367 * Dump HWComposer state
4368 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004369 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004370 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004371 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004372 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004373 result.appendFormat(" h/w composer %s\n",
4374 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004375 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004376
4377 /*
4378 * Dump gralloc state
4379 */
4380 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4381 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004382
4383 /*
4384 * Dump VrFlinger state if in use.
4385 */
4386 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4387 result.append("VrFlinger state:\n");
4388 result.append(mVrFlinger->Dump().c_str());
4389 result.append("\n");
4390 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004391}
4392
Mathias Agopian13127d82013-03-05 17:47:11 -08004393const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004394SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004395 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004396 wp<IBinder> dpy;
4397 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4398 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4399 dpy = mDisplays.keyAt(i);
4400 break;
4401 }
4402 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004403 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004404 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4405 // Just use the primary display so we have something to return
4406 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4407 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004408 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004409}
4410
Keun young Park63f165f2012-08-31 10:53:36 -07004411bool SurfaceFlinger::startDdmConnection()
4412{
4413 void* libddmconnection_dso =
4414 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4415 if (!libddmconnection_dso) {
4416 return false;
4417 }
4418 void (*DdmConnection_start)(const char* name);
4419 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004420 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004421 if (!DdmConnection_start) {
4422 dlclose(libddmconnection_dso);
4423 return false;
4424 }
4425 (*DdmConnection_start)(getServiceName());
4426 return true;
4427}
4428
Chia-I Wu28f320b2018-05-03 11:02:56 -07004429void SurfaceFlinger::updateColorMatrixLocked() {
4430 mat4 colorMatrix;
4431 if (mGlobalSaturationFactor != 1.0f) {
4432 // Rec.709 luma coefficients
4433 float3 luminance{0.213f, 0.715f, 0.072f};
4434 luminance *= 1.0f - mGlobalSaturationFactor;
4435 mat4 saturationMatrix = mat4(
4436 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4437 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4438 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4439 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4440 );
4441 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4442 } else {
4443 colorMatrix = mClientColorMatrix * mDaltonizer();
4444 }
4445
4446 if (mCurrentState.colorMatrix != colorMatrix) {
4447 mCurrentState.colorMatrix = colorMatrix;
4448 mCurrentState.colorMatrixChanged = true;
4449 setTransactionFlags(eTransactionNeeded);
4450 }
4451}
4452
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004453status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004454 switch (code) {
4455 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004456 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004457 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004458 case CLEAR_ANIMATION_FRAME_STATS:
4459 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004460 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004461 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004462 case ENABLE_VSYNC_INJECTIONS:
4463 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004464 {
4465 // codes that require permission check
4466 IPCThreadState* ipc = IPCThreadState::self();
4467 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004468 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004469 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004470 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004471 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004472 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004473 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004474 break;
4475 }
Robert Carr1db73f62016-12-21 12:58:51 -08004476 /*
4477 * Calling setTransactionState is safe, because you need to have been
4478 * granted a reference to Client* and Handle* to do anything with it.
4479 *
4480 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4481 */
4482 case SET_TRANSACTION_STATE:
4483 case CREATE_SCOPED_CONNECTION:
4484 {
4485 return OK;
4486 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004487 case CAPTURE_SCREEN:
4488 {
4489 // codes that require permission check
4490 IPCThreadState* ipc = IPCThreadState::self();
4491 const int pid = ipc->getCallingPid();
4492 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004493 if ((uid != AID_GRAPHICS) &&
4494 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004495 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004496 return PERMISSION_DENIED;
4497 }
4498 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004499 }
chaviwa76b2712017-09-20 12:02:26 -07004500 case CAPTURE_LAYERS: {
4501 IPCThreadState* ipc = IPCThreadState::self();
4502 const int pid = ipc->getCallingPid();
4503 const int uid = ipc->getCallingUid();
4504 if ((uid != AID_GRAPHICS) &&
4505 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4506 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4507 return PERMISSION_DENIED;
4508 }
4509 break;
4510 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004511 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004512 return OK;
4513}
4514
4515status_t SurfaceFlinger::onTransact(
4516 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4517{
4518 status_t credentialCheck = CheckTransactCodeCredentials(code);
4519 if (credentialCheck != OK) {
4520 return credentialCheck;
4521 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004522
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004523 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4524 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004525 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004526 IPCThreadState* ipc = IPCThreadState::self();
4527 const int uid = ipc->getCallingUid();
4528 if (CC_UNLIKELY(uid != AID_SYSTEM
4529 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004530 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004531 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004532 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004533 return PERMISSION_DENIED;
4534 }
4535 int n;
4536 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004537 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004538 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004539 return NO_ERROR;
4540 case 1002: // SHOW_UPDATES
4541 n = data.readInt32();
4542 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004543 invalidateHwcGeometry();
4544 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004545 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004546 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004547 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004548 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004549 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004550 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004551 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004552 setTransactionFlags(
4553 eTransactionNeeded|
4554 eDisplayTransactionNeeded|
4555 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004556 return NO_ERROR;
4557 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004558 case 1006:{ // send empty update
4559 signalRefresh();
4560 return NO_ERROR;
4561 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004562 case 1008: // toggle use of hw composer
4563 n = data.readInt32();
4564 mDebugDisableHWC = n ? 1 : 0;
4565 invalidateHwcGeometry();
4566 repaintEverything();
4567 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004568 case 1009: // toggle use of transform hint
4569 n = data.readInt32();
4570 mDebugDisableTransformHint = n ? 1 : 0;
4571 invalidateHwcGeometry();
4572 repaintEverything();
4573 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004574 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004575 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004576 reply->writeInt32(0);
4577 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004578 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004579 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004580 return NO_ERROR;
4581 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004582 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004583 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004584 return NO_ERROR;
4585 }
4586 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004587 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004588 // daltonize
4589 n = data.readInt32();
4590 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004591 case 1:
4592 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4593 break;
4594 case 2:
4595 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4596 break;
4597 case 3:
4598 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4599 break;
4600 default:
4601 mDaltonizer.setType(ColorBlindnessType::None);
4602 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004603 }
4604 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004605 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004606 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004607 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004608 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004609
4610 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004611 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004612 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004613 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004614 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004615 // apply a color matrix
4616 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004617 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004618 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004619 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004620 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004621 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004622 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004623 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004624 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004625 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004626 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004627
4628 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4629 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004630 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004631 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4632 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4633 }
4634
Chia-I Wu28f320b2018-05-03 11:02:56 -07004635 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004636 return NO_ERROR;
4637 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004638 // This is an experimental interface
4639 // Needs to be shifted to proper binder interface when we productize
4640 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004641 n = data.readInt32();
4642 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004643 return NO_ERROR;
4644 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004645 case 1017: {
4646 n = data.readInt32();
4647 mForceFullDamage = static_cast<bool>(n);
4648 return NO_ERROR;
4649 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004650 case 1018: { // Modify Choreographer's phase offset
4651 n = data.readInt32();
4652 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4653 return NO_ERROR;
4654 }
4655 case 1019: { // Modify SurfaceFlinger's phase offset
4656 n = data.readInt32();
4657 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4658 return NO_ERROR;
4659 }
Irvel468051e2016-06-13 16:44:44 -07004660 case 1020: { // Layer updates interceptor
4661 n = data.readInt32();
4662 if (n) {
4663 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004664 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004665 }
4666 else{
4667 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004668 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004669 }
4670 return NO_ERROR;
4671 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004672 case 1021: { // Disable HWC virtual displays
4673 n = data.readInt32();
4674 mUseHwcVirtualDisplays = !n;
4675 return NO_ERROR;
4676 }
Romain Guy0147a172017-06-01 13:53:56 -07004677 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004678 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004679 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004680
Chia-I Wu28f320b2018-05-03 11:02:56 -07004681 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004682 return NO_ERROR;
4683 }
Romain Guy54f154a2017-10-24 21:40:32 +01004684 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004685 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004686 invalidateHwcGeometry();
4687 repaintEverything();
4688 return NO_ERROR;
4689 }
4690 case 1024: { // Is wide color gamut rendering/color management supported?
4691 reply->writeBool(hasWideColorDisplay);
4692 return NO_ERROR;
4693 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004694 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004695 n = data.readInt32();
4696 if (n) {
4697 ALOGV("LayerTracing enabled");
4698 mTracing.enable();
4699 doTracing("tracing.enable");
4700 reply->writeInt32(NO_ERROR);
4701 } else {
4702 ALOGV("LayerTracing disabled");
4703 status_t err = mTracing.disable();
4704 reply->writeInt32(err);
4705 }
4706 return NO_ERROR;
4707 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004708 case 1026: { // Get layer tracing status
4709 reply->writeBool(mTracing.isEnabled());
4710 return NO_ERROR;
4711 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004712 // Is a DisplayColorSetting supported?
4713 case 1027: {
Chia-I Wu0d711262018-05-21 15:19:35 -07004714 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
4715 if (!hw) {
4716 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004717 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004718
4719 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4720 switch (setting) {
4721 case DisplayColorSetting::MANAGED:
4722 reply->writeBool(hasWideColorDisplay);
4723 break;
4724 case DisplayColorSetting::UNMANAGED:
4725 reply->writeBool(true);
4726 break;
4727 case DisplayColorSetting::ENHANCED:
4728 reply->writeBool(hw->hasRenderIntent(RenderIntent::ENHANCE));
4729 break;
4730 default: // vendor display color setting
4731 reply->writeBool(hw->hasRenderIntent(static_cast<RenderIntent>(setting)));
4732 break;
4733 }
4734 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004735 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004736 }
4737 }
4738 return err;
4739}
4740
Steven Thomas6d8110b2017-08-31 18:24:21 -07004741void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004742 android_atomic_or(1, &mRepaintEverything);
4743 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004744}
4745
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004746// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4747class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004748public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004749 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4750 ~WindowDisconnector() {
4751 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004752 }
4753
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004754private:
4755 ANativeWindow* mWindow;
4756 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004757};
4758
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004759status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4760 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4761 int32_t minLayerZ, int32_t maxLayerZ,
4762 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004763 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004764 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004765
chaviwa76b2712017-09-20 12:02:26 -07004766 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4767
4768 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004769 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4770
chaviwa76b2712017-09-20 12:02:26 -07004771 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4772
4773 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4774 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004775 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004776}
4777
4778status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004779 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004780 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004781 ATRACE_CALL();
4782
4783 class LayerRenderArea : public RenderArea {
4784 public:
Robert Carr578038f2018-03-09 12:25:24 -08004785 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4786 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004787 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004788 mLayer(layer),
4789 mCrop(crop),
4790 mFlinger(flinger),
4791 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004792 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004793 Rect getBounds() const override {
4794 const Layer::State& layerState(mLayer->getDrawingState());
4795 return Rect(layerState.active.w, layerState.active.h);
4796 }
4797 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4798 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4799 bool isSecure() const override { return false; }
4800 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004801 Rect getSourceCrop() const override {
4802 if (mCrop.isEmpty()) {
4803 return getBounds();
4804 } else {
4805 return mCrop;
4806 }
4807 }
Robert Carr578038f2018-03-09 12:25:24 -08004808 class ReparentForDrawing {
4809 public:
4810 const sp<Layer>& oldParent;
4811 const sp<Layer>& newParent;
4812
4813 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4814 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004815 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004816 }
Robert Carr15eae092018-03-23 13:43:53 -07004817 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004818 };
4819
4820 void render(std::function<void()> drawLayers) override {
4821 if (!mChildrenOnly) {
4822 mTransform = mLayer->getTransform().inverse();
4823 drawLayers();
4824 } else {
4825 Rect bounds = getBounds();
4826 screenshotParentLayer =
4827 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4828 bounds.getWidth(), bounds.getHeight(), 0);
4829
4830 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4831 drawLayers();
4832 }
4833 }
chaviwa76b2712017-09-20 12:02:26 -07004834
chaviwa76b2712017-09-20 12:02:26 -07004835 private:
chaviw7206d492017-11-10 16:16:12 -08004836 const sp<Layer> mLayer;
4837 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004838
4839 // In the "childrenOnly" case we reparent the children to a screenshot
4840 // layer which has no properties set and which does not draw.
4841 sp<ContainerLayer> screenshotParentLayer;
4842 Transform mTransform;
4843
4844 SurfaceFlinger* mFlinger;
4845 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004846 };
4847
4848 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4849 auto parent = layerHandle->owner.promote();
4850
chaviw7206d492017-11-10 16:16:12 -08004851 if (parent == nullptr || parent->isPendingRemoval()) {
4852 ALOGE("captureLayers called with a removed parent");
4853 return NAME_NOT_FOUND;
4854 }
4855
Robert Carr578038f2018-03-09 12:25:24 -08004856 const int uid = IPCThreadState::self()->getCallingUid();
4857 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4858 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4859 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4860 return PERMISSION_DENIED;
4861 }
4862
chaviw7206d492017-11-10 16:16:12 -08004863 Rect crop(sourceCrop);
4864 if (sourceCrop.width() <= 0) {
4865 crop.left = 0;
4866 crop.right = parent->getCurrentState().active.w;
4867 }
4868
4869 if (sourceCrop.height() <= 0) {
4870 crop.top = 0;
4871 crop.bottom = parent->getCurrentState().active.h;
4872 }
4873
4874 int32_t reqWidth = crop.width() * frameScale;
4875 int32_t reqHeight = crop.height() * frameScale;
4876
Robert Carr578038f2018-03-09 12:25:24 -08004877 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004878
Robert Carr578038f2018-03-09 12:25:24 -08004879 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004880 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4881 if (!layer->isVisible()) {
4882 return;
Robert Carr578038f2018-03-09 12:25:24 -08004883 } else if (childrenOnly && layer == parent.get()) {
4884 return;
chaviwa76b2712017-09-20 12:02:26 -07004885 }
4886 visitor(layer);
4887 });
4888 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004889 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004890}
4891
4892status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4893 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004894 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004895 bool useIdentityTransform) {
4896 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004897
Iris Chang7501ed62018-04-30 14:45:42 +08004898 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004899
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004900 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4901 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4902 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4903 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004904
4905 // This mutex protects syncFd and captureResult for communication of the return values from the
4906 // main thread back to this Binder thread
4907 std::mutex captureMutex;
4908 std::condition_variable captureCondition;
4909 std::unique_lock<std::mutex> captureLock(captureMutex);
4910 int syncFd = -1;
4911 std::optional<status_t> captureResult;
4912
Robert Carr03480e22018-01-04 16:02:06 -08004913 const int uid = IPCThreadState::self()->getCallingUid();
4914 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4915
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004916 sp<LambdaMessage> message = new LambdaMessage([&]() {
4917 // If there is a refresh pending, bug out early and tell the binder thread to try again
4918 // after the refresh.
4919 if (mRefreshPending) {
4920 ATRACE_NAME("Skipping screenshot for now");
4921 std::unique_lock<std::mutex> captureLock(captureMutex);
4922 captureResult = std::make_optional<status_t>(EAGAIN);
4923 captureCondition.notify_one();
4924 return;
4925 }
4926
4927 status_t result = NO_ERROR;
4928 int fd = -1;
4929 {
4930 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004931 renderArea.render([&]() {
4932 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4933 useIdentityTransform, forSystem, &fd);
4934 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004935 }
4936
4937 {
4938 std::unique_lock<std::mutex> captureLock(captureMutex);
4939 syncFd = fd;
4940 captureResult = std::make_optional<status_t>(result);
4941 captureCondition.notify_one();
4942 }
4943 });
4944
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004945 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004946 if (result == NO_ERROR) {
4947 captureCondition.wait(captureLock, [&]() { return captureResult; });
4948 while (*captureResult == EAGAIN) {
4949 captureResult.reset();
4950 result = postMessageAsync(message);
4951 if (result != NO_ERROR) {
4952 return result;
4953 }
4954 captureCondition.wait(captureLock, [&]() { return captureResult; });
4955 }
4956 result = *captureResult;
4957 }
4958
4959 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004960 sync_wait(syncFd, -1);
4961 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004962 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004963
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004964 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004965}
4966
chaviwa76b2712017-09-20 12:02:26 -07004967void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4968 TraverseLayersFunction traverseLayers, bool yswap,
4969 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004970 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004971
Lloyd Pique144e1162017-12-20 16:44:52 -08004972 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004973
4974 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004975 const auto raWidth = renderArea.getWidth();
4976 const auto raHeight = renderArea.getHeight();
4977
4978 const auto reqWidth = renderArea.getReqWidth();
4979 const auto reqHeight = renderArea.getReqHeight();
4980 Rect sourceCrop = renderArea.getSourceCrop();
4981
Iris Chang7501ed62018-04-30 14:45:42 +08004982 bool filtering = false;
4983 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
4984 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
4985 static_cast<int32_t>(reqHeight) != raWidth;
4986 } else {
4987 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4988 static_cast<int32_t>(reqHeight) != raHeight;
4989 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004990
Dan Stozac1879002014-05-22 15:59:05 -07004991 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004992 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004993 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004994 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08004995 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
4996 Transform tr;
4997 uint32_t flags = 0x00;
4998 switch (mPrimaryDisplayOrientation) {
4999 case DisplayState::eOrientation90:
5000 flags = Transform::ROT_90;
5001 break;
5002 case DisplayState::eOrientation180:
5003 flags = Transform::ROT_180;
5004 break;
5005 case DisplayState::eOrientation270:
5006 flags = Transform::ROT_270;
5007 break;
5008 }
5009 tr.set(flags, raWidth, raHeight);
5010 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005011 }
5012
5013 // ensure that sourceCrop is inside screen
5014 if (sourceCrop.left < 0) {
5015 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5016 }
chaviwa76b2712017-09-20 12:02:26 -07005017 if (sourceCrop.right > raWidth) {
5018 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005019 }
5020 if (sourceCrop.top < 0) {
5021 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5022 }
chaviwa76b2712017-09-20 12:02:26 -07005023 if (sourceCrop.bottom > raHeight) {
5024 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005025 }
5026
Chia-I Wu36574d92018-05-16 10:54:36 -07005027 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5028 engine.setOutputDataSpace(Dataspace::SRGB);
5029 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005030
Mathias Agopian180f10d2013-04-10 22:55:41 -07005031 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005032 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005033
Iris Chang7501ed62018-04-30 14:45:42 +08005034 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5035 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5036 // convert hw orientation into flag presentation
5037 // here inverse transform needed
5038 uint8_t hw_rot_90 = 0x00;
5039 uint8_t hw_flip_hv = 0x00;
5040 switch (mPrimaryDisplayOrientation) {
5041 case DisplayState::eOrientation90:
5042 hw_rot_90 = Transform::ROT_90;
5043 hw_flip_hv = Transform::ROT_180;
5044 break;
5045 case DisplayState::eOrientation180:
5046 hw_flip_hv = Transform::ROT_180;
5047 break;
5048 case DisplayState::eOrientation270:
5049 hw_rot_90 = Transform::ROT_90;
5050 break;
5051 }
5052
5053 // transform flags operation
5054 // 1) flip H V if both have ROT_90 flag
5055 // 2) XOR these flags
5056 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5057 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5058 if (rotation_rot_90 & hw_rot_90) {
5059 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5060 }
5061 rotation = static_cast<Transform::orientation_flags>
5062 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5063 }
5064
Mathias Agopian180f10d2013-04-10 22:55:41 -07005065 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005066 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005067 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005068 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005069
chaviw50da5042018-04-09 13:49:37 -07005070 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005071 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005072 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005073
chaviwa76b2712017-09-20 12:02:26 -07005074 traverseLayers([&](Layer* layer) {
5075 if (filtering) layer->setFiltering(true);
bohu21566132018-03-27 14:36:34 -07005076 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005077 if (filtering) layer->setFiltering(false);
5078 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005079}
5080
chaviwa76b2712017-09-20 12:02:26 -07005081status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5082 TraverseLayersFunction traverseLayers,
5083 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005084 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005085 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005086 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005087 ATRACE_CALL();
5088
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005089 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005090
5091 traverseLayers([&](Layer* layer) {
5092 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5093 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005094
Robert Carr03480e22018-01-04 16:02:06 -08005095 // We allow the system server to take screenshots of secure layers for
5096 // use in situations like the Screen-rotation animation and place
5097 // the impetus on WindowManager to not persist them.
5098 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005099 ALOGW("FB is protected: PERMISSION_DENIED");
5100 return PERMISSION_DENIED;
5101 }
5102
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005103 // this binds the given EGLImage as a framebuffer for the
5104 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005105 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005106 if (bufferBond.getStatus() != NO_ERROR) {
5107 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005108 return INVALID_OPERATION;
5109 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005110
Dan Stozaabcda352017-06-01 14:37:39 -07005111 // this will in fact render into our dequeued buffer
5112 // via an FBO, which means we didn't have to create
5113 // an EGLSurface and therefore we're not
5114 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005115 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005116
Dan Stozaabcda352017-06-01 14:37:39 -07005117 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005118 getRenderEngine().finish();
5119 *outSyncFd = -1;
5120
chaviwa76b2712017-09-20 12:02:26 -07005121 const auto reqWidth = renderArea.getReqWidth();
5122 const auto reqHeight = renderArea.getReqHeight();
5123
Dan Stozaabcda352017-06-01 14:37:39 -07005124 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5125 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005126 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005127 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005128 } else {
5129 base::unique_fd syncFd = getRenderEngine().flush();
5130 if (syncFd < 0) {
5131 getRenderEngine().finish();
5132 }
5133 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005134 }
5135
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005136 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005137}
5138
Mathias Agopiand5556842013-09-19 17:08:37 -07005139void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005140 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005141 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005142 for (size_t y = 0; y < h; y++) {
5143 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5144 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005145 if (p[x] != 0xFF000000) return;
5146 }
5147 }
chaviwa76b2712017-09-20 12:02:26 -07005148 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005149
Robert Carr2047fae2016-11-28 14:09:09 -08005150 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005151 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005152 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005153 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5154 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5155 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5156 static_cast<float>(state.color.a));
5157 i++;
5158 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005159 }
5160}
5161
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005162// ---------------------------------------------------------------------------
5163
Dan Stoza412903f2017-04-27 13:42:17 -07005164void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5165 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005166}
5167
Dan Stoza412903f2017-04-27 13:42:17 -07005168void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5169 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005170}
5171
chaviwa76b2712017-09-20 12:02:26 -07005172void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5173 int32_t maxLayerZ,
5174 const LayerVector::Visitor& visitor) {
5175 // We loop through the first level of layers without traversing,
5176 // as we need to interpret min/max layer Z in the top level Z space.
5177 for (const auto& layer : mDrawingState.layersSortedByZ) {
5178 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5179 continue;
5180 }
5181 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005182 // relative layers are traversed in Layer::traverseInZOrder
5183 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005184 continue;
5185 }
5186 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005187 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5188 return;
5189 }
chaviwa76b2712017-09-20 12:02:26 -07005190 if (!layer->isVisible()) {
5191 return;
5192 }
5193 visitor(layer);
5194 });
5195 }
5196}
5197
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005198}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005199
Chia-I Wu30505fb2018-03-26 16:20:31 -07005200
Mathias Agopian3f844832013-08-07 21:24:32 -07005201#if defined(__gl_h_)
5202#error "don't include gl/gl.h in this file"
5203#endif
5204
5205#if defined(__gl2_h_)
5206#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005207#endif