blob: 35eb8c65de9c266fe0d648efc49669a799e3ca39 [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())) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001616 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1617 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1618 if (displayDevice->isPrimary()) {
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001619 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*displayDevice));
1620 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001621 }
1622 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001623
1624 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001625 }
1626}
1627
Chia-I Wu30505fb2018-03-26 16:20:31 -07001628void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001629{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001630 ATRACE_CALL();
1631 ALOGV("preComposition");
1632
Mathias Agopiancd60f992012-08-16 16:28:27 -07001633 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001634 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001635 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001636 needExtraInvalidate = true;
1637 }
Robert Carr2047fae2016-11-28 14:09:09 -08001638 });
1639
Mathias Agopiancd60f992012-08-16 16:28:27 -07001640 if (needExtraInvalidate) {
1641 signalLayerUpdate();
1642 }
1643}
1644
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001645void SurfaceFlinger::updateCompositorTiming(
1646 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1647 std::shared_ptr<FenceTime>& presentFenceTime) {
1648 // Update queue of past composite+present times and determine the
1649 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001650 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001651 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001652 while (!getBE().mCompositePresentTimes.empty()) {
1653 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001654 // Cached values should have been updated before calling this method,
1655 // which helps avoid duplicate syscalls.
1656 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1657 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1658 break;
1659 }
1660 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001661 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001662 }
1663
1664 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001665 while (getBE().mCompositePresentTimes.size() > 16) {
1666 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001667 }
1668
Brian Andersond0010582017-03-07 13:20:31 -08001669 setCompositorTimingSnapped(
1670 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1671}
1672
1673void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1674 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001675 // Integer division and modulo round toward 0 not -inf, so we need to
1676 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001677 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001678 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1679 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1680
Brian Andersond0010582017-03-07 13:20:31 -08001681 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1682 if (idealLatency <= 0) {
1683 idealLatency = vsyncInterval;
1684 }
1685
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001686 // Snap the latency to a value that removes scheduling jitter from the
1687 // composition and present times, which often have >1ms of jitter.
1688 // Reducing jitter is important if an app attempts to extrapolate
1689 // something (such as user input) to an accurate diasplay time.
1690 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1691 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001692 nsecs_t bias = vsyncInterval / 2;
1693 int64_t extraVsyncs =
1694 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1695 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1696 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001697
David Sodman99974d22017-11-28 12:04:33 -08001698 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1699 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1700 getBE().mCompositorTiming.interval = vsyncInterval;
1701 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001702}
1703
Chia-I Wu30505fb2018-03-26 16:20:31 -07001704void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001705{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001706 ATRACE_CALL();
1707 ALOGV("postComposition");
1708
Brian Anderson3546a3f2016-07-14 11:51:14 -07001709 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001710 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001711 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001712 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001713 }
1714
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001715 // |mStateLock| not needed as we are on the main thread
1716 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001717
David Sodman73beded2017-11-15 11:56:06 -08001718 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001719 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001720 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001721 glCompositionDoneFenceTime =
1722 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001723 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001724 } else {
1725 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1726 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001727
David Sodman73beded2017-11-15 11:56:06 -08001728 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001729 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001730 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001731 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001732
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001733 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1734 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1735
Chia-I Wu30505fb2018-03-26 16:20:31 -07001736 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001737 // when we started doing work for this frame, but that should be okay
1738 // since updateCompositorTiming has snapping logic.
1739 updateCompositorTiming(
Chia-I Wu30505fb2018-03-26 16:20:31 -07001740 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001741 CompositorTiming compositorTiming;
1742 {
David Sodman99974d22017-11-28 12:04:33 -08001743 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1744 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001745 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001746
Robert Carr2047fae2016-11-28 14:09:09 -08001747 mDrawingState.traverseInZOrder([&](Layer* layer) {
1748 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001749 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001750 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001751 recordBufferingStats(layer->getName().string(),
1752 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001753 }
Robert Carr2047fae2016-11-28 14:09:09 -08001754 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001755
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001756 if (presentFenceTime->isValid()) {
1757 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001758 enableHardwareVsync();
1759 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001760 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001761 }
1762 }
1763
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001764 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001765 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001766 enableHardwareVsync();
1767 }
1768 }
1769
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001770 if (mAnimCompositionPending) {
1771 mAnimCompositionPending = false;
1772
Brian Anderson4e606e32017-03-16 15:34:57 -07001773 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001774 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001775 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001776 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001777 // The HWC doesn't support present fences, so use the refresh
1778 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001779 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001780 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001781 mAnimFrameTracker.setActualPresentTime(presentTime);
1782 }
1783 mAnimFrameTracker.advanceFrame();
1784 }
Dan Stozab90cf072015-03-05 11:05:59 -08001785
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001786 mTimeStats.incrementTotalFrames();
1787 if (mHadClientComposition) {
1788 mTimeStats.incrementClientCompositionFrames();
1789 }
1790
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001791 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1792 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001793 return;
1794 }
1795
1796 nsecs_t currentTime = systemTime();
1797 if (mHasPoweredOff) {
1798 mHasPoweredOff = false;
1799 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001800 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001801 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001802 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1803 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001804 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001805 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001806 }
David Sodman4a36e932017-11-07 14:29:47 -08001807 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001808 }
David Sodman4a36e932017-11-07 14:29:47 -08001809 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001810}
1811
1812void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001813 ATRACE_CALL();
1814 ALOGV("rebuildLayerStacks");
1815
Mathias Agopiancd60f992012-08-16 16:28:27 -07001816 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001817 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001818 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001819 mVisibleRegionsDirty = false;
1820 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001821
Jeff Sharkey76488112017-02-27 14:15:18 -07001822 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1823 Region opaqueRegion;
1824 Region dirtyRegion;
1825 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001826 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001827 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1828 const Transform& tr(displayDevice->getTransform());
1829 const Rect bounds(displayDevice->getBounds());
1830 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001831 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001832
Jeff Sharkey76488112017-02-27 14:15:18 -07001833 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001834 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001835 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1836 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001837 Region drawRegion(tr.transform(
1838 layer->visibleNonTransparentRegion));
1839 drawRegion.andSelf(bounds);
1840 if (!drawRegion.isEmpty()) {
1841 layersSortedByZ.add(layer);
1842 } else {
Chia-I Wu30505fb2018-03-26 16:20:31 -07001843 // Clear out the HWC layer if this layer was
1844 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001845 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001846 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001847 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001848 } else {
1849 // WM changes displayDevice->layerStack upon sleep/awake.
1850 // Here we make sure we delete the HWC layers even if
1851 // WM changed their layer stack.
1852 hwcLayerDestroyed = layer->destroyHwcLayer(
1853 displayDevice->getHwcDisplayId());
Chia-I Wu83806892017-11-16 10:50:20 -08001854 }
1855
1856 // If a layer is not going to get a release fence because
1857 // it is invisible, but it is also going to release its
1858 // old buffer, add it to the list of layers needing
1859 // fences.
1860 if (hwcLayerDestroyed) {
1861 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1862 mLayersWithQueuedFrames.cend(), layer);
1863 if (found != mLayersWithQueuedFrames.cend()) {
1864 layersNeedingFences.add(layer);
1865 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001866 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001867 });
1868 }
1869 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001870 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001871 displayDevice->undefinedRegion.set(bounds);
1872 displayDevice->undefinedRegion.subtractSelf(
1873 tr.transform(opaqueRegion));
1874 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001875 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001876 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001877}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001878
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001879// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001880// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001881// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001882// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001883// The returned HDR data space is one of
1884// - Dataspace::UNKNOWN
1885// - Dataspace::BT2020_HLG
1886// - Dataspace::BT2020_PQ
1887Dataspace SurfaceFlinger::getBestDataspace(
1888 const sp<const DisplayDevice>& displayDevice, Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001889 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001890 *outHdrDataSpace = Dataspace::UNKNOWN;
1891
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001892 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001893 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001894 case Dataspace::V0_SCRGB:
1895 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001896 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001897 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001898 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001899 case Dataspace::BT2020_PQ:
1900 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001901 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001902 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001903 case Dataspace::BT2020_HLG:
1904 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001905 // When there's mixed PQ content and HLG content, we set the HDR
1906 // data space to be BT2020_PQ and convert HLG to PQ.
1907 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1908 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001909 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001910 break;
1911 default:
1912 break;
1913 }
Romain Guy54f154a2017-10-24 21:40:32 +01001914 }
1915
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001916 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001917}
1918
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001919// Pick the ColorMode / Dataspace for the display device.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001920void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001921 ColorMode* outMode, Dataspace* outDataSpace,
1922 RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001923 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1924 *outMode = ColorMode::NATIVE;
1925 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001926 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001927 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001928 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001929
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001930 Dataspace hdrDataSpace;
1931 Dataspace bestDataSpace = getBestDataspace(displayDevice, &hdrDataSpace);
1932
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001933 // respect hdrDataSpace only when there is modern HDR support
1934 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
1935 displayDevice->hasModernHdrSupport(hdrDataSpace);
1936 if (isHdr) {
1937 bestDataSpace = hdrDataSpace;
1938 }
1939
Chia-I Wu0d711262018-05-21 15:19:35 -07001940 RenderIntent intent;
1941 switch (mDisplayColorSetting) {
1942 case DisplayColorSetting::MANAGED:
1943 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001944 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001945 break;
1946 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001947 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001948 break;
1949 default: // vendor display color setting
1950 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1951 break;
1952 }
Chia-I Wube02ec02018-05-18 10:59:36 -07001953
Chia-I Wube02ec02018-05-18 10:59:36 -07001954 displayDevice->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001955}
1956
Chia-I Wu30505fb2018-03-26 16:20:31 -07001957void SurfaceFlinger::setUpHWComposer() {
1958 ATRACE_CALL();
1959 ALOGV("setUpHWComposer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001960
Jesse Hall028dc8f2013-08-20 16:35:32 -07001961 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07001962 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07001963 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1964 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1965
1966 // If nothing has changed (!dirty), don't recompose.
1967 // If something changed, but we don't currently have any visible layers,
1968 // and didn't when we last did a composition, then skip it this time.
1969 // The second rule does two things:
1970 // - When all layers are removed from a display, we'll emit one black
1971 // frame, then nothing more until we get new layers.
1972 // - When a display is created with a private layer stack, we won't
1973 // emit any black frames until a layer is added to the layer stack.
1974 bool mustRecompose = dirty && !(empty && wasEmpty);
1975
Dominik Laskowski281644e2018-04-19 15:47:35 -07001976 ALOGV_IF(mDisplays[dpy]->isVirtual(),
Jesse Hallb7a05492014-08-14 15:45:06 -07001977 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1978 mustRecompose ? "doing" : "skipping",
1979 dirty ? "+" : "-",
1980 empty ? "+" : "-",
1981 wasEmpty ? "+" : "-");
1982
Dan Stoza71433162014-02-04 16:22:36 -08001983 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001984
1985 if (mustRecompose) {
1986 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1987 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001988 }
1989
Chia-I Wu30505fb2018-03-26 16:20:31 -07001990 // build the h/w work list
1991 if (CC_UNLIKELY(mGeometryInvalid)) {
1992 mGeometryInvalid = false;
1993 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1994 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1995 const auto hwcId = displayDevice->getHwcDisplayId();
1996 if (hwcId >= 0) {
1997 const Vector<sp<Layer>>& currentLayers(
1998 displayDevice->getVisibleLayersSortedByZ());
1999 for (size_t i = 0; i < currentLayers.size(); i++) {
2000 const auto& layer = currentLayers[i];
2001 if (!layer->hasHwcLayer(hwcId)) {
2002 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
2003 layer->forceClientComposition(hwcId);
2004 continue;
2005 }
2006 }
2007
2008 layer->setGeometry(displayDevice, i);
2009 if (mDebugDisableHWC || mDebugRegion) {
2010 layer->forceClientComposition(hwcId);
2011 }
2012 }
2013 }
2014 }
2015 }
2016
Chia-I Wu30505fb2018-03-26 16:20:31 -07002017 // Set the per-frame data
2018 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2019 auto& displayDevice = mDisplays[displayId];
2020 const auto hwcId = displayDevice->getHwcDisplayId();
2021
2022 if (hwcId < 0) {
2023 continue;
2024 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07002025 if (mDrawingState.colorMatrixChanged) {
2026 displayDevice->setColorTransform(mDrawingState.colorMatrix);
2027 status_t result = getBE().mHwc->setColorTransform(hwcId, mDrawingState.colorMatrix);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002028 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2029 "display %zd: %d", displayId, result);
2030 }
2031 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002032 if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2033 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002034 !displayDevice->hasHDR10Support()) {
Chia-I Wu30505fb2018-03-26 16:20:31 -07002035 layer->forceClientComposition(hwcId);
2036 }
Chia-I Wu01591c92018-05-22 12:03:00 -07002037 if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2038 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Peiyong Linf59a7192018-04-25 11:19:31 -07002039 !displayDevice->hasHLGSupport()) {
2040 layer->forceClientComposition(hwcId);
2041 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002042
2043 if (layer->getForceClientComposition(hwcId)) {
2044 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2045 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2046 continue;
2047 }
2048
2049 layer->setPerFrameData(displayDevice);
2050 }
2051
2052 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002053 ColorMode colorMode;
2054 Dataspace dataSpace;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002055 RenderIntent renderIntent;
2056 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
2057 setActiveColorModeInternal(displayDevice, colorMode, dataSpace, renderIntent);
Chia-I Wu30505fb2018-03-26 16:20:31 -07002058 }
2059 }
2060
Chia-I Wu28f320b2018-05-03 11:02:56 -07002061 mDrawingState.colorMatrixChanged = false;
Chia-I Wu30505fb2018-03-26 16:20:31 -07002062
Dan Stoza9e56aa02015-11-02 13:00:03 -08002063 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002064 auto& displayDevice = mDisplays[displayId];
2065 if (!displayDevice->isDisplayOn()) {
2066 continue;
2067 }
2068
David Sodman105b7dc2017-11-04 20:28:14 -07002069 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002070 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2071 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002072 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002073}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002074
Mathias Agopiancd60f992012-08-16 16:28:27 -07002075void SurfaceFlinger::doComposition() {
2076 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002077 ALOGV("doComposition");
2078
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002079 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002080 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002081 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002082 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002083 // transform the dirty region into this screen's coordinate space
2084 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002085
2086 // repaint the framebuffer (if needed)
2087 doDisplayComposition(hw, dirtyRegion);
2088
Mathias Agopiancd60f992012-08-16 16:28:27 -07002089 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002090 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002091 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002092 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002093 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002094}
2095
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002096void SurfaceFlinger::postFramebuffer()
2097{
Mathias Agopian841cde52012-03-01 15:44:37 -08002098 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002099 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002100
Mathias Agopiana44b0412011-10-16 18:46:35 -07002101 const nsecs_t now = systemTime();
2102 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002103
Dan Stoza9e56aa02015-11-02 13:00:03 -08002104 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2105 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002106 if (!displayDevice->isDisplayOn()) {
2107 continue;
2108 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002109 const auto hwcId = displayDevice->getHwcDisplayId();
2110 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002111 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002112 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002113 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002114 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002115 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002116 // The layer buffer from the previous frame (if any) is released
2117 // by HWC only when the release fence from this frame (if any) is
2118 // signaled. Always get the release fence from HWC first.
2119 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002120 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002121
2122 // If the layer was client composited in the previous frame, we
2123 // need to merge with the previous client target acquire fence.
2124 // Since we do not track that, always merge with the current
2125 // client target acquire fence when it is available, even though
2126 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002127 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002128 releaseFence = Fence::merge("LayerRelease", releaseFence,
2129 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002130 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002131
David Sodmanb8af7922017-12-21 15:17:55 -08002132 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002133 }
Chia-I Wu83806892017-11-16 10:50:20 -08002134
2135 // We've got a list of layers needing fences, that are disjoint with
2136 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2137 // supply them with the present fence.
2138 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002139 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002140 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002141 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002142 }
2143 }
2144
Dan Stoza9e56aa02015-11-02 13:00:03 -08002145 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002146 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002147 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002148 }
2149
Mathias Agopiana44b0412011-10-16 18:46:35 -07002150 mLastSwapBufferTime = systemTime() - now;
2151 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002152
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002153 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002154 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2155 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2156 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2157 logFrameStats();
2158 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002159 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002160}
2161
Mathias Agopian87baae12012-07-31 12:38:26 -07002162void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002163{
Mathias Agopian841cde52012-03-01 15:44:37 -08002164 ATRACE_CALL();
2165
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002166 // here we keep a copy of the drawing state (that is the state that's
2167 // going to be overwritten by handleTransactionLocked()) outside of
2168 // mStateLock so that the side-effects of the State assignment
2169 // don't happen with mStateLock held (which can cause deadlocks).
2170 State drawingState(mDrawingState);
2171
Mathias Agopianca4d3602011-05-19 15:38:14 -07002172 Mutex::Autolock _l(mStateLock);
2173 const nsecs_t now = systemTime();
2174 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002175
Mathias Agopianca4d3602011-05-19 15:38:14 -07002176 // Here we're guaranteed that some transaction flags are set
2177 // so we can call handleTransactionLocked() unconditionally.
2178 // We call getTransactionFlags(), which will also clear the flags,
2179 // with mStateLock held to guarantee that mCurrentState won't change
2180 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002181
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002182 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002183 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002184 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002185
Mathias Agopianca4d3602011-05-19 15:38:14 -07002186 mLastTransactionTime = systemTime() - now;
2187 mDebugInTransaction = 0;
2188 invalidateHwcGeometry();
2189 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002190}
2191
Lloyd Pique715a2c12017-12-14 17:18:08 -08002192DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002193 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002194 // Figure out whether the event is for the primary display or an
2195 // external display by matching the Hwc display id against one for a
2196 // connected display. If we did not find a match, we then check what
2197 // displays are not already connected to determine the type. If we don't
2198 // have a connected primary display, we assume the new display is meant to
2199 // be the primary display, and then if we don't have an external display,
2200 // we assume it is that.
2201 const auto primaryDisplayId =
2202 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2203 const auto externalDisplayId =
2204 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2205 if (primaryDisplayId && primaryDisplayId == display) {
2206 return DisplayDevice::DISPLAY_PRIMARY;
2207 } else if (externalDisplayId && externalDisplayId == display) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002208 return DisplayDevice::DISPLAY_EXTERNAL;
Lloyd Pique715a2c12017-12-14 17:18:08 -08002209 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2210 return DisplayDevice::DISPLAY_PRIMARY;
2211 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2212 return DisplayDevice::DISPLAY_EXTERNAL;
2213 }
2214
2215 return DisplayDevice::DISPLAY_ID_INVALID;
2216}
2217
Lloyd Piqueba04e622017-12-14 17:11:26 -08002218void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2219 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002220 auto displayType = determineDisplayType(event.display, event.connection);
2221 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2222 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2223 continue;
2224 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002225
2226 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2227 ALOGE("External displays are not supported by the vr hardware composer.");
2228 continue;
2229 }
2230
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002231 const auto displayId =
2232 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
2233 if (displayId) {
2234 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.display, *displayId);
2235 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002236
2237 if (event.connection == HWC2::Connection::Connected) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002238 if (!mBuiltinDisplays[displayType].get()) {
2239 ALOGV("Creating built in display %d", displayType);
2240 mBuiltinDisplays[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002241 DisplayDeviceState info;
2242 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002243 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2244 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002245 info.isSecure = true; // All physical displays are currently considered secure.
Steven Thomaseb6d2052018-03-20 15:40:48 -07002246 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
2247 mInterceptor->saveDisplayCreation(info);
2248 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002249 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002250 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002251
Lloyd Piquefcd86612017-12-14 17:15:36 -08002252 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2253 if (idx >= 0) {
2254 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002255 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002256 mCurrentState.displays.removeItemsAt(idx);
2257 }
2258 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002259 }
2260
2261 processDisplayChangesLocked();
2262 }
2263
2264 mPendingHotplugEvents.clear();
2265}
2266
Lloyd Pique99d3da52018-01-22 17:48:03 -08002267sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2268 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2269 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002270 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002271 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002272
Lloyd Pique99d3da52018-01-22 17:48:03 -08002273 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002274 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002275 for (ColorMode colorMode : modes) {
2276 switch (colorMode) {
2277 case ColorMode::DISPLAY_P3:
2278 case ColorMode::ADOBE_RGB:
2279 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002280 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002281 break;
2282 default:
2283 break;
2284 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002285
2286 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2287 colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002288 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002289 }
2290 }
2291
Peiyong Lin62665892018-04-16 11:07:44 -07002292 HdrCapabilities hdrCapabilities;
2293 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002294
2295 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2296 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2297
2298 /*
2299 * Create our display's surface
2300 */
2301 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2302 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002303 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002304 renderSurface->setNativeWindow(nativeWindow.get());
2305 const int displayWidth = renderSurface->queryWidth();
2306 const int displayHeight = renderSurface->queryHeight();
2307
2308 // Make sure that composition can never be stalled by a virtual display
2309 // consumer that isn't processing buffers fast enough. We have to do this
2310 // in two places:
2311 // * Here, in case the display is composed entirely by HWC.
2312 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2313 // window's swap interval in eglMakeCurrent, so they'll override the
2314 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002315 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002316 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2317 }
2318
2319 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002320 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002321
2322 sp<DisplayDevice> hw =
2323 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2324 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin0ac5f4e2018-04-19 22:06:34 -07002325 hasWideColorGamut, hdrCapabilities,
2326 getHwComposer().getSupportedPerFrameMetadata(hwcId),
Chia-I Wube02ec02018-05-18 10:59:36 -07002327 hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002328
2329 if (maxFrameBufferAcquiredBuffers >= 3) {
2330 nativeWindowSurface->preallocateBuffers();
2331 }
2332
2333 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002334 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2335 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002336 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002337 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002338 }
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002339 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace,
2340 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002341 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
2342 hw->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
2343 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002344 hw->setLayerStack(state.layerStack);
2345 hw->setProjection(state.orientation, state.viewport, state.frame);
2346 hw->setDisplayName(state.displayName);
2347
2348 return hw;
2349}
2350
Lloyd Pique347200f2017-12-14 17:00:15 -08002351void SurfaceFlinger::processDisplayChangesLocked() {
2352 // here we take advantage of Vector's copy-on-write semantics to
2353 // improve performance by skipping the transaction entirely when
2354 // know that the lists are identical
2355 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2356 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2357 if (!curr.isIdenticalTo(draw)) {
2358 mVisibleRegionsDirty = true;
2359 const size_t cc = curr.size();
2360 size_t dc = draw.size();
2361
2362 // find the displays that were removed
2363 // (ie: in drawing state but not in current state)
2364 // also handle displays that changed
2365 // (ie: displays that are in both lists)
2366 for (size_t i = 0; i < dc;) {
2367 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2368 if (j < 0) {
2369 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002370 // Call makeCurrent() on the primary display so we can
2371 // be sure that nothing associated with this display
2372 // is current.
2373 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2374 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2375 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2376 if (hw != nullptr) hw->disconnect(getHwComposer());
2377 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2378 mEventThread->onHotplugReceived(draw[i].type, false);
2379 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002380 } else {
2381 // this display is in both lists. see if something changed.
2382 const DisplayDeviceState& state(curr[j]);
2383 const wp<IBinder>& display(curr.keyAt(j));
2384 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2385 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2386 if (state_binder != draw_binder) {
2387 // changing the surface is like destroying and
2388 // recreating the DisplayDevice, so we just remove it
2389 // from the drawing state, so that it get re-added
2390 // below.
2391 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2392 if (hw != nullptr) hw->disconnect(getHwComposer());
2393 mDisplays.removeItem(display);
2394 mDrawingState.displays.removeItemsAt(i);
2395 dc--;
2396 // at this point we must loop to the next item
2397 continue;
2398 }
2399
2400 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2401 if (disp != nullptr) {
2402 if (state.layerStack != draw[i].layerStack) {
2403 disp->setLayerStack(state.layerStack);
2404 }
2405 if ((state.orientation != draw[i].orientation) ||
2406 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2407 disp->setProjection(state.orientation, state.viewport, state.frame);
2408 }
2409 if (state.width != draw[i].width || state.height != draw[i].height) {
2410 disp->setDisplaySize(state.width, state.height);
2411 }
2412 }
2413 }
2414 ++i;
2415 }
2416
2417 // find displays that were added
2418 // (ie: in current state but not in drawing state)
2419 for (size_t i = 0; i < cc; i++) {
2420 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2421 const DisplayDeviceState& state(curr[i]);
2422
2423 sp<DisplaySurface> dispSurface;
2424 sp<IGraphicBufferProducer> producer;
2425 sp<IGraphicBufferProducer> bqProducer;
2426 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002427 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002428
2429 int32_t hwcId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002430 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002431 // Virtual displays without a surface are dormant:
2432 // they have external state (layer stack, projection,
2433 // etc.) but no internal state (i.e. a DisplayDevice).
2434 if (state.surface != nullptr) {
2435 // Allow VR composer to use virtual displays.
2436 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2437 int width = 0;
2438 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2439 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2440 int height = 0;
2441 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2442 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2443 int intFormat = 0;
2444 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2445 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002446 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002447
2448 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2449 }
2450
2451 // TODO: Plumb requested format back up to consumer
2452
2453 sp<VirtualDisplaySurface> vds =
2454 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2455 bqProducer, bqConsumer,
2456 state.displayName);
2457
2458 dispSurface = vds;
2459 producer = vds;
2460 }
2461 } else {
2462 ALOGE_IF(state.surface != nullptr,
2463 "adding a supported display, but rendering "
2464 "surface is provided (%p), ignoring it",
2465 state.surface.get());
2466
2467 hwcId = state.type;
2468 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2469 producer = bqProducer;
2470 }
2471
2472 const wp<IBinder>& display(curr.keyAt(i));
2473 if (dispSurface != nullptr) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002474 mDisplays.add(display,
2475 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2476 producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002477 if (!state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002478 mEventThread->onHotplugReceived(state.type, true);
2479 }
2480 }
2481 }
2482 }
2483 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002484
2485 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002486}
2487
Mathias Agopian87baae12012-07-31 12:38:26 -07002488void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002489{
Dan Stoza7dde5992015-05-22 09:51:44 -07002490 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002491 mCurrentState.traverseInZOrder([](Layer* layer) {
2492 layer->notifyAvailableFrames();
2493 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002494
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002495 /*
2496 * Traversal of the children
2497 * (perform the transaction for each of them if needed)
2498 */
2499
Mathias Agopian3559b072012-08-15 13:46:03 -07002500 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002501 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002502 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002503 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002504
2505 const uint32_t flags = layer->doTransaction(0);
2506 if (flags & Layer::eVisibleRegion)
2507 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002508 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002509 }
2510
2511 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002512 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002513 */
2514
Mathias Agopiane57f2922012-08-09 16:29:12 -07002515 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002516 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002517 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002518 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002519
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002520 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002521 // The transform hint might have changed for some layers
2522 // (either because a display has changed, or because a layer
2523 // as changed).
2524 //
2525 // Walk through all the layers in currentLayers,
2526 // and update their transform hint.
2527 //
2528 // If a layer is visible only on a single display, then that
2529 // display is used to calculate the hint, otherwise we use the
2530 // default display.
2531 //
2532 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2533 // the hint is set before we acquire a buffer from the surface texture.
2534 //
2535 // NOTE: layer transactions have taken place already, so we use their
2536 // drawing state. However, SurfaceFlinger's own transaction has not
2537 // happened yet, so we must use the current state layer list
2538 // (soon to become the drawing state list).
2539 //
2540 sp<const DisplayDevice> disp;
2541 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002542 bool first = true;
2543 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002544 // NOTE: we rely on the fact that layers are sorted by
2545 // layerStack first (so we don't have to traverse the list
2546 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002547 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002548 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002549 currentlayerStack = layerStack;
2550 // figure out if this layerstack is mirrored
2551 // (more than one display) if so, pick the default display,
2552 // if not, pick the only display it's on.
2553 disp.clear();
2554 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2555 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002556 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002557 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002558 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002559 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002560 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002561 break;
2562 }
2563 }
2564 }
2565 }
Chet Haase91d25932013-04-11 15:24:55 -07002566
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002567 if (disp == nullptr) {
2568 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2569 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002570
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002571 // could be null when this layer is using a layerStack
2572 // that is not visible on any display. Also can occur at
2573 // screen off/on times.
2574 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002575 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002576
2577 // disp can be null if there is no display available at all to get
2578 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002579 if (disp != nullptr) {
2580 layer->updateTransformHint(disp);
2581 }
Robert Carr2047fae2016-11-28 14:09:09 -08002582
2583 first = false;
2584 });
Mathias Agopian84300952012-11-21 16:02:13 -08002585 }
2586
2587
Mathias Agopian3559b072012-08-15 13:46:03 -07002588 /*
2589 * Perform our own transaction if needed
2590 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002591
2592 if (mLayersAdded) {
2593 mLayersAdded = false;
2594 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002595 mVisibleRegionsDirty = true;
2596 }
2597
2598 // some layers might have been removed, so
2599 // we need to update the regions they're exposing.
2600 if (mLayersRemoved) {
2601 mLayersRemoved = false;
2602 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002603 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002604 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002605 // this layer is not visible anymore
2606 // TODO: we could traverse the tree from front to back and
2607 // compute the actual visible region
2608 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002609 Region visibleReg;
2610 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002611 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002612 }
Robert Carr2047fae2016-11-28 14:09:09 -08002613 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002614 }
2615
2616 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002617
2618 updateCursorAsync();
2619}
2620
2621void SurfaceFlinger::updateCursorAsync()
2622{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002623 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2624 auto& displayDevice = mDisplays[displayId];
2625 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002626 continue;
2627 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002628
2629 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2630 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002631 }
2632 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002633}
2634
2635void SurfaceFlinger::commitTransaction()
2636{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002637 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002638 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002639 for (const auto& l : mLayersPendingRemoval) {
2640 recordBufferingStats(l->getName().string(),
2641 l->getOccupancyHistory(true));
2642 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002643 }
2644 mLayersPendingRemoval.clear();
2645 }
2646
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002647 // If this transaction is part of a window animation then the next frame
2648 // we composite should be considered an animation as well.
2649 mAnimCompositionPending = mAnimTransactionPending;
2650
Mathias Agopian4fec8732012-06-29 14:12:52 -07002651 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002652 // clear the "changed" flags in current state
2653 mCurrentState.colorMatrixChanged = false;
2654
Robert Carr1f0a16a2016-10-24 16:27:39 -07002655 mDrawingState.traverseInZOrder([](Layer* layer) {
2656 layer->commitChildList();
2657 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002658 mTransactionPending = false;
2659 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002660 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002661}
2662
Chia-I Wuab0c3192017-08-01 11:29:00 -07002663void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002664 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002665{
Mathias Agopian841cde52012-03-01 15:44:37 -08002666 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002667 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002668
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002669 Region aboveOpaqueLayers;
2670 Region aboveCoveredLayers;
2671 Region dirty;
2672
Mathias Agopian87baae12012-07-31 12:38:26 -07002673 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002674
Robert Carr2047fae2016-11-28 14:09:09 -08002675 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002676 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002677 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002678
Jesse Hall01e29052013-02-19 16:13:35 -08002679 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002680 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002681 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002682
Mathias Agopianab028732010-03-16 16:41:46 -07002683 /*
2684 * opaqueRegion: area of a surface that is fully opaque.
2685 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002686 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002687
2688 /*
2689 * visibleRegion: area of a surface that is visible on screen
2690 * and not fully transparent. This is essentially the layer's
2691 * footprint minus the opaque regions above it.
2692 * Areas covered by a translucent surface are considered visible.
2693 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002694 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002695
2696 /*
2697 * coveredRegion: area of a surface that is covered by all
2698 * visible regions above it (which includes the translucent areas).
2699 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002700 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002701
Jesse Halla8026d22012-09-25 13:25:04 -07002702 /*
2703 * transparentRegion: area of a surface that is hinted to be completely
2704 * transparent. This is only used to tell when the layer has no visible
2705 * non-transparent regions and can be removed from the layer list. It
2706 * does not affect the visibleRegion of this layer or any layers
2707 * beneath it. The hint may not be correct if apps don't respect the
2708 * SurfaceView restrictions (which, sadly, some don't).
2709 */
2710 Region transparentRegion;
2711
Mathias Agopianab028732010-03-16 16:41:46 -07002712
2713 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002714 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002715 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002716 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002717 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002718 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002719 if (!visibleRegion.isEmpty()) {
2720 // Remove the transparent area from the visible region
2721 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002722 if (tr.preserveRects()) {
2723 // transform the transparent region
2724 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002725 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002726 // transformation too complex, can't do the
2727 // transparent region optimization.
2728 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002729 }
Mathias Agopianab028732010-03-16 16:41:46 -07002730 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002731
Mathias Agopianab028732010-03-16 16:41:46 -07002732 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002733 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002734 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002735 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2736 // the opaque region is the layer's footprint
2737 opaqueRegion = visibleRegion;
2738 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002739 }
2740 }
2741
Robert Carre5f4f692018-01-12 13:12:28 -08002742 if (visibleRegion.isEmpty()) {
2743 layer->clearVisibilityRegions();
2744 return;
2745 }
2746
Mathias Agopianab028732010-03-16 16:41:46 -07002747 // Clip the covered region to the visible region
2748 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2749
2750 // Update aboveCoveredLayers for next (lower) layer
2751 aboveCoveredLayers.orSelf(visibleRegion);
2752
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002753 // subtract the opaque region covered by the layers above us
2754 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002755
2756 // compute this layer's dirty region
2757 if (layer->contentDirty) {
2758 // we need to invalidate the whole region
2759 dirty = visibleRegion;
2760 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002761 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002762 layer->contentDirty = false;
2763 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002764 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002765 * the exposed region consists of two components:
2766 * 1) what's VISIBLE now and was COVERED before
2767 * 2) what's EXPOSED now less what was EXPOSED before
2768 *
2769 * note that (1) is conservative, we start with the whole
2770 * visible region but only keep what used to be covered by
2771 * something -- which mean it may have been exposed.
2772 *
2773 * (2) handles areas that were not covered by anything but got
2774 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002775 */
Mathias Agopianab028732010-03-16 16:41:46 -07002776 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002777 const Region oldVisibleRegion = layer->visibleRegion;
2778 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002779 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2780 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002781 }
2782 dirty.subtractSelf(aboveOpaqueLayers);
2783
2784 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002785 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002786
Mathias Agopianab028732010-03-16 16:41:46 -07002787 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002788 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002789
Jesse Halla8026d22012-09-25 13:25:04 -07002790 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002791 layer->setVisibleRegion(visibleRegion);
2792 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002793 layer->setVisibleNonTransparentRegion(
2794 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002795 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002796
Mathias Agopian87baae12012-07-31 12:38:26 -07002797 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002798}
2799
Chia-I Wuab0c3192017-08-01 11:29:00 -07002800void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002801 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002802 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002803 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002804 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002805 }
2806 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002807}
2808
Dan Stoza6b9454d2014-11-07 16:00:59 -08002809bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002810{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002811 ALOGV("handlePageFlip");
2812
Brian Andersond6927fb2016-07-23 23:37:30 -07002813 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002814
Mathias Agopian4fec8732012-06-29 14:12:52 -07002815 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002816 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002817 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002818
2819 // Store the set of layers that need updates. This set must not change as
2820 // buffers are being latched, as this could result in a deadlock.
2821 // Example: Two producers share the same command stream and:
2822 // 1.) Layer 0 is latched
2823 // 2.) Layer 0 gets a new frame
2824 // 2.) Layer 1 gets a new frame
2825 // 3.) Layer 1 is latched.
2826 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2827 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002828 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002829 if (layer->hasQueuedFrame()) {
2830 frameQueued = true;
2831 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002832 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002833 } else {
2834 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002835 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002836 } else {
2837 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002838 }
Robert Carr2047fae2016-11-28 14:09:09 -08002839 });
2840
Dan Stoza9e56aa02015-11-02 13:00:03 -08002841 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002842 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002843 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002844 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002845 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002846 newDataLatched = true;
2847 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002848 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002849
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002850 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002851
2852 // If we will need to wake up at some time in the future to deal with a
2853 // queued frame that shouldn't be displayed during this vsync period, wake
2854 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002855 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002856 signalLayerUpdate();
2857 }
2858
2859 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002860 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002861}
2862
Mathias Agopianad456f92011-01-13 17:53:01 -08002863void SurfaceFlinger::invalidateHwcGeometry()
2864{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002865 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002866}
2867
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002868
Fabien Sanglard830b8472016-11-30 16:35:58 -08002869void SurfaceFlinger::doDisplayComposition(
2870 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002871 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002872{
Dan Stoza71433162014-02-04 16:22:36 -08002873 // We only need to actually compose the display if:
2874 // 1) It is being handled by hardware composer, which may need this to
2875 // keep its virtual display state machine in sync, or
2876 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002877 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002878 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002879 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002880 return;
2881 }
2882
Dan Stoza9e56aa02015-11-02 13:00:03 -08002883 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002884 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002885
2886 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002887 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002888}
2889
Chia-I Wub02087d2017-11-09 10:19:54 -08002890bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002891{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002892 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002893
Chia-I Wub02087d2017-11-09 10:19:54 -08002894 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002895 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002896 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002897 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002898 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002899
Chia-I Wu8e50e692018-05-04 10:12:37 -07002900 bool applyColorMatrix = false;
Peiyong Lin00f9c022018-05-09 15:35:33 -07002901 bool needsLegacyColorMatrix = false;
2902 bool legacyColorMatrixApplied = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002903
Dan Stoza9e56aa02015-11-02 13:00:03 -08002904 if (hasClientComposition) {
2905 ALOGV("hasClientComposition");
2906
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002907 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002908 if (displayDevice->hasWideColorGamut()) {
2909 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002910 }
2911 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002912 getBE().mRenderEngine->setDisplayMaxLuminance(
2913 displayDevice->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002914
Chia-I Wu8e50e692018-05-04 10:12:37 -07002915 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2916 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2917 HWC2::Capability::SkipClientColorTransform);
2918
2919 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2920 if (applyColorMatrix) {
Peiyong Lin00f9c022018-05-09 15:35:33 -07002921 getRenderEngine().setupColorTransform(mDrawingState.colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002922 }
2923
Chia-I Wubbb44462018-05-21 15:33:27 -07002924 needsLegacyColorMatrix =
Chia-I Wu0d711262018-05-21 15:19:35 -07002925 (displayDevice->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
Chia-I Wubbb44462018-05-21 15:33:27 -07002926 outputDataspace != Dataspace::UNKNOWN &&
2927 outputDataspace != Dataspace::SRGB);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002928
Chia-I Wu7f402902017-11-09 12:51:10 -08002929 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002930 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskibf170d92018-04-19 15:08:05 -07002931 displayDevice->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002932 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002933
2934 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002935 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002936 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2937 }
2938 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002939 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002940
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002941 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002942 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002943 // when using overlays, we assume a fully transparent framebuffer
2944 // NOTE: we could reduce how much we need to clear, for instance
2945 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002946 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002947 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002948 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002949 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002950 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002951 // we're left with the letterbox region
2952 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002953 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002954
2955 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002956 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002957
Mathias Agopianb9494d52012-04-18 02:28:45 -07002958 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002959 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002960 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002961 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002962 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002963 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002964
Dominik Laskowski281644e2018-04-19 15:47:35 -07002965 if (!displayDevice->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002966 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002967 // scissor on the main display. It should never be needed
2968 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002969 const Rect& bounds(displayDevice->getBounds());
2970 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002971 if (scissor != bounds) {
2972 // scissor doesn't match the screen's dimensions, so we
2973 // need to clear everything outside of it and enable
2974 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002975
Mathias Agopianf45c5102012-10-24 16:29:17 -07002976 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002977 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002978 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002979 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002980 }
2981 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002982 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002983
Mathias Agopian85d751c2012-08-29 16:59:24 -07002984 /*
2985 * and then, render the layers targeted at the framebuffer
2986 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002987
Dan Stoza9e56aa02015-11-02 13:00:03 -08002988 ALOGV("Rendering client layers");
2989 const Transform& displayTransform = displayDevice->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002990 bool firstLayer = true;
2991 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2992 const Region clip(bounds.intersect(
2993 displayTransform.transform(layer->visibleRegion)));
2994 ALOGV("Layer: %s", layer->getName().string());
2995 ALOGV(" Composition type: %s",
2996 to_string(layer->getCompositionType(hwcId)).c_str());
2997 if (!clip.isEmpty()) {
2998 switch (layer->getCompositionType(hwcId)) {
2999 case HWC2::Composition::Cursor:
3000 case HWC2::Composition::Device:
3001 case HWC2::Composition::Sideband:
3002 case HWC2::Composition::SolidColor: {
3003 const Layer::State& state(layer->getDrawingState());
3004 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
3005 layer->isOpaque(state) && (state.color.a == 1.0f)
3006 && hasClientComposition) {
3007 // never clear the very first layer since we're
3008 // guaranteed the FB is already cleared
3009 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003010 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003011 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003012 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003013 case HWC2::Composition::Client: {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003014 // switch color matrices lazily
Peiyong Lin00f9c022018-05-09 15:35:33 -07003015 if (layer->isLegacyDataSpace() && needsLegacyColorMatrix) {
3016 if (!legacyColorMatrixApplied) {
3017 getRenderEngine().setSaturationMatrix(mLegacySrgbSaturationMatrix);
3018 legacyColorMatrixApplied = true;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003019 }
Peiyong Lin00f9c022018-05-09 15:35:33 -07003020 } else if (legacyColorMatrixApplied) {
3021 getRenderEngine().setSaturationMatrix(mat4());
3022 legacyColorMatrixApplied = false;
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003023 }
Chia-I Wu8e50e692018-05-04 10:12:37 -07003024
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003025 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003026 break;
3027 }
3028 default:
3029 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003030 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003031 } else {
3032 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003033 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003034 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003035 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003036
Peiyong Lin00f9c022018-05-09 15:35:33 -07003037 if (applyColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003038 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003039 }
Peiyong Lin00f9c022018-05-09 15:35:33 -07003040 if (needsLegacyColorMatrix && legacyColorMatrixApplied) {
3041 getRenderEngine().setSaturationMatrix(mat4());
3042 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003043
Mathias Agopianf45c5102012-10-24 16:29:17 -07003044 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003045 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003046 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003047}
3048
Fabien Sanglard830b8472016-11-30 16:35:58 -08003049void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3050 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003051 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003052 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003053}
3054
Dan Stoza7d89d062015-04-30 13:29:25 -07003055status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003056 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003057 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003058 const sp<Layer>& lbc,
3059 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003060{
Dan Stoza7d89d062015-04-30 13:29:25 -07003061 // add this layer to the current state list
3062 {
3063 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003064 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003065 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3066 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003067 return NO_MEMORY;
3068 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003069 if (parent == nullptr) {
3070 mCurrentState.layersSortedByZ.add(lbc);
3071 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003072 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003073 ALOGE("addClientLayer called with a removed parent");
3074 return NAME_NOT_FOUND;
3075 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003076 parent->addChild(lbc);
3077 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003078
Yiwei Zhang243b3782018-05-15 17:40:04 -07003079 if (gbc != nullptr) {
3080 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3081 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3082 mMaxGraphicBufferProducerListSize,
3083 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3084 mGraphicBufferProducerList.size(),
3085 mMaxGraphicBufferProducerListSize, mNumLayers);
3086 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003087 mLayersAdded = true;
3088 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003089 }
3090
Mathias Agopian96f08192010-06-02 23:28:45 -07003091 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003092 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003093
Dan Stoza7d89d062015-04-30 13:29:25 -07003094 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003095}
3096
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003097status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003098 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003099 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3100}
Robert Carr7f9b8992017-03-10 11:08:39 -08003101
chaviwca27f252018-02-06 16:46:39 -08003102status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3103 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003104 if (layer->isPendingRemoval()) {
3105 return NO_ERROR;
3106 }
3107
Robert Carr1f0a16a2016-10-24 16:27:39 -07003108 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003109 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003110 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003111 if (topLevelOnly) {
3112 return NO_ERROR;
3113 }
3114
Chia-I Wu98f1c102017-05-30 14:54:08 -07003115 sp<Layer> ancestor = p;
3116 while (ancestor->getParent() != nullptr) {
3117 ancestor = ancestor->getParent();
3118 }
3119 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3120 ALOGE("removeLayer called with a layer whose parent has been removed");
3121 return NAME_NOT_FOUND;
3122 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003123
3124 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003125 } else {
3126 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003127 }
3128
Robert Carr136e2f62017-02-08 17:54:29 -08003129 // As a matter of normal operation, the LayerCleaner will produce a second
3130 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3131 // so we will succeed in promoting it, but it's already been removed
3132 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3133 // otherwise something has gone wrong and we are leaking the layer.
3134 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003135 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3136 layer->getName().string(),
3137 (p != nullptr) ? p->getName().string() : "no-parent");
3138 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003139 } else if (index < 0) {
3140 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003141 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003142
Chia-I Wuc6657022017-08-15 11:18:17 -07003143 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003144 mLayersPendingRemoval.add(layer);
3145 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003146 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003147 setTransactionFlags(eTransactionNeeded);
3148 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003149}
3150
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003151uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003152 return android_atomic_release_load(&mTransactionFlags);
3153}
3154
Mathias Agopian3f844832013-08-07 21:24:32 -07003155uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003156 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3157}
3158
Mathias Agopian3f844832013-08-07 21:24:32 -07003159uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003160 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3161}
3162
3163uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3164 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003165 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003166 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003167 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003168 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003169 }
3170 return old;
3171}
3172
chaviwca27f252018-02-06 16:46:39 -08003173bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3174 for (const ComposerState& state : states) {
3175 // Here we need to check that the interface we're given is indeed
3176 // one of our own. A malicious client could give us a nullptr
3177 // IInterface, or one of its own or even one of our own but a
3178 // different type. All these situations would cause us to crash.
3179 if (state.client == nullptr) {
3180 return true;
3181 }
3182
3183 sp<IBinder> binder = IInterface::asBinder(state.client);
3184 if (binder == nullptr) {
3185 return true;
3186 }
3187
3188 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3189 return true;
3190 }
3191 }
3192 return false;
3193}
3194
Mathias Agopian8b33f032012-07-24 20:43:54 -07003195void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003196 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003197 const Vector<DisplayState>& displays,
3198 uint32_t flags)
3199{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003200 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003201 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003202 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003203
chaviwca27f252018-02-06 16:46:39 -08003204 if (containsAnyInvalidClientState(states)) {
3205 return;
3206 }
3207
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003208 if (flags & eAnimation) {
3209 // For window updates that are part of an animation we must wait for
3210 // previous animation "frames" to be handled.
3211 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003212 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003213 if (CC_UNLIKELY(err != NO_ERROR)) {
3214 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003215 // caller after a few seconds.
3216 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3217 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003218 mAnimTransactionPending = false;
3219 break;
3220 }
3221 }
3222 }
3223
chaviwca27f252018-02-06 16:46:39 -08003224 for (const DisplayState& display : displays) {
3225 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003226 }
3227
chaviwca27f252018-02-06 16:46:39 -08003228 for (const ComposerState& state : states) {
3229 transactionFlags |= setClientStateLocked(state);
3230 }
3231
3232 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3233 // as destroyed should only occur after setting all other states. This is to allow for a
3234 // child re-parent to happen before marking its original parent as destroyed (which would
3235 // then mark the child as destroyed).
3236 for (const ComposerState& state : states) {
3237 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003238 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003239
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003240 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3241 // anyway. This can be used as a flush mechanism for previous async transactions.
3242 // Empty animation transaction can be used to simulate back-pressure, so also force a
3243 // transaction for empty animation transactions.
3244 if (transactionFlags == 0 &&
3245 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003246 transactionFlags = eTransactionNeeded;
3247 }
3248
Mathias Agopian386aa982011-11-07 21:58:03 -08003249 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003250 if (mInterceptor->isEnabled()) {
3251 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003252 }
Irvel468051e2016-06-13 16:44:44 -07003253
Mathias Agopian386aa982011-11-07 21:58:03 -08003254 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003255 const auto start = (flags & eEarlyWakeup)
3256 ? VSyncModulator::TransactionStart::EARLY
3257 : VSyncModulator::TransactionStart::NORMAL;
3258 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003259
3260 // if this is a synchronous transaction, wait for it to take effect
3261 // before returning.
3262 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003263 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003264 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003265 if (flags & eAnimation) {
3266 mAnimTransactionPending = true;
3267 }
3268 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003269 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3270 if (CC_UNLIKELY(err != NO_ERROR)) {
3271 // just in case something goes wrong in SF, return to the
3272 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003273 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3274 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003275 break;
3276 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003277 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003278 }
3279}
3280
Mathias Agopiane57f2922012-08-09 16:29:12 -07003281uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3282{
Jesse Hall9a143922012-10-04 16:29:19 -07003283 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3284 if (dpyIdx < 0)
3285 return 0;
3286
Mathias Agopiane57f2922012-08-09 16:29:12 -07003287 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003288 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003289 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003290 const uint32_t what = s.what;
3291 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003292 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003293 disp.surface = s.surface;
3294 flags |= eDisplayTransactionNeeded;
3295 }
3296 }
3297 if (what & DisplayState::eLayerStackChanged) {
3298 if (disp.layerStack != s.layerStack) {
3299 disp.layerStack = s.layerStack;
3300 flags |= eDisplayTransactionNeeded;
3301 }
3302 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003303 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003304 if (disp.orientation != s.orientation) {
3305 disp.orientation = s.orientation;
3306 flags |= eDisplayTransactionNeeded;
3307 }
3308 if (disp.frame != s.frame) {
3309 disp.frame = s.frame;
3310 flags |= eDisplayTransactionNeeded;
3311 }
3312 if (disp.viewport != s.viewport) {
3313 disp.viewport = s.viewport;
3314 flags |= eDisplayTransactionNeeded;
3315 }
3316 }
Michael Lentine47e45402014-07-18 15:34:25 -07003317 if (what & DisplayState::eDisplaySizeChanged) {
3318 if (disp.width != s.width) {
3319 disp.width = s.width;
3320 flags |= eDisplayTransactionNeeded;
3321 }
3322 if (disp.height != s.height) {
3323 disp.height = s.height;
3324 flags |= eDisplayTransactionNeeded;
3325 }
3326 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003327 }
3328 return flags;
3329}
3330
chaviwca27f252018-02-06 16:46:39 -08003331uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3332 const layer_state_t& s = composerState.state;
3333 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3334
Mathias Agopian13127d82013-03-05 17:47:11 -08003335 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003336 if (layer == nullptr) {
3337 return 0;
3338 }
3339
3340 if (layer->isPendingRemoval()) {
3341 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3342 return 0;
3343 }
3344
3345 uint32_t flags = 0;
3346
3347 const uint32_t what = s.what;
3348 bool geometryAppliesWithResize =
3349 what & layer_state_t::eGeometryAppliesWithResize;
3350 if (what & layer_state_t::ePositionChanged) {
3351 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3352 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003353 }
chaviw8b3871a2017-11-01 17:41:01 -07003354 }
3355 if (what & layer_state_t::eLayerChanged) {
3356 // NOTE: index needs to be calculated before we update the state
3357 const auto& p = layer->getParent();
3358 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003359 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003360 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003361 mCurrentState.layersSortedByZ.removeAt(idx);
3362 mCurrentState.layersSortedByZ.add(layer);
3363 // we need traversal (state changed)
3364 // AND transaction (list changed)
3365 flags |= eTransactionNeeded|eTraversalNeeded;
3366 }
chaviw8b3871a2017-11-01 17:41:01 -07003367 } else {
3368 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003369 flags |= eTransactionNeeded|eTraversalNeeded;
3370 }
3371 }
chaviw8b3871a2017-11-01 17:41:01 -07003372 }
3373 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003374 // NOTE: index needs to be calculated before we update the state
3375 const auto& p = layer->getParent();
3376 if (p == nullptr) {
3377 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3378 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3379 mCurrentState.layersSortedByZ.removeAt(idx);
3380 mCurrentState.layersSortedByZ.add(layer);
3381 // we need traversal (state changed)
3382 // AND transaction (list changed)
3383 flags |= eTransactionNeeded|eTraversalNeeded;
3384 }
3385 } else {
3386 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3387 flags |= eTransactionNeeded|eTraversalNeeded;
3388 }
chaviw8b3871a2017-11-01 17:41:01 -07003389 }
3390 }
3391 if (what & layer_state_t::eSizeChanged) {
3392 if (layer->setSize(s.w, s.h)) {
3393 flags |= eTraversalNeeded;
3394 }
3395 }
3396 if (what & layer_state_t::eAlphaChanged) {
3397 if (layer->setAlpha(s.alpha))
3398 flags |= eTraversalNeeded;
3399 }
3400 if (what & layer_state_t::eColorChanged) {
3401 if (layer->setColor(s.color))
3402 flags |= eTraversalNeeded;
3403 }
3404 if (what & layer_state_t::eMatrixChanged) {
3405 if (layer->setMatrix(s.matrix))
3406 flags |= eTraversalNeeded;
3407 }
3408 if (what & layer_state_t::eTransparentRegionChanged) {
3409 if (layer->setTransparentRegionHint(s.transparentRegion))
3410 flags |= eTraversalNeeded;
3411 }
3412 if (what & layer_state_t::eFlagsChanged) {
3413 if (layer->setFlags(s.flags, s.mask))
3414 flags |= eTraversalNeeded;
3415 }
3416 if (what & layer_state_t::eCropChanged) {
3417 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3418 flags |= eTraversalNeeded;
3419 }
3420 if (what & layer_state_t::eFinalCropChanged) {
3421 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3422 flags |= eTraversalNeeded;
3423 }
3424 if (what & layer_state_t::eLayerStackChanged) {
3425 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3426 // We only allow setting layer stacks for top level layers,
3427 // everything else inherits layer stack from its parent.
3428 if (layer->hasParent()) {
3429 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3430 layer->getName().string());
3431 } else if (idx < 0) {
3432 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3433 "that also does not appear in the top level layer list. Something"
3434 " has gone wrong.", layer->getName().string());
3435 } else if (layer->setLayerStack(s.layerStack)) {
3436 mCurrentState.layersSortedByZ.removeAt(idx);
3437 mCurrentState.layersSortedByZ.add(layer);
3438 // we need traversal (state changed)
3439 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003440 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003441 }
3442 }
3443 if (what & layer_state_t::eDeferTransaction) {
3444 if (s.barrierHandle != nullptr) {
3445 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3446 } else if (s.barrierGbp != nullptr) {
3447 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3448 if (authenticateSurfaceTextureLocked(gbp)) {
3449 const auto& otherLayer =
3450 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3451 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3452 } else {
3453 ALOGE("Attempt to defer transaction to to an"
3454 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003455 }
3456 }
chaviw8b3871a2017-11-01 17:41:01 -07003457 // We don't trigger a traversal here because if no other state is
3458 // changed, we don't want this to cause any more work
3459 }
3460 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003461 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003462 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003463 if (!hadParent) {
3464 mCurrentState.layersSortedByZ.remove(layer);
3465 }
chaviw8b3871a2017-11-01 17:41:01 -07003466 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003467 }
chaviw8b3871a2017-11-01 17:41:01 -07003468 }
3469 if (what & layer_state_t::eReparentChildren) {
3470 if (layer->reparentChildren(s.reparentHandle)) {
3471 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003472 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003473 }
chaviw8b3871a2017-11-01 17:41:01 -07003474 if (what & layer_state_t::eDetachChildren) {
3475 layer->detachChildren();
3476 }
3477 if (what & layer_state_t::eOverrideScalingModeChanged) {
3478 layer->setOverrideScalingMode(s.overrideScalingMode);
3479 // We don't trigger a traversal here because if no other state is
3480 // changed, we don't want this to cause any more work
3481 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003482 return flags;
3483}
3484
chaviwca27f252018-02-06 16:46:39 -08003485void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3486 const layer_state_t& state = composerState.state;
3487 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3488
3489 sp<Layer> layer(client->getLayerUser(state.surface));
3490 if (layer == nullptr) {
3491 return;
3492 }
3493
3494 if (layer->isPendingRemoval()) {
3495 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3496 return;
3497 }
3498
3499 if (state.what & layer_state_t::eDestroySurface) {
3500 removeLayerLocked(mStateLock, layer);
3501 }
3502}
3503
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003504status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003505 const String8& name,
3506 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003507 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003508 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003509 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003510{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003511 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003512 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003513 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003514 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003515 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003516
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003517 status_t result = NO_ERROR;
3518
3519 sp<Layer> layer;
3520
Cody Northropbc755282017-03-31 12:00:08 -06003521 String8 uniqueName = getUniqueLayerName(name);
3522
Mathias Agopian3165cc22012-08-08 19:42:09 -07003523 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3524 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003525 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003526 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003527 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003528
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003529 break;
chaviw13fdc492017-06-27 12:40:18 -07003530 case ISurfaceComposerClient::eFXSurfaceColor:
3531 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003532 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003533 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003534 break;
3535 default:
3536 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003537 break;
3538 }
3539
Dan Stoza7d89d062015-04-30 13:29:25 -07003540 if (result != NO_ERROR) {
3541 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003542 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003543
Chia-I Wuab0c3192017-08-01 11:29:00 -07003544 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3545 // TODO b/64227542
3546 if (windowType == 441731) {
3547 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3548 layer->setPrimaryDisplayOnly();
3549 }
3550
Albert Chaulk479c60c2017-01-27 14:21:34 -05003551 layer->setInfo(windowType, ownerUid);
3552
Robert Carr1f0a16a2016-10-24 16:27:39 -07003553 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003554 if (result != NO_ERROR) {
3555 return result;
3556 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003557 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003558
3559 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003560 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003561}
3562
Cody Northropbc755282017-03-31 12:00:08 -06003563String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3564{
3565 bool matchFound = true;
3566 uint32_t dupeCounter = 0;
3567
3568 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3569 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3570
3571 // Loop over layers until we're sure there is no matching name
3572 while (matchFound) {
3573 matchFound = false;
3574 mDrawingState.traverseInZOrder([&](Layer* layer) {
3575 if (layer->getName() == uniqueName) {
3576 matchFound = true;
3577 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3578 }
3579 });
3580 }
3581
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003582 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3583 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003584
3585 return uniqueName;
3586}
3587
David Sodman0c69cad2017-08-21 12:12:51 -07003588status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003589 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3590 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003591{
3592 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003593 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003594 case PIXEL_FORMAT_TRANSPARENT:
3595 case PIXEL_FORMAT_TRANSLUCENT:
3596 format = PIXEL_FORMAT_RGBA_8888;
3597 break;
3598 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003599 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003600 break;
3601 }
3602
David Sodman0c69cad2017-08-21 12:12:51 -07003603 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3604 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003605 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003606 *handle = layer->getHandle();
3607 *gbp = layer->getProducer();
3608 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003609 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003610
David Sodman0c69cad2017-08-21 12:12:51 -07003611 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003612 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003613}
3614
chaviw13fdc492017-06-27 12:40:18 -07003615status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003616 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003617 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003618{
chaviw13fdc492017-06-27 12:40:18 -07003619 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003620 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003621 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003622}
3623
Mathias Agopianac9fa422013-02-11 16:40:36 -08003624status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003625{
Robert Carr9524cb32017-02-13 11:32:32 -08003626 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003627 status_t err = NO_ERROR;
3628 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003629 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003630 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003631 err = removeLayer(l);
3632 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3633 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003634 }
3635 return err;
3636}
3637
Mathias Agopian13127d82013-03-05 17:47:11 -08003638status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003639{
Mathias Agopian67106042013-03-14 19:18:13 -07003640 // called by ~LayerCleaner() when all references to the IBinder (handle)
3641 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003642 sp<Layer> l = layer.promote();
3643 if (l == nullptr) {
3644 // The layer has already been removed, carry on
3645 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003646 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003647 // If we have a parent, then we can continue to live as long as it does.
3648 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003649}
3650
Mathias Agopianb60314a2012-04-10 22:09:54 -07003651// ---------------------------------------------------------------------------
3652
Andy McFadden13a082e2012-08-24 10:16:42 -07003653void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003654 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003655 Vector<ComposerState> state;
3656 Vector<DisplayState> displays;
3657 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003658 d.what = DisplayState::eDisplayProjectionChanged |
3659 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003660 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003661 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003662 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003663 d.frame.makeInvalid();
3664 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003665 d.width = 0;
3666 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003667 displays.add(d);
3668 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003669 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3670 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003671
David Sodman105b7dc2017-11-04 20:28:14 -07003672 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003673 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003674 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003675
Brian Andersond0010582017-03-07 13:20:31 -08003676 // Use phase of 0 since phase is not known.
3677 // Use latency of 0, which will snap to the ideal latency.
3678 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003679}
3680
3681void SurfaceFlinger::initializeDisplays() {
3682 class MessageScreenInitialized : public MessageBase {
3683 SurfaceFlinger* flinger;
3684 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003685 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003686 virtual bool handler() {
3687 flinger->onInitializeDisplays();
3688 return true;
3689 }
3690 };
3691 sp<MessageBase> msg = new MessageScreenInitialized(this);
3692 postMessageAsync(msg); // we may be called from main thread, use async message
3693}
3694
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003695void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003696 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003697 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3698 this);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003699 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003700
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003701 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003702 return;
3703 }
3704
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003705 hw->setPowerMode(mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -07003706 if (hw->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003707 ALOGW("Trying to set power mode for virtual display");
3708 return;
3709 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003710
Lloyd Pique4dccc412018-01-22 17:21:36 -08003711 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003712 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003713 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3714 if (idx < 0) {
3715 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3716 return;
3717 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003718 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003719 }
3720
Dominik Laskowski281644e2018-04-19 15:47:35 -07003721 int32_t type = hw->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003722 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003723 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003724 getHwComposer().setPowerMode(type, mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -07003725 if (hw->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003726 // FIXME: eventthread only knows about the main display right now
3727 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003728 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003729 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003730
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003731 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003732 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003733 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003734
3735 struct sched_param param = {0};
3736 param.sched_priority = 1;
3737 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3738 ALOGW("Couldn't set SCHED_FIFO on display on");
3739 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003740 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003741 // Turn off the display
3742 struct sched_param param = {0};
3743 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3744 ALOGW("Couldn't set SCHED_OTHER on display off");
3745 }
3746
Dominik Laskowski281644e2018-04-19 15:47:35 -07003747 if (hw->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003748 disableHardwareVsync(true); // also cancels any in-progress resync
3749
Mathias Agopiancde87a32012-09-13 14:09:01 -07003750 // FIXME: eventthread only knows about the main display right now
3751 mEventThread->onScreenReleased();
3752 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003753
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003754 getHwComposer().setPowerMode(type, mode);
3755 mVisibleRegionsDirty = true;
3756 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003757 } else if (mode == HWC_POWER_MODE_DOZE ||
3758 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003759 // Update display while dozing
3760 getHwComposer().setPowerMode(type, mode);
Dominik Laskowski281644e2018-04-19 15:47:35 -07003761 if (hw->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003762 // FIXME: eventthread only knows about the main display right now
3763 mEventThread->onScreenAcquired();
3764 resyncToHardwareVsync(true);
3765 }
3766 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3767 // Leave display going to doze
Dominik Laskowski281644e2018-04-19 15:47:35 -07003768 if (hw->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003769 disableHardwareVsync(true); // also cancels any in-progress resync
3770 // FIXME: eventthread only knows about the main display right now
3771 mEventThread->onScreenReleased();
3772 }
3773 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003774 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003775 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003776 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003777 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003778 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003779}
3780
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003781void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3782 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003783 SurfaceFlinger& mFlinger;
3784 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003785 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003786 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003787 MessageSetPowerMode(SurfaceFlinger& flinger,
3788 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3789 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003790 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003791 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003792 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003793 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003794 mMode, mDisplay.get());
Dominik Laskowski281644e2018-04-19 15:47:35 -07003795 } else if (hw->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003796 ALOGW("Attempt to set power mode = %d for virtual display",
3797 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003798 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003799 mFlinger.setPowerModeInternal(
3800 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003801 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003802 return true;
3803 }
3804 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003805 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003806 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003807}
3808
3809// ---------------------------------------------------------------------------
3810
Lloyd Pique755e3192018-01-31 16:46:15 -08003811status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3812 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003813 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003814
Mathias Agopianbd115332013-04-18 16:41:04 -07003815 IPCThreadState* ipc = IPCThreadState::self();
3816 const int pid = ipc->getCallingPid();
3817 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003818
Mathias Agopianbd115332013-04-18 16:41:04 -07003819 if ((uid != AID_SHELL) &&
3820 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003821 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003822 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003823 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003824 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003825 // (this would indicate SF is stuck, but we want to be able to
3826 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003827 status_t err = mStateLock.timedLock(s2ns(1));
3828 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003829 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003830 result.appendFormat(
3831 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3832 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003833 }
3834
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003835 bool dumpAll = true;
3836 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003837 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003838
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003839 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003840 if ((index < numArgs) &&
3841 (args[index] == String16("--list"))) {
3842 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003843 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003844 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003845 }
3846
3847 if ((index < numArgs) &&
3848 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003849 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003850 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003851 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003852 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003853
3854 if ((index < numArgs) &&
3855 (args[index] == String16("--latency-clear"))) {
3856 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003857 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003858 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003859 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003860
3861 if ((index < numArgs) &&
3862 (args[index] == String16("--dispsync"))) {
3863 index++;
3864 mPrimaryDispSync.dump(result);
3865 dumpAll = false;
3866 }
Dan Stozab90cf072015-03-05 11:05:59 -08003867
3868 if ((index < numArgs) &&
3869 (args[index] == String16("--static-screen"))) {
3870 index++;
3871 dumpStaticScreenStats(result);
3872 dumpAll = false;
3873 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003874
3875 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003876 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003877 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003878 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003879 dumpAll = false;
3880 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003881
3882 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3883 index++;
3884 dumpWideColorInfo(result);
3885 dumpAll = false;
3886 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003887
3888 if ((index < numArgs) &&
3889 (args[index] == String16("--enable-layer-stats"))) {
3890 index++;
3891 mLayerStats.enable();
3892 dumpAll = false;
3893 }
3894
3895 if ((index < numArgs) &&
3896 (args[index] == String16("--disable-layer-stats"))) {
3897 index++;
3898 mLayerStats.disable();
3899 dumpAll = false;
3900 }
3901
3902 if ((index < numArgs) &&
3903 (args[index] == String16("--clear-layer-stats"))) {
3904 index++;
3905 mLayerStats.clear();
3906 dumpAll = false;
3907 }
3908
3909 if ((index < numArgs) &&
3910 (args[index] == String16("--dump-layer-stats"))) {
3911 index++;
3912 mLayerStats.dump(result);
3913 dumpAll = false;
3914 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003915
3916 if ((index < numArgs) &&
3917 (args[index] == String16("--display-identification"))) {
3918 index++;
3919 dumpDisplayIdentificationData(result);
3920 dumpAll = false;
3921 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003922
3923 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3924 index++;
3925 mTimeStats.parseArgs(asProto, args, index, result);
3926 dumpAll = false;
3927 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003928 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003929
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003930 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003931 if (asProto) {
3932 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3933 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3934 } else {
3935 dumpAllLocked(args, index, result);
3936 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003937 }
3938
Mathias Agopian9795c422009-08-26 16:36:26 -07003939 if (locked) {
3940 mStateLock.unlock();
3941 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003942 }
3943 write(fd, result.string(), result.size());
3944 return NO_ERROR;
3945}
3946
Dan Stozac7014012014-02-14 15:03:43 -08003947void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3948 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003949{
Robert Carr2047fae2016-11-28 14:09:09 -08003950 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003951 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003952 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003953}
3954
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003955void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003956 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003957{
3958 String8 name;
3959 if (index < args.size()) {
3960 name = String8(args[index]);
3961 index++;
3962 }
3963
David Sodman105b7dc2017-11-04 20:28:14 -07003964 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003965 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003966 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003967
3968 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003969 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003970 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003971 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003972 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003973 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003974 }
Robert Carr2047fae2016-11-28 14:09:09 -08003975 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003976 }
3977}
3978
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003979void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003980 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003981{
3982 String8 name;
3983 if (index < args.size()) {
3984 name = String8(args[index]);
3985 index++;
3986 }
3987
Robert Carr2047fae2016-11-28 14:09:09 -08003988 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003989 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003990 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003991 }
Robert Carr2047fae2016-11-28 14:09:09 -08003992 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003993
Svetoslavd85084b2014-03-20 10:28:31 -07003994 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003995}
3996
Jamie Gennis6547ff42013-07-16 20:12:42 -07003997// This should only be called from the main thread. Otherwise it would need
3998// the lock and should use mCurrentState rather than mDrawingState.
3999void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004000 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004001 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004002 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004003
4004 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4005}
4006
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004007void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004008{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004009 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004010
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004011 if (isLayerTripleBufferingDisabled())
4012 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004013
4014 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004015 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004016 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004017 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004018 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4019 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004020 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004021}
4022
Dan Stozab90cf072015-03-05 11:05:59 -08004023void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4024{
4025 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004026 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4027 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004028 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004029 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004030 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4031 b + 1, bucketTimeSec, percent);
4032 }
David Sodman4a36e932017-11-07 14:29:47 -08004033 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004034 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004035 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004036 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004037 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004038}
4039
Dan Stozae77c7662016-05-13 11:37:28 -07004040void SurfaceFlinger::recordBufferingStats(const char* layerName,
4041 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004042 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4043 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004044 for (const auto& segment : history) {
4045 if (!segment.usedThirdBuffer) {
4046 stats.twoBufferTime += segment.totalTime;
4047 }
4048 if (segment.occupancyAverage < 1.0f) {
4049 stats.doubleBufferedTime += segment.totalTime;
4050 } else if (segment.occupancyAverage < 2.0f) {
4051 stats.tripleBufferedTime += segment.totalTime;
4052 }
4053 ++stats.numSegments;
4054 stats.totalTime += segment.totalTime;
4055 }
4056}
4057
Brian Andersond6927fb2016-07-23 23:37:30 -07004058void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4059 result.appendFormat("Layer frame timestamps:\n");
4060
4061 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4062 const size_t count = currentLayers.size();
4063 for (size_t i=0 ; i<count ; i++) {
4064 currentLayers[i]->dumpFrameEvents(result);
4065 }
4066}
4067
Dan Stozae77c7662016-05-13 11:37:28 -07004068void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4069 result.append("Buffering stats:\n");
4070 result.append(" [Layer name] <Active time> <Two buffer> "
4071 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004072 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004073 typedef std::tuple<std::string, float, float, float> BufferTuple;
4074 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004075 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004076 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004077 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004078 if (stats.numSegments == 0) {
4079 continue;
4080 }
4081 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4082 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4083 stats.totalTime;
4084 float doubleBufferRatio = static_cast<float>(
4085 stats.doubleBufferedTime) / stats.totalTime;
4086 float tripleBufferRatio = static_cast<float>(
4087 stats.tripleBufferedTime) / stats.totalTime;
4088 sorted.insert({activeTime, {name, twoBufferRatio,
4089 doubleBufferRatio, tripleBufferRatio}});
4090 }
4091 for (const auto& sortedPair : sorted) {
4092 float activeTime = sortedPair.first;
4093 const BufferTuple& values = sortedPair.second;
4094 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4095 std::get<0>(values).c_str(), activeTime,
4096 std::get<1>(values), std::get<2>(values),
4097 std::get<3>(values));
4098 }
4099 result.append("\n");
4100}
4101
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004102void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
4103 for (size_t d = 0; d < mDisplays.size(); d++) {
4104 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4105 const int32_t hwcId = displayDevice->getHwcDisplayId();
4106 const auto displayId = getHwComposer().getHwcDisplayId(hwcId);
4107 if (!displayId) {
4108 continue;
4109 }
4110
4111 result.appendFormat("Display %d: ", hwcId);
4112 uint8_t port;
4113 DisplayIdentificationData data;
4114 if (!getHwComposer().getDisplayIdentificationData(*displayId, &port, &data)) {
4115 result.append("no identification data\n");
4116 continue;
4117 }
4118
4119 if (!isEdid(data)) {
4120 result.append("unknown identification data: ");
4121 for (uint8_t byte : data) {
4122 result.appendFormat("%x ", byte);
4123 }
4124 result.append("\n");
4125 continue;
4126 }
4127
4128 const auto edid = parseEdid(data);
4129 if (!edid) {
4130 result.append("invalid EDID: ");
4131 for (uint8_t byte : data) {
4132 result.appendFormat("%x ", byte);
4133 }
4134 result.append("\n");
4135 continue;
4136 }
4137
4138 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4139 result.append(edid->displayName.data(), edid->displayName.length());
4140 result.append("\"\n");
4141 }
4142 result.append("\n");
4143}
4144
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004145void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4146 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004147 result.appendFormat("DisplayColorSetting: %s\n",
4148 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004149
4150 // TODO: print out if wide-color mode is active or not
4151
4152 for (size_t d = 0; d < mDisplays.size(); d++) {
4153 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4154 int32_t hwcId = displayDevice->getHwcDisplayId();
4155 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4156 continue;
4157 }
4158
4159 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004160 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004161 for (auto&& mode : modes) {
4162 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4163 }
4164
Peiyong Lina52f0292018-03-14 17:26:31 -07004165 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004166 result.appendFormat(" Current color mode: %s (%d)\n",
4167 decodeColorMode(currentMode).c_str(), currentMode);
4168 }
4169 result.append("\n");
4170}
4171
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004172LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004173 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004174 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4175 const State& state = useDrawing ? mDrawingState : mCurrentState;
4176 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004177 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004178 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004179 });
4180
4181 return layersProto;
4182}
4183
Dominik Laskowski63165dc2018-05-25 18:36:52 -07004184LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004185 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004186
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004187 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowski63165dc2018-05-25 18:36:52 -07004188 resolution->set_w(displayDevice.getWidth());
4189 resolution->set_h(displayDevice.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004190
Dominik Laskowski63165dc2018-05-25 18:36:52 -07004191 layersProto.set_color_mode(decodeColorMode(displayDevice.getActiveColorMode()));
4192 layersProto.set_color_transform(decodeColorTransform(displayDevice.getColorTransform()));
4193 layersProto.set_global_transform(static_cast<int32_t>(displayDevice.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004194
Dominik Laskowski63165dc2018-05-25 18:36:52 -07004195 const int32_t hwcId = displayDevice.getHwcDisplayId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004196 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004197 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004198 LayerProto* layerProto = layersProto.add_layers();
4199 layer->writeToProto(layerProto, hwcId);
4200 }
4201 });
4202
4203 return layersProto;
4204}
4205
Mathias Agopian74d211a2013-04-22 16:55:35 +02004206void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4207 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004208{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004209 bool colorize = false;
4210 if (index < args.size()
4211 && (args[index] == String16("--color"))) {
4212 colorize = true;
4213 index++;
4214 }
4215
4216 Colorizer colorizer(colorize);
4217
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004218 // figure out if we're stuck somewhere
4219 const nsecs_t now = systemTime();
4220 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4221 const nsecs_t inTransaction(mDebugInTransaction);
4222 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4223 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4224
4225 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004226 * Dump library configuration.
4227 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004228
4229 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004230 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004231 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004232 appendSfConfigString(result);
4233 appendUiConfigString(result);
4234 appendGuiConfigString(result);
4235 result.append("\n");
4236
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004237 result.append("\nDisplay identification data:\n");
4238 dumpDisplayIdentificationData(result);
4239
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004240 result.append("\nWide-Color information:\n");
4241 dumpWideColorInfo(result);
4242
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004243 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004244 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004245 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004246 result.append(SyncFeatures::getInstance().toString());
4247 result.append("\n");
4248
David Sodman105b7dc2017-11-04 20:28:14 -07004249 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004250
Andy McFadden41d67d72014-04-25 16:58:34 -07004251 colorizer.bold(result);
4252 result.append("DispSync configuration: ");
4253 colorizer.reset(result);
Dan Stoza84d619e2018-03-28 17:07:36 -07004254 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, early sf phase %" PRId64
4255 " ns, present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4256 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, mVsyncModulator.getEarlyPhaseOffset(),
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004257 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004258 result.append("\n");
4259
Dan Stozab90cf072015-03-05 11:05:59 -08004260 // Dump static screen stats
4261 result.append("\n");
4262 dumpStaticScreenStats(result);
4263 result.append("\n");
4264
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004265 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4266
Dan Stozae77c7662016-05-13 11:37:28 -07004267 dumpBufferingStats(result);
4268
Andy McFadden4803b742012-09-24 19:07:20 -07004269 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004270 * Dump the visible layer list
4271 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004272 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004273 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004274 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4275 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004276 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004277
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004278 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004279 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004280 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004281 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004282
4283 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004284 * Dump Display state
4285 */
4286
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004287 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004288 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004289 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004290 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4291 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004292 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004293 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004294 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004295
4296 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004297 * Dump SurfaceFlinger global state
4298 */
4299
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004300 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004301 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004302 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004303
Mathias Agopian888c8222012-08-04 21:10:38 -07004304 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004305 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004306
David Sodmanbc815282017-11-05 18:57:52 -08004307 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004308
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004309 if (hw) {
4310 hw->undefinedRegion.dump(result, "undefinedRegion");
4311 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4312 hw->getOrientation(), hw->isDisplayOn());
4313 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004314 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004315 " last eglSwapBuffers() time: %f us\n"
4316 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004317 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004318 " refresh-rate : %f fps\n"
4319 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004320 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004321 " gpu_to_cpu_unsupported : %d\n"
4322 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004323 mLastSwapBufferTime/1000.0,
4324 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004325 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004326 1e9 / activeConfig->getVsyncPeriod(),
4327 activeConfig->getDpiX(),
4328 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004329 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004330
Mathias Agopian74d211a2013-04-22 16:55:35 +02004331 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004332 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004333
Mathias Agopian74d211a2013-04-22 16:55:35 +02004334 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004335 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004336
4337 /*
4338 * VSYNC state
4339 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004340 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004341 result.append("\n");
4342
4343 /*
4344 * HWC layer minidump
4345 */
4346 for (size_t d = 0; d < mDisplays.size(); d++) {
4347 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4348 int32_t hwcId = displayDevice->getHwcDisplayId();
4349 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4350 continue;
4351 }
4352
4353 result.appendFormat("Display %d HWC layers:\n", hwcId);
4354 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004355 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004356 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004357 });
Dan Stozae22aec72016-08-01 13:20:59 -07004358 result.append("\n");
4359 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004360
4361 /*
4362 * Dump HWComposer state
4363 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004364 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004365 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004366 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004367 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004368 result.appendFormat(" h/w composer %s\n",
4369 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004370 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004371
4372 /*
4373 * Dump gralloc state
4374 */
4375 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4376 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004377
4378 /*
4379 * Dump VrFlinger state if in use.
4380 */
4381 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4382 result.append("VrFlinger state:\n");
4383 result.append(mVrFlinger->Dump().c_str());
4384 result.append("\n");
4385 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004386}
4387
Mathias Agopian13127d82013-03-05 17:47:11 -08004388const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004389SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004390 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004391 wp<IBinder> dpy;
4392 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4393 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4394 dpy = mDisplays.keyAt(i);
4395 break;
4396 }
4397 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004398 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004399 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4400 // Just use the primary display so we have something to return
4401 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4402 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004403 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004404}
4405
Keun young Park63f165f2012-08-31 10:53:36 -07004406bool SurfaceFlinger::startDdmConnection()
4407{
4408 void* libddmconnection_dso =
4409 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4410 if (!libddmconnection_dso) {
4411 return false;
4412 }
4413 void (*DdmConnection_start)(const char* name);
4414 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004415 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004416 if (!DdmConnection_start) {
4417 dlclose(libddmconnection_dso);
4418 return false;
4419 }
4420 (*DdmConnection_start)(getServiceName());
4421 return true;
4422}
4423
Chia-I Wu28f320b2018-05-03 11:02:56 -07004424void SurfaceFlinger::updateColorMatrixLocked() {
4425 mat4 colorMatrix;
4426 if (mGlobalSaturationFactor != 1.0f) {
4427 // Rec.709 luma coefficients
4428 float3 luminance{0.213f, 0.715f, 0.072f};
4429 luminance *= 1.0f - mGlobalSaturationFactor;
4430 mat4 saturationMatrix = mat4(
4431 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4432 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4433 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4434 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4435 );
4436 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4437 } else {
4438 colorMatrix = mClientColorMatrix * mDaltonizer();
4439 }
4440
4441 if (mCurrentState.colorMatrix != colorMatrix) {
4442 mCurrentState.colorMatrix = colorMatrix;
4443 mCurrentState.colorMatrixChanged = true;
4444 setTransactionFlags(eTransactionNeeded);
4445 }
4446}
4447
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004448status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004449 switch (code) {
4450 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004451 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004452 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004453 case CLEAR_ANIMATION_FRAME_STATS:
4454 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004455 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004456 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004457 case ENABLE_VSYNC_INJECTIONS:
4458 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004459 {
4460 // codes that require permission check
4461 IPCThreadState* ipc = IPCThreadState::self();
4462 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07004463 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07004464 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07004465 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004466 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07004467 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004468 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004469 break;
4470 }
Robert Carr1db73f62016-12-21 12:58:51 -08004471 /*
4472 * Calling setTransactionState is safe, because you need to have been
4473 * granted a reference to Client* and Handle* to do anything with it.
4474 *
4475 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4476 */
4477 case SET_TRANSACTION_STATE:
4478 case CREATE_SCOPED_CONNECTION:
4479 {
4480 return OK;
4481 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004482 case CAPTURE_SCREEN:
4483 {
4484 // codes that require permission check
4485 IPCThreadState* ipc = IPCThreadState::self();
4486 const int pid = ipc->getCallingPid();
4487 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004488 if ((uid != AID_GRAPHICS) &&
4489 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004490 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004491 return PERMISSION_DENIED;
4492 }
4493 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004494 }
chaviwa76b2712017-09-20 12:02:26 -07004495 case CAPTURE_LAYERS: {
4496 IPCThreadState* ipc = IPCThreadState::self();
4497 const int pid = ipc->getCallingPid();
4498 const int uid = ipc->getCallingUid();
4499 if ((uid != AID_GRAPHICS) &&
4500 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4501 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4502 return PERMISSION_DENIED;
4503 }
4504 break;
4505 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004506 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004507 return OK;
4508}
4509
4510status_t SurfaceFlinger::onTransact(
4511 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4512{
4513 status_t credentialCheck = CheckTransactCodeCredentials(code);
4514 if (credentialCheck != OK) {
4515 return credentialCheck;
4516 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004517
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004518 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4519 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004520 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004521 IPCThreadState* ipc = IPCThreadState::self();
4522 const int uid = ipc->getCallingUid();
4523 if (CC_UNLIKELY(uid != AID_SYSTEM
4524 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004525 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004526 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004527 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004528 return PERMISSION_DENIED;
4529 }
4530 int n;
4531 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004532 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004533 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004534 return NO_ERROR;
4535 case 1002: // SHOW_UPDATES
4536 n = data.readInt32();
4537 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004538 invalidateHwcGeometry();
4539 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004540 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004541 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004542 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004543 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004544 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004545 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004546 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004547 setTransactionFlags(
4548 eTransactionNeeded|
4549 eDisplayTransactionNeeded|
4550 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004551 return NO_ERROR;
4552 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004553 case 1006:{ // send empty update
4554 signalRefresh();
4555 return NO_ERROR;
4556 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004557 case 1008: // toggle use of hw composer
4558 n = data.readInt32();
4559 mDebugDisableHWC = n ? 1 : 0;
4560 invalidateHwcGeometry();
4561 repaintEverything();
4562 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004563 case 1009: // toggle use of transform hint
4564 n = data.readInt32();
4565 mDebugDisableTransformHint = n ? 1 : 0;
4566 invalidateHwcGeometry();
4567 repaintEverything();
4568 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004569 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004570 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004571 reply->writeInt32(0);
4572 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004573 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004574 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004575 return NO_ERROR;
4576 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004577 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004578 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004579 return NO_ERROR;
4580 }
4581 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004582 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004583 // daltonize
4584 n = data.readInt32();
4585 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004586 case 1:
4587 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4588 break;
4589 case 2:
4590 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4591 break;
4592 case 3:
4593 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4594 break;
4595 default:
4596 mDaltonizer.setType(ColorBlindnessType::None);
4597 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004598 }
4599 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004600 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004601 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004602 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004603 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004604
4605 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004606 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004607 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004608 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004609 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004610 // apply a color matrix
4611 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004612 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004613 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004614 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004615 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004616 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004617 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004618 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004619 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004620 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004621 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004622
4623 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4624 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004625 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004626 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4627 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4628 }
4629
Chia-I Wu28f320b2018-05-03 11:02:56 -07004630 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004631 return NO_ERROR;
4632 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004633 // This is an experimental interface
4634 // Needs to be shifted to proper binder interface when we productize
4635 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004636 n = data.readInt32();
4637 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004638 return NO_ERROR;
4639 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004640 case 1017: {
4641 n = data.readInt32();
4642 mForceFullDamage = static_cast<bool>(n);
4643 return NO_ERROR;
4644 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004645 case 1018: { // Modify Choreographer's phase offset
4646 n = data.readInt32();
4647 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4648 return NO_ERROR;
4649 }
4650 case 1019: { // Modify SurfaceFlinger's phase offset
4651 n = data.readInt32();
4652 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4653 return NO_ERROR;
4654 }
Irvel468051e2016-06-13 16:44:44 -07004655 case 1020: { // Layer updates interceptor
4656 n = data.readInt32();
4657 if (n) {
4658 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004659 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004660 }
4661 else{
4662 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004663 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004664 }
4665 return NO_ERROR;
4666 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004667 case 1021: { // Disable HWC virtual displays
4668 n = data.readInt32();
4669 mUseHwcVirtualDisplays = !n;
4670 return NO_ERROR;
4671 }
Romain Guy0147a172017-06-01 13:53:56 -07004672 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004673 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004674 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004675
Chia-I Wu28f320b2018-05-03 11:02:56 -07004676 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004677 return NO_ERROR;
4678 }
Romain Guy54f154a2017-10-24 21:40:32 +01004679 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004680 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004681 invalidateHwcGeometry();
4682 repaintEverything();
4683 return NO_ERROR;
4684 }
4685 case 1024: { // Is wide color gamut rendering/color management supported?
4686 reply->writeBool(hasWideColorDisplay);
4687 return NO_ERROR;
4688 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004689 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004690 n = data.readInt32();
4691 if (n) {
4692 ALOGV("LayerTracing enabled");
4693 mTracing.enable();
4694 doTracing("tracing.enable");
4695 reply->writeInt32(NO_ERROR);
4696 } else {
4697 ALOGV("LayerTracing disabled");
4698 status_t err = mTracing.disable();
4699 reply->writeInt32(err);
4700 }
4701 return NO_ERROR;
4702 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004703 case 1026: { // Get layer tracing status
4704 reply->writeBool(mTracing.isEnabled());
4705 return NO_ERROR;
4706 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004707 // Is a DisplayColorSetting supported?
4708 case 1027: {
Chia-I Wu0d711262018-05-21 15:19:35 -07004709 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
4710 if (!hw) {
4711 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004712 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004713
4714 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4715 switch (setting) {
4716 case DisplayColorSetting::MANAGED:
4717 reply->writeBool(hasWideColorDisplay);
4718 break;
4719 case DisplayColorSetting::UNMANAGED:
4720 reply->writeBool(true);
4721 break;
4722 case DisplayColorSetting::ENHANCED:
4723 reply->writeBool(hw->hasRenderIntent(RenderIntent::ENHANCE));
4724 break;
4725 default: // vendor display color setting
4726 reply->writeBool(hw->hasRenderIntent(static_cast<RenderIntent>(setting)));
4727 break;
4728 }
4729 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004730 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004731 }
4732 }
4733 return err;
4734}
4735
Steven Thomas6d8110b2017-08-31 18:24:21 -07004736void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004737 android_atomic_or(1, &mRepaintEverything);
4738 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004739}
4740
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004741// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4742class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004743public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004744 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4745 ~WindowDisconnector() {
4746 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004747 }
4748
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004749private:
4750 ANativeWindow* mWindow;
4751 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004752};
4753
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004754status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4755 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4756 int32_t minLayerZ, int32_t maxLayerZ,
4757 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004758 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004759 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004760
chaviwa76b2712017-09-20 12:02:26 -07004761 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4762
4763 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004764 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4765
chaviwa76b2712017-09-20 12:02:26 -07004766 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4767
4768 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4769 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004770 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004771}
4772
4773status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004774 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004775 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004776 ATRACE_CALL();
4777
4778 class LayerRenderArea : public RenderArea {
4779 public:
Robert Carr578038f2018-03-09 12:25:24 -08004780 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4781 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004782 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004783 mLayer(layer),
4784 mCrop(crop),
4785 mFlinger(flinger),
4786 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004787 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004788 Rect getBounds() const override {
4789 const Layer::State& layerState(mLayer->getDrawingState());
4790 return Rect(layerState.active.w, layerState.active.h);
4791 }
4792 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4793 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4794 bool isSecure() const override { return false; }
4795 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004796 Rect getSourceCrop() const override {
4797 if (mCrop.isEmpty()) {
4798 return getBounds();
4799 } else {
4800 return mCrop;
4801 }
4802 }
Robert Carr578038f2018-03-09 12:25:24 -08004803 class ReparentForDrawing {
4804 public:
4805 const sp<Layer>& oldParent;
4806 const sp<Layer>& newParent;
4807
4808 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4809 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004810 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004811 }
Robert Carr15eae092018-03-23 13:43:53 -07004812 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004813 };
4814
4815 void render(std::function<void()> drawLayers) override {
4816 if (!mChildrenOnly) {
4817 mTransform = mLayer->getTransform().inverse();
4818 drawLayers();
4819 } else {
4820 Rect bounds = getBounds();
4821 screenshotParentLayer =
4822 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4823 bounds.getWidth(), bounds.getHeight(), 0);
4824
4825 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4826 drawLayers();
4827 }
4828 }
chaviwa76b2712017-09-20 12:02:26 -07004829
chaviwa76b2712017-09-20 12:02:26 -07004830 private:
chaviw7206d492017-11-10 16:16:12 -08004831 const sp<Layer> mLayer;
4832 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004833
4834 // In the "childrenOnly" case we reparent the children to a screenshot
4835 // layer which has no properties set and which does not draw.
4836 sp<ContainerLayer> screenshotParentLayer;
4837 Transform mTransform;
4838
4839 SurfaceFlinger* mFlinger;
4840 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004841 };
4842
4843 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4844 auto parent = layerHandle->owner.promote();
4845
chaviw7206d492017-11-10 16:16:12 -08004846 if (parent == nullptr || parent->isPendingRemoval()) {
4847 ALOGE("captureLayers called with a removed parent");
4848 return NAME_NOT_FOUND;
4849 }
4850
Robert Carr578038f2018-03-09 12:25:24 -08004851 const int uid = IPCThreadState::self()->getCallingUid();
4852 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4853 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4854 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4855 return PERMISSION_DENIED;
4856 }
4857
chaviw7206d492017-11-10 16:16:12 -08004858 Rect crop(sourceCrop);
4859 if (sourceCrop.width() <= 0) {
4860 crop.left = 0;
4861 crop.right = parent->getCurrentState().active.w;
4862 }
4863
4864 if (sourceCrop.height() <= 0) {
4865 crop.top = 0;
4866 crop.bottom = parent->getCurrentState().active.h;
4867 }
4868
4869 int32_t reqWidth = crop.width() * frameScale;
4870 int32_t reqHeight = crop.height() * frameScale;
4871
Robert Carr578038f2018-03-09 12:25:24 -08004872 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004873
Robert Carr578038f2018-03-09 12:25:24 -08004874 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004875 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4876 if (!layer->isVisible()) {
4877 return;
Robert Carr578038f2018-03-09 12:25:24 -08004878 } else if (childrenOnly && layer == parent.get()) {
4879 return;
chaviwa76b2712017-09-20 12:02:26 -07004880 }
4881 visitor(layer);
4882 });
4883 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004884 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004885}
4886
4887status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4888 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004889 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004890 bool useIdentityTransform) {
4891 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004892
Iris Chang7501ed62018-04-30 14:45:42 +08004893 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004894
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004895 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4896 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4897 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4898 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004899
4900 // This mutex protects syncFd and captureResult for communication of the return values from the
4901 // main thread back to this Binder thread
4902 std::mutex captureMutex;
4903 std::condition_variable captureCondition;
4904 std::unique_lock<std::mutex> captureLock(captureMutex);
4905 int syncFd = -1;
4906 std::optional<status_t> captureResult;
4907
Robert Carr03480e22018-01-04 16:02:06 -08004908 const int uid = IPCThreadState::self()->getCallingUid();
4909 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4910
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004911 sp<LambdaMessage> message = new LambdaMessage([&]() {
4912 // If there is a refresh pending, bug out early and tell the binder thread to try again
4913 // after the refresh.
4914 if (mRefreshPending) {
4915 ATRACE_NAME("Skipping screenshot for now");
4916 std::unique_lock<std::mutex> captureLock(captureMutex);
4917 captureResult = std::make_optional<status_t>(EAGAIN);
4918 captureCondition.notify_one();
4919 return;
4920 }
4921
4922 status_t result = NO_ERROR;
4923 int fd = -1;
4924 {
4925 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004926 renderArea.render([&]() {
4927 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4928 useIdentityTransform, forSystem, &fd);
4929 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004930 }
4931
4932 {
4933 std::unique_lock<std::mutex> captureLock(captureMutex);
4934 syncFd = fd;
4935 captureResult = std::make_optional<status_t>(result);
4936 captureCondition.notify_one();
4937 }
4938 });
4939
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004940 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004941 if (result == NO_ERROR) {
4942 captureCondition.wait(captureLock, [&]() { return captureResult; });
4943 while (*captureResult == EAGAIN) {
4944 captureResult.reset();
4945 result = postMessageAsync(message);
4946 if (result != NO_ERROR) {
4947 return result;
4948 }
4949 captureCondition.wait(captureLock, [&]() { return captureResult; });
4950 }
4951 result = *captureResult;
4952 }
4953
4954 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004955 sync_wait(syncFd, -1);
4956 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004957 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004958
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004959 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004960}
4961
chaviwa76b2712017-09-20 12:02:26 -07004962void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4963 TraverseLayersFunction traverseLayers, bool yswap,
4964 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004965 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004966
Lloyd Pique144e1162017-12-20 16:44:52 -08004967 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004968
4969 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004970 const auto raWidth = renderArea.getWidth();
4971 const auto raHeight = renderArea.getHeight();
4972
4973 const auto reqWidth = renderArea.getReqWidth();
4974 const auto reqHeight = renderArea.getReqHeight();
4975 Rect sourceCrop = renderArea.getSourceCrop();
4976
Iris Chang7501ed62018-04-30 14:45:42 +08004977 bool filtering = false;
4978 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
4979 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
4980 static_cast<int32_t>(reqHeight) != raWidth;
4981 } else {
4982 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4983 static_cast<int32_t>(reqHeight) != raHeight;
4984 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004985
Dan Stozac1879002014-05-22 15:59:05 -07004986 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07004987 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07004988 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07004989 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08004990 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
4991 Transform tr;
4992 uint32_t flags = 0x00;
4993 switch (mPrimaryDisplayOrientation) {
4994 case DisplayState::eOrientation90:
4995 flags = Transform::ROT_90;
4996 break;
4997 case DisplayState::eOrientation180:
4998 flags = Transform::ROT_180;
4999 break;
5000 case DisplayState::eOrientation270:
5001 flags = Transform::ROT_270;
5002 break;
5003 }
5004 tr.set(flags, raWidth, raHeight);
5005 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005006 }
5007
5008 // ensure that sourceCrop is inside screen
5009 if (sourceCrop.left < 0) {
5010 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5011 }
chaviwa76b2712017-09-20 12:02:26 -07005012 if (sourceCrop.right > raWidth) {
5013 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005014 }
5015 if (sourceCrop.top < 0) {
5016 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5017 }
chaviwa76b2712017-09-20 12:02:26 -07005018 if (sourceCrop.bottom > raHeight) {
5019 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005020 }
5021
Chia-I Wu36574d92018-05-16 10:54:36 -07005022 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5023 engine.setOutputDataSpace(Dataspace::SRGB);
5024 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005025
Mathias Agopian180f10d2013-04-10 22:55:41 -07005026 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005027 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005028
Iris Chang7501ed62018-04-30 14:45:42 +08005029 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5030 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5031 // convert hw orientation into flag presentation
5032 // here inverse transform needed
5033 uint8_t hw_rot_90 = 0x00;
5034 uint8_t hw_flip_hv = 0x00;
5035 switch (mPrimaryDisplayOrientation) {
5036 case DisplayState::eOrientation90:
5037 hw_rot_90 = Transform::ROT_90;
5038 hw_flip_hv = Transform::ROT_180;
5039 break;
5040 case DisplayState::eOrientation180:
5041 hw_flip_hv = Transform::ROT_180;
5042 break;
5043 case DisplayState::eOrientation270:
5044 hw_rot_90 = Transform::ROT_90;
5045 break;
5046 }
5047
5048 // transform flags operation
5049 // 1) flip H V if both have ROT_90 flag
5050 // 2) XOR these flags
5051 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5052 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5053 if (rotation_rot_90 & hw_rot_90) {
5054 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5055 }
5056 rotation = static_cast<Transform::orientation_flags>
5057 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5058 }
5059
Mathias Agopian180f10d2013-04-10 22:55:41 -07005060 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005061 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005062 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005063 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005064
chaviw50da5042018-04-09 13:49:37 -07005065 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005066 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005067 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005068
chaviwa76b2712017-09-20 12:02:26 -07005069 traverseLayers([&](Layer* layer) {
5070 if (filtering) layer->setFiltering(true);
bohu21566132018-03-27 14:36:34 -07005071 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005072 if (filtering) layer->setFiltering(false);
5073 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005074}
5075
chaviwa76b2712017-09-20 12:02:26 -07005076status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5077 TraverseLayersFunction traverseLayers,
5078 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005079 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005080 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005081 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005082 ATRACE_CALL();
5083
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005084 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005085
5086 traverseLayers([&](Layer* layer) {
5087 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5088 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005089
Robert Carr03480e22018-01-04 16:02:06 -08005090 // We allow the system server to take screenshots of secure layers for
5091 // use in situations like the Screen-rotation animation and place
5092 // the impetus on WindowManager to not persist them.
5093 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005094 ALOGW("FB is protected: PERMISSION_DENIED");
5095 return PERMISSION_DENIED;
5096 }
5097
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005098 // this binds the given EGLImage as a framebuffer for the
5099 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005100 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005101 if (bufferBond.getStatus() != NO_ERROR) {
5102 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005103 return INVALID_OPERATION;
5104 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005105
Dan Stozaabcda352017-06-01 14:37:39 -07005106 // this will in fact render into our dequeued buffer
5107 // via an FBO, which means we didn't have to create
5108 // an EGLSurface and therefore we're not
5109 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005110 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005111
Dan Stozaabcda352017-06-01 14:37:39 -07005112 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005113 getRenderEngine().finish();
5114 *outSyncFd = -1;
5115
chaviwa76b2712017-09-20 12:02:26 -07005116 const auto reqWidth = renderArea.getReqWidth();
5117 const auto reqHeight = renderArea.getReqHeight();
5118
Dan Stozaabcda352017-06-01 14:37:39 -07005119 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5120 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005121 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005122 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005123 } else {
5124 base::unique_fd syncFd = getRenderEngine().flush();
5125 if (syncFd < 0) {
5126 getRenderEngine().finish();
5127 }
5128 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005129 }
5130
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005131 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005132}
5133
Mathias Agopiand5556842013-09-19 17:08:37 -07005134void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005135 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005136 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005137 for (size_t y = 0; y < h; y++) {
5138 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5139 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005140 if (p[x] != 0xFF000000) return;
5141 }
5142 }
chaviwa76b2712017-09-20 12:02:26 -07005143 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005144
Robert Carr2047fae2016-11-28 14:09:09 -08005145 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005146 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005147 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005148 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5149 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5150 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5151 static_cast<float>(state.color.a));
5152 i++;
5153 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005154 }
5155}
5156
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005157// ---------------------------------------------------------------------------
5158
Dan Stoza412903f2017-04-27 13:42:17 -07005159void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5160 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005161}
5162
Dan Stoza412903f2017-04-27 13:42:17 -07005163void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5164 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005165}
5166
chaviwa76b2712017-09-20 12:02:26 -07005167void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5168 int32_t maxLayerZ,
5169 const LayerVector::Visitor& visitor) {
5170 // We loop through the first level of layers without traversing,
5171 // as we need to interpret min/max layer Z in the top level Z space.
5172 for (const auto& layer : mDrawingState.layersSortedByZ) {
5173 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5174 continue;
5175 }
5176 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005177 // relative layers are traversed in Layer::traverseInZOrder
5178 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005179 continue;
5180 }
5181 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005182 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5183 return;
5184 }
chaviwa76b2712017-09-20 12:02:26 -07005185 if (!layer->isVisible()) {
5186 return;
5187 }
5188 visitor(layer);
5189 });
5190 }
5191}
5192
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005193}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005194
Chia-I Wu30505fb2018-03-26 16:20:31 -07005195
Mathias Agopian3f844832013-08-07 21:24:32 -07005196#if defined(__gl_h_)
5197#error "don't include gl/gl.h in this file"
5198#endif
5199
5200#if defined(__gl2_h_)
5201#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005202#endif