blob: 2c7f8c4c1dac7d2ff89b435e6082e604a3516cad [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
Chia-I Wu6d844112018-06-27 07:17:41 +080040#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060041#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070043#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080048#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070050
51#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Robert Carr578038f2018-03-09 12:25:24 -080065#include "BufferLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020066#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080067#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080070#include "DdmConnection.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070071#include "DispSync.h"
Robert Carr578038f2018-03-09 12:25:24 -080072#include "DisplayDevice.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070073#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080074#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070076#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080077#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078#include "SurfaceFlinger.h"
Robert Carr578038f2018-03-09 12:25:24 -080079#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080
Steven Thomasb02664d2017-07-26 18:48:28 -070081#include "DisplayHardware/ComposerHal.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 Linfd997e02018-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 Pique09594832018-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 Pique2d3ee6d2018-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),
Chia-I Wuad8d8272018-06-26 10:18:18 +0800226 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800227 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700228 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700229 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700230 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700231 mDebugInSwapBuffers(0),
232 mLastSwapBufferTime(0),
233 mDebugInTransaction(0),
234 mLastTransactionTime(0),
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 Pique09594832018-01-22 17:48:03 -0800243 mCreateBufferQueue(&BufferQueue::createBufferQueue),
244 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800245
246SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800247 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800248
249 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
250 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
251
252 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
253 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
254
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800255 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
256 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700258 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
259 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
260
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700261 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
262 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
263
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800264 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
265 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
266
Steven Thomas050b2c82017-03-06 11:45:16 -0800267 // Vr flinger is only enabled on Daydream ready devices.
268 useVrFlinger = getBool< ISurfaceFlingerConfigs,
269 &ISurfaceFlingerConfigs::useVrFlinger>(false);
270
Fabien Sanglard1971b632017-03-10 14:50:03 -0800271 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
272 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
273
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600274 hasWideColorDisplay =
275 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
276
Iris Chang7501ed62018-04-30 14:45:42 +0800277 V1_1::DisplayOrientation primaryDisplayOrientation =
278 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
279 V1_1::DisplayOrientation::ORIENTATION_0);
280
281 switch (primaryDisplayOrientation) {
282 case V1_1::DisplayOrientation::ORIENTATION_90:
283 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
284 break;
285 case V1_1::DisplayOrientation::ORIENTATION_180:
286 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
287 break;
288 case V1_1::DisplayOrientation::ORIENTATION_270:
289 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
290 break;
291 default:
292 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
293 break;
294 }
295 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
296
David Sodman99974d22017-11-28 12:04:33 -0800297 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700298
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800299 // debugging stuff...
300 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700301
Mathias Agopianb4b17302013-03-20 18:36:41 -0700302 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700303 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700304
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800305 property_get("debug.sf.showupdates", value, "0");
306 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700307
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700308 property_get("debug.sf.ddms", value, "0");
309 mDebugDDMS = atoi(value);
310 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700311 if (!startDdmConnection()) {
312 // start failed, and DDMS debugging not enabled
313 mDebugDDMS = 0;
314 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700315 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700316 ALOGI_IF(mDebugRegion, "showupdates enabled");
317 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700318
319 property_get("debug.sf.disable_backpressure", value, "0");
320 mPropagateBackpressure = !atoi(value);
321 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700322
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800323 property_get("debug.sf.enable_hwc_vds", value, "0");
324 mUseHwcVirtualDisplays = atoi(value);
325 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800326
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800327 property_get("ro.sf.disable_triple_buffer", value, "1");
328 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800329 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700330
Yiwei Zhang243b3782018-05-15 17:40:04 -0700331 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700332 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
333 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
334
Jorim Jaggie203e042018-06-19 15:57:08 +0200335 property_get("debug.sf.early_phase_offset_ns", value, "-1");
336 const int earlySfOffsetNs = atoi(value);
337
338 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
339 const int earlyGlSfOffsetNs = atoi(value);
340
341 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
342 const int earlyAppOffsetNs = atoi(value);
343
344 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
345 const int earlyGlAppOffsetNs = atoi(value);
346
347 const VSyncModulator::Offsets earlyOffsets =
348 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
349 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
350 const VSyncModulator::Offsets earlyGlOffsets =
351 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
352 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
353 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
354 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza2713c302018-03-28 17:07:36 -0700355
Romain Guy11d63f42017-07-20 12:47:14 -0700356 // We should be reading 'persist.sys.sf.color_saturation' here
357 // but since /data may be encrypted, we need to wait until after vold
358 // comes online to attempt to read the property. The property is
359 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800360
361 if (useTrebleTestingOverride()) {
362 // Without the override SurfaceFlinger cannot connect to HIDL
363 // services that are not listed in the manifests. Considered
364 // deriving the setting from the set service name, but it
365 // would be brittle if the name that's not 'default' is used
366 // for production purposes later on.
367 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
368 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800369}
370
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800371void SurfaceFlinger::onFirstRef()
372{
Lloyd Pique9123ae52018-01-22 17:14:00 -0800373 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800374}
375
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800376SurfaceFlinger::~SurfaceFlinger()
377{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800378}
379
Dan Stozac7014012014-02-14 15:03:43 -0800380void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800381{
382 // the window manager died on us. prepare its eulogy.
383
Andy McFadden13a082e2012-08-24 10:16:42 -0700384 // restore initial conditions (default device unblank, etc)
385 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800386
387 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700388 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800389}
390
Robert Carr1db73f62016-12-21 12:58:51 -0800391static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700392 status_t err = client->initCheck();
393 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800394 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800395 }
Robert Carr1db73f62016-12-21 12:58:51 -0800396 return nullptr;
397}
398
399sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
400 return initClient(new Client(this));
401}
402
403sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
404 const sp<IGraphicBufferProducer>& gbp) {
405 if (authenticateSurfaceTexture(gbp) == false) {
406 return nullptr;
407 }
408 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
409 if (layer == nullptr) {
410 return nullptr;
411 }
412
413 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800414}
415
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700416sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
417 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700418{
419 class DisplayToken : public BBinder {
420 sp<SurfaceFlinger> flinger;
421 virtual ~DisplayToken() {
422 // no more references, this display must be terminated
423 Mutex::Autolock _l(flinger->mStateLock);
424 flinger->mCurrentState.displays.removeItem(this);
425 flinger->setTransactionFlags(eDisplayTransactionNeeded);
426 }
427 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700428 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700429 : flinger(flinger) {
430 }
431 };
432
433 sp<BBinder> token = new DisplayToken(this);
434
435 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700436 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700437 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700438 mCurrentState.displays.add(token, info);
Lloyd Pique4d234852018-01-22 17:21:36 -0800439 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700440 return token;
441}
442
Jesse Hall6c913be2013-08-08 12:15:49 -0700443void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
444 Mutex::Autolock _l(mStateLock);
445
446 ssize_t idx = mCurrentState.displays.indexOfKey(display);
447 if (idx < 0) {
448 ALOGW("destroyDisplay: invalid display token");
449 return;
450 }
451
452 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
453 if (!info.isVirtualDisplay()) {
454 ALOGE("destroyDisplay called for non-virtual display");
455 return;
456 }
Lloyd Pique4d234852018-01-22 17:21:36 -0800457 mInterceptor->saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700458 mCurrentState.displays.removeItemsAt(idx);
459 setTransactionFlags(eDisplayTransactionNeeded);
460}
461
Mathias Agopiane57f2922012-08-09 16:29:12 -0700462sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700463 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700464 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800465 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700466 }
Jesse Hall692c7232012-11-08 15:41:56 -0800467 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700468}
469
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800470void SurfaceFlinger::bootFinished()
471{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700472 if (mStartPropertySetThread->join() != NO_ERROR) {
473 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800474 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800475 const nsecs_t now = systemTime();
476 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000477 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700478
479 // wait patiently for the window manager death
480 const String16 name("window");
481 sp<IBinder> window(defaultServiceManager()->getService(name));
482 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700483 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700484 }
485
Steven Thomas050b2c82017-03-06 11:45:16 -0800486 if (mVrFlinger) {
487 mVrFlinger->OnBootFinished();
488 }
489
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700490 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700491 // formerly we would just kill the process, but we now ask it to exit so it
492 // can choose where to stop the animation.
493 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700494
495 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
496 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
497 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700498
Thierry Strudel2924d012017-08-14 15:19:37 -0700499 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700500 readPersistentProperties();
Chia-I Wuad8d8272018-06-26 10:18:18 +0800501 mBootStage = BootStage::FINISHED;
Romain Guy11d63f42017-07-20 12:47:14 -0700502 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700503 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800504}
505
Dan Stoza9fdb7e02018-06-21 12:10:12 -0700506uint32_t SurfaceFlinger::getNewTexture() {
507 {
508 std::lock_guard lock(mTexturePoolMutex);
509 if (!mTexturePool.empty()) {
510 uint32_t name = mTexturePool.back();
511 mTexturePool.pop_back();
512 ATRACE_INT("TexturePoolSize", mTexturePool.size());
513 return name;
514 }
515
516 // The pool was too small, so increase it for the future
517 ++mTexturePoolSize;
518 }
519
520 // The pool was empty, so we need to get a new texture name directly using a
521 // blocking call to the main thread
522 uint32_t name = 0;
523 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
524 return name;
525}
526
Mathias Agopian3f844832013-08-07 21:24:32 -0700527void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700528 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800529 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700530 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700531 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800532 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
533 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700534 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700535 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700536 return true;
537 }
538 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700539 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700540}
541
Lloyd Piquee83f9312018-02-01 12:53:17 -0800542class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700543public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700544 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000545 const char* name) :
546 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700547 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700548 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000549 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
550 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700551 mDispSync(dispSync),
552 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700553 mVsyncMutex(),
554 mPhaseOffset(phaseOffset),
555 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700556
Lloyd Piquee83f9312018-02-01 12:53:17 -0800557 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700558
Lloyd Piquee83f9312018-02-01 12:53:17 -0800559 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700560 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700561 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000562 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700563 static_cast<DispSync::Callback*>(this));
564 if (err != NO_ERROR) {
565 ALOGE("error registering vsync callback: %s (%d)",
566 strerror(-err), err);
567 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700568 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700569 } else {
570 status_t err = mDispSync->removeEventListener(
571 static_cast<DispSync::Callback*>(this));
572 if (err != NO_ERROR) {
573 ALOGE("error unregistering vsync callback: %s (%d)",
574 strerror(-err), err);
575 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700576 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700577 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700578 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700579 }
580
Lloyd Piquee83f9312018-02-01 12:53:17 -0800581 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700582 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700583 mCallback = callback;
584 }
585
Lloyd Piquee83f9312018-02-01 12:53:17 -0800586 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700587 Mutex::Autolock lock(mVsyncMutex);
588
589 // Normalize phaseOffset to [0, period)
590 auto period = mDispSync->getPeriod();
591 phaseOffset %= period;
592 if (phaseOffset < 0) {
593 // If we're here, then phaseOffset is in (-period, 0). After this
594 // operation, it will be in (0, period)
595 phaseOffset += period;
596 }
597 mPhaseOffset = phaseOffset;
598
599 // If we're not enabled, we don't need to mess with the listeners
600 if (!mEnabled) {
601 return;
602 }
603
Dan Stoza2713c302018-03-28 17:07:36 -0700604 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
605 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700606 if (err != NO_ERROR) {
Dan Stoza2713c302018-03-28 17:07:36 -0700607 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700608 strerror(-err), err);
609 }
610 }
611
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700612private:
613 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800614 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700615 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700616 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700617 callback = mCallback;
618
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700619 if (mTraceVsync) {
620 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700621 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700622 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700623 }
624
Peiyong Lin566a3b42018-01-09 18:22:43 -0800625 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700626 callback->onVSyncEvent(when);
627 }
628 }
629
Tim Murray4a4e4a22016-04-19 16:29:23 +0000630 const char* const mName;
631
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700632 int mValue;
633
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700634 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700635 const String8 mVsyncOnLabel;
636 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700637
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700638 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700639
640 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800641 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700642
643 Mutex mVsyncMutex; // Protects the following
644 nsecs_t mPhaseOffset;
645 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700646};
647
Lloyd Piquee83f9312018-02-01 12:53:17 -0800648class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700649public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800650 InjectVSyncSource() = default;
651 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700652
Lloyd Piquee83f9312018-02-01 12:53:17 -0800653 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700654 std::lock_guard<std::mutex> lock(mCallbackMutex);
655 mCallback = callback;
656 }
657
Lloyd Piquee83f9312018-02-01 12:53:17 -0800658 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700659 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700660 if (mCallback) {
661 mCallback->onVSyncEvent(when);
662 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700663 }
664
Lloyd Piquee83f9312018-02-01 12:53:17 -0800665 void setVSyncEnabled(bool) override {}
666 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700667
668private:
669 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800670 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700671};
672
Wei Wangf9b05ee2017-07-19 20:59:39 -0700673// Do not call property_set on main thread which will be blocked by init
674// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700675void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700676 ALOGI( "SurfaceFlinger's main thread ready to run. "
677 "Initializing graphics H/W...");
678
Thierry Strudel2924d012017-08-14 15:19:37 -0700679 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900680
Steven Thomasb02664d2017-07-26 18:48:28 -0700681 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800682
Steven Thomasb02664d2017-07-26 18:48:28 -0700683 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800684 mEventThreadSource =
685 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
686 true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800687 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
688 [this]() { resyncWithRateLimit(); },
689 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800690 "appEventThread");
691 mSfEventThreadSource =
692 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
693 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800694
Lloyd Pique24b0a482018-03-09 18:52:26 -0800695 mSFEventThread =
696 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
697 [this]() { resyncWithRateLimit(); },
698 [this](nsecs_t timestamp) {
699 mInterceptor->saveVSyncEvent(timestamp);
700 },
701 "sfEventThread");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800702 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggie203e042018-06-19 15:57:08 +0200703 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800704
Steven Thomasb02664d2017-07-26 18:48:28 -0700705 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800706 getBE().mRenderEngine =
707 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
708 hasWideColorDisplay
709 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
710 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800711 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700712
713 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
714 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800715 getBE().mHwc.reset(
716 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700717 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800718 // Process any initial hotplug and resulting display changes.
719 processDisplayHotplugEventsLocked();
720 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
721 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800722
Lloyd Piquefcd86612017-12-14 17:15:36 -0800723 // make the default display GLContext current so that we can create textures
724 // when creating Layers (which may happens before we render something)
725 getDefaultDisplayDeviceLocked()->makeCurrent();
726
Steven Thomas050b2c82017-03-06 11:45:16 -0800727 if (useVrFlinger) {
728 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700729 // This callback is called from the vr flinger dispatch thread. We
730 // need to call signalTransaction(), which requires holding
731 // mStateLock when we're not on the main thread. Acquiring
732 // mStateLock from the vr flinger dispatch thread might trigger a
733 // deadlock in surface flinger (see b/66916578), so post a message
734 // to be handled on the main thread instead.
735 sp<LambdaMessage> message = new LambdaMessage([=]() {
736 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
737 mVrFlingerRequestsDisplay = requestDisplay;
738 signalTransaction();
739 });
740 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800741 };
David Sodman105b7dc2017-11-04 20:28:14 -0700742 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
743 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800744 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800745 if (!mVrFlinger) {
746 ALOGE("Failed to start vrflinger");
747 }
748 }
749
Lloyd Pique0c3a8832018-01-22 17:31:47 -0800750 mEventControlThread = std::make_unique<impl::EventControlThread>(
751 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700752
Mathias Agopian92a979a2012-08-02 18:32:23 -0700753 // initialize our drawing state
754 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700755
Andy McFadden13a082e2012-08-24 10:16:42 -0700756 // set initial conditions (e.g. unblank default device)
757 initializeDisplays();
758
David Sodmanbc815282017-11-05 18:57:52 -0800759 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700760
Wei Wangf9b05ee2017-07-19 20:59:39 -0700761 // Inform native graphics APIs whether the present timestamp is supported:
762 if (getHwComposer().hasCapability(
763 HWC2::Capability::PresentFenceIsNotReliable)) {
764 mStartPropertySetThread = new StartPropertySetThread(false);
765 } else {
766 mStartPropertySetThread = new StartPropertySetThread(true);
767 }
768
769 if (mStartPropertySetThread->Start() != NO_ERROR) {
770 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800771 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800772
Chia-I Wu6d844112018-06-27 07:17:41 +0800773 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
774 // is used to saturate legacy sRGB content. However, to make sure the same color under
775 // Display P3 will be saturated to the same color, we intentionally break the API spec
776 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
777 // such saturation matrix on Display P3 is understood fully, the API should always return
778 // identify matrix.
779 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800780 Dataspace::SRGB_LINEAR);
781
Chia-I Wu6d844112018-06-27 07:17:41 +0800782 // we will apply this on Display P3.
783 if (mEnhancedSaturationMatrix != mat4()) {
784 ColorSpace srgb(ColorSpace::sRGB());
785 ColorSpace displayP3(ColorSpace::DisplayP3());
786 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
787 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
788 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
789 }
790
Dan Stoza9e56aa02015-11-02 13:00:03 -0800791 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700792}
793
Romain Guy11d63f42017-07-20 12:47:14 -0700794void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700795 Mutex::Autolock _l(mStateLock);
796
Romain Guy11d63f42017-07-20 12:47:14 -0700797 char value[PROPERTY_VALUE_MAX];
798
799 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800800 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700801 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800802 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100803
804 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700805 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700806}
807
Mathias Agopiana67e4182012-06-19 17:26:12 -0700808void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800809 // Start boot animation service by setting a property mailbox
810 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700811 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800812 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700813 if (mStartPropertySetThread->join() != NO_ERROR) {
814 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800815 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700816}
817
Mathias Agopian875d8e12013-06-07 15:35:48 -0700818size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800819 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700820}
821
Mathias Agopian875d8e12013-06-07 15:35:48 -0700822size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800823 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700824}
825
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800826// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800827
Jamie Gennis582270d2011-08-17 18:19:00 -0700828bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800829 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800830 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800831 return authenticateSurfaceTextureLocked(bufferProducer);
832}
833
834bool SurfaceFlinger::authenticateSurfaceTextureLocked(
835 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800836 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800837 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800838}
839
Brian Anderson6b376712017-04-04 10:51:39 -0700840status_t SurfaceFlinger::getSupportedFrameTimestamps(
841 std::vector<FrameEvent>* outSupported) const {
842 *outSupported = {
843 FrameEvent::REQUESTED_PRESENT,
844 FrameEvent::ACQUIRE,
845 FrameEvent::LATCH,
846 FrameEvent::FIRST_REFRESH_START,
847 FrameEvent::LAST_REFRESH_START,
848 FrameEvent::GPU_COMPOSITION_DONE,
849 FrameEvent::DEQUEUE_READY,
850 FrameEvent::RELEASE,
851 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700852 ConditionalLock _l(mStateLock,
853 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700854 if (!getHwComposer().hasCapability(
855 HWC2::Capability::PresentFenceIsNotReliable)) {
856 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
857 }
858 return NO_ERROR;
859}
860
Dan Stoza7f7da322014-05-02 15:26:25 -0700861status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
862 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800863 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700864 return BAD_VALUE;
865 }
866
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500867 if (!display.get())
868 return NAME_NOT_FOUND;
869
Jesse Hall692c7232012-11-08 15:41:56 -0800870 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700871 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800872 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700873 type = i;
874 break;
875 }
876 }
877
878 if (type < 0) {
879 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700880 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700881
Mathias Agopian8b736f12012-08-13 17:54:26 -0700882 // TODO: Not sure if display density should handled by SF any longer
883 class Density {
884 static int getDensityFromProperty(char const* propName) {
885 char property[PROPERTY_VALUE_MAX];
886 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800887 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700888 density = atoi(property);
889 }
890 return density;
891 }
892 public:
893 static int getEmuDensity() {
894 return getDensityFromProperty("qemu.sf.lcd_density"); }
895 static int getBuildDensity() {
896 return getDensityFromProperty("ro.sf.lcd_density"); }
897 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700898
Dan Stoza7f7da322014-05-02 15:26:25 -0700899 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700900
Steven Thomas6d8110b2017-08-31 18:24:21 -0700901 ConditionalLock _l(mStateLock,
902 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800903 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700904 DisplayInfo info = DisplayInfo();
905
Dan Stoza9e56aa02015-11-02 13:00:03 -0800906 float xdpi = hwConfig->getDpiX();
907 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700908
909 if (type == DisplayDevice::DISPLAY_PRIMARY) {
910 // The density of the device is provided by a build property
911 float density = Density::getBuildDensity() / 160.0f;
912 if (density == 0) {
913 // the build doesn't provide a density -- this is wrong!
914 // use xdpi instead
915 ALOGE("ro.sf.lcd_density must be defined as a build property");
916 density = xdpi / 160.0f;
917 }
918 if (Density::getEmuDensity()) {
919 // if "qemu.sf.lcd_density" is specified, it overrides everything
920 xdpi = ydpi = density = Density::getEmuDensity();
921 density /= 160.0f;
922 }
923 info.density = density;
924
925 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700926 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800927 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700928 } else {
929 // TODO: where should this value come from?
930 static const int TV_DENSITY = 213;
931 info.density = TV_DENSITY / 160.0f;
932 info.orientation = 0;
933 }
934
Dan Stoza9e56aa02015-11-02 13:00:03 -0800935 info.w = hwConfig->getWidth();
936 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700937 info.xdpi = xdpi;
938 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800939 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900940 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800941
Andy McFadden91b2ca82014-06-13 14:04:23 -0700942 // This is how far in advance a buffer must be queued for
943 // presentation at a given time. If you want a buffer to appear
944 // on the screen at time N, you must submit the buffer before
945 // (N - presentationDeadline).
946 //
947 // Normally it's one full refresh period (to give SF a chance to
948 // latch the buffer), but this can be reduced by configuring a
949 // DispSync offset. Any additional delays introduced by the hardware
950 // composer or panel must be accounted for here.
951 //
952 // We add an additional 1ms to allow for processing time and
953 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800954 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800955 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700956
957 // All non-virtual displays are currently considered secure.
958 info.secure = true;
959
Iris Chang7501ed62018-04-30 14:45:42 +0800960 if (type == DisplayDevice::DISPLAY_PRIMARY &&
961 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
962 std::swap(info.w, info.h);
963 }
964
Michael Wright28f24d02016-07-12 13:30:53 -0700965 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700966 }
967
Dan Stoza7f7da322014-05-02 15:26:25 -0700968 return NO_ERROR;
969}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700970
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800971status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700972 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800973 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700974 return BAD_VALUE;
975 }
976
977 // FIXME for now we always return stats for the primary display
978 memset(stats, 0, sizeof(*stats));
979 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
980 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
981 return NO_ERROR;
982}
983
Yiwei Zhang1d465af2018-08-21 15:15:42 -0700984status_t SurfaceFlinger::getDisplayViewport(const sp<IBinder>& display, Rect* outViewport) {
985 if (outViewport == nullptr || display.get() == nullptr) {
986 return BAD_VALUE;
987 }
988
989 sp<const DisplayDevice> device(getDisplayDevice(display));
990 if (device == nullptr) {
991 return BAD_VALUE;
992 }
993
994 *outViewport = device->getViewport();
995
996 return NO_ERROR;
997}
998
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700999int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08001000 if (display == nullptr) {
1001 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +08001002 return BAD_VALUE;
1003 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001004
1005 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -08001006 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -07001007 return device->getActiveConfig();
1008 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001009
Dan Stoza24a42e92015-03-09 10:04:11 -07001010 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -07001011}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001012
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001013void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
1014 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
1015 this);
1016 int32_t type = hw->getDisplayType();
1017 int currentMode = hw->getActiveConfig();
1018
1019 if (mode == currentMode) {
1020 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
1021 return;
1022 }
1023
1024 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1025 ALOGW("Trying to set config for virtual display");
1026 return;
1027 }
1028
1029 hw->setActiveConfig(mode);
1030 getHwComposer().setActiveConfig(type, mode);
1031}
1032
1033status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
1034 class MessageSetActiveConfig: public MessageBase {
1035 SurfaceFlinger& mFlinger;
1036 sp<IBinder> mDisplay;
1037 int mMode;
1038 public:
1039 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
1040 int mode) :
1041 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1042 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -07001043 Vector<DisplayInfo> configs;
1044 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -07001045 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -07001046 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -07001047 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -07001048 return true;
Michael Lentine7306c672014-07-30 13:00:37 -07001049 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001050 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08001051 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001052 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07001053 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001054 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
1055 ALOGW("Attempt to set active config = %d for virtual display",
1056 mMode);
1057 } else {
1058 mFlinger.setActiveConfigInternal(hw, mMode);
1059 }
1060 return true;
1061 }
1062 };
1063 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
1064 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -07001065 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001066}
Michael Wright28f24d02016-07-12 13:30:53 -07001067status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001068 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001069 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
1070 return BAD_VALUE;
1071 }
1072
1073 if (!display.get()) {
1074 return NAME_NOT_FOUND;
1075 }
1076
1077 int32_t type = NAME_NOT_FOUND;
1078 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
1079 if (display == mBuiltinDisplays[i]) {
1080 type = i;
1081 break;
1082 }
1083 }
1084
1085 if (type < 0) {
1086 return type;
1087 }
1088
Peiyong Lina52f0292018-03-14 17:26:31 -07001089 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001090 {
1091 ConditionalLock _l(mStateLock,
1092 std::this_thread::get_id() != mMainThreadId);
1093 modes = getHwComposer().getColorModes(type);
1094 }
Michael Wright28f24d02016-07-12 13:30:53 -07001095 outColorModes->clear();
1096 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1097
1098 return NO_ERROR;
1099}
1100
Peiyong Lina52f0292018-03-14 17:26:31 -07001101ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001102 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -07001103 if (device != nullptr) {
1104 return device->getActiveColorMode();
1105 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001106 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001107}
1108
1109void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001110 ColorMode mode, Dataspace dataSpace,
1111 RenderIntent renderIntent) {
Michael Wright28f24d02016-07-12 13:30:53 -07001112 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -07001113 ColorMode currentMode = hw->getActiveColorMode();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001114 Dataspace currentDataSpace = hw->getCompositionDataSpace();
Peiyong Lin38e9a562018-04-10 16:24:20 -07001115 RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001116
Peiyong Lin38e9a562018-04-10 16:24:20 -07001117 if (mode == currentMode && dataSpace == currentDataSpace &&
1118 renderIntent == currentRenderIntent) {
1119 return;
1120 }
1121
1122 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1123 ALOGW("Trying to set config for virtual display");
1124 return;
1125 }
1126
1127 hw->setActiveColorMode(mode);
1128 hw->setCompositionDataSpace(dataSpace);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001129 hw->setActiveRenderIntent(renderIntent);
1130 getHwComposer().setActiveColorMode(type, mode, renderIntent);
1131
1132 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1133 decodeColorMode(mode).c_str(), mode,
1134 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1135 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001136}
1137
1138
1139status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001140 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001141 class MessageSetActiveColorMode: public MessageBase {
1142 SurfaceFlinger& mFlinger;
1143 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001144 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001145 public:
1146 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001147 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001148 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1149 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001150 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001151 mFlinger.getDisplayColorModes(mDisplay, &modes);
1152 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001153 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001154 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1155 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001156 return true;
1157 }
1158 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1159 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001160 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1161 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001162 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001163 ALOGW("Attempt to set active color mode %s %d for virtual display",
1164 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001165 } else {
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001166 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN,
1167 RenderIntent::COLORIMETRIC);
Michael Wright28f24d02016-07-12 13:30:53 -07001168 }
1169 return true;
1170 }
1171 };
1172 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1173 postMessageSync(msg);
1174 return NO_ERROR;
1175}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001176
Svetoslavd85084b2014-03-20 10:28:31 -07001177status_t SurfaceFlinger::clearAnimationFrameStats() {
1178 Mutex::Autolock _l(mStateLock);
1179 mAnimFrameTracker.clearStats();
1180 return NO_ERROR;
1181}
1182
1183status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1184 Mutex::Autolock _l(mStateLock);
1185 mAnimFrameTracker.getStats(outStats);
1186 return NO_ERROR;
1187}
1188
Dan Stozac4f471e2016-03-24 09:31:08 -07001189status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1190 HdrCapabilities* outCapabilities) const {
1191 Mutex::Autolock _l(mStateLock);
1192
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001193 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001194 if (displayDevice == nullptr) {
1195 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1196 return BAD_VALUE;
1197 }
1198
Peiyong Linfb069302018-04-25 14:34:31 -07001199 // At this point the DisplayDeivce should already be set up,
1200 // meaning the luminance information is already queried from
1201 // hardware composer and stored properly.
1202 const HdrCapabilities& capabilities = displayDevice->getHdrCapabilities();
1203 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1204 capabilities.getDesiredMaxLuminance(),
1205 capabilities.getDesiredMaxAverageLuminance(),
1206 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001207
1208 return NO_ERROR;
1209}
1210
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001211status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001212 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1213 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001214
Chia-I Wu90f669f2017-10-05 14:24:41 -07001215 if (mInjectVSyncs == enable) {
1216 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001217 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001218
1219 if (enable) {
1220 ALOGV("VSync Injections enabled");
1221 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001222 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001223 mInjectorEventThread = std::make_unique<
1224 impl::EventThread>(mVSyncInjector.get(),
1225 [this]() { resyncWithRateLimit(); },
1226 impl::EventThread::InterceptVSyncsCallback(),
1227 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001228 }
Lloyd Pique9123ae52018-01-22 17:14:00 -08001229 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001230 } else {
1231 ALOGV("VSync Injections disabled");
Lloyd Pique9123ae52018-01-22 17:14:00 -08001232 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001233 }
1234
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001235 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001236 });
1237 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001238 return NO_ERROR;
1239}
1240
1241status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001242 Mutex::Autolock _l(mStateLock);
1243
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001244 if (!mInjectVSyncs) {
1245 ALOGE("VSync Injections not enabled");
1246 return BAD_VALUE;
1247 }
1248 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1249 ALOGV("Injecting VSync inside SurfaceFlinger");
1250 mVSyncInjector->onInjectSyncEvent(when);
1251 }
1252 return NO_ERROR;
1253}
1254
Lloyd Pique755e3192018-01-31 16:46:15 -08001255status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1256 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001257 IPCThreadState* ipc = IPCThreadState::self();
1258 const int pid = ipc->getCallingPid();
1259 const int uid = ipc->getCallingUid();
1260 if ((uid != AID_SHELL) &&
1261 !PermissionCache::checkPermission(sDump, pid, uid)) {
1262 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1263 return PERMISSION_DENIED;
1264 }
1265
1266 // Try to acquire a lock for 1s, fail gracefully
1267 const status_t err = mStateLock.timedLock(s2ns(1));
1268 const bool locked = (err == NO_ERROR);
1269 if (!locked) {
1270 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1271 return TIMED_OUT;
1272 }
1273
1274 outLayers->clear();
1275 mCurrentState.traverseInZOrder([&](Layer* layer) {
1276 outLayers->push_back(layer->getLayerDebugInfo());
1277 });
1278
1279 mStateLock.unlock();
1280 return NO_ERROR;
1281}
1282
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001283// ----------------------------------------------------------------------------
1284
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001285sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1286 ISurfaceComposer::VsyncSource vsyncSource) {
1287 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1288 return mSFEventThread->createEventConnection();
1289 } else {
1290 return mEventThread->createEventConnection();
1291 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001292}
1293
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001294// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001295
1296void SurfaceFlinger::waitForEvent() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001297 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001298}
1299
1300void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001301 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001302}
1303
1304void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001305 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001306}
1307
1308void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001309 mRefreshPending = true;
Lloyd Pique9123ae52018-01-22 17:14:00 -08001310 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001311}
1312
1313status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001314 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001315 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001316}
1317
1318status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001319 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001320 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001321 if (res == NO_ERROR) {
1322 msg->wait();
1323 }
1324 return res;
1325}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001326
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001327void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001328 do {
1329 waitForEvent();
1330 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001331}
1332
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001333void SurfaceFlinger::enableHardwareVsync() {
1334 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001335 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001336 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001337 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1338 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001339 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001340 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001341}
1342
Jesse Hall948fe0c2013-10-14 12:56:09 -07001343void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001344 Mutex::Autolock _l(mHWVsyncLock);
1345
Jesse Hall948fe0c2013-10-14 12:56:09 -07001346 if (makeAvailable) {
1347 mHWVsyncAvailable = true;
1348 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001349 // Hardware vsync is not currently available, so abort the resync
1350 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001351 return;
1352 }
1353
David Sodman105b7dc2017-11-04 20:28:14 -07001354 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001355 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001356
1357 mPrimaryDispSync.reset();
1358 mPrimaryDispSync.setPeriod(period);
1359
1360 if (!mPrimaryHWVsyncEnabled) {
1361 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001362 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1363 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001364 mPrimaryHWVsyncEnabled = true;
1365 }
1366}
1367
Jesse Hall948fe0c2013-10-14 12:56:09 -07001368void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001369 Mutex::Autolock _l(mHWVsyncLock);
1370 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001371 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1372 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001373 mPrimaryDispSync.endResync();
1374 mPrimaryHWVsyncEnabled = false;
1375 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001376 if (makeUnavailable) {
1377 mHWVsyncAvailable = false;
1378 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001379}
1380
Tim Murray4a4e4a22016-04-19 16:29:23 +00001381void SurfaceFlinger::resyncWithRateLimit() {
1382 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001383
1384 // No explicit locking is needed here since EventThread holds a lock while calling this method
1385 static nsecs_t sLastResyncAttempted = 0;
1386 const nsecs_t now = systemTime();
1387 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001388 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001389 }
Dan Stoza57164302017-05-08 14:03:54 -07001390 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001391}
1392
Steven Thomasb02664d2017-07-26 18:48:28 -07001393void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1394 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001395 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001396 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001397 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001398 return;
1399 }
1400
1401 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001402 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001403 return;
1404 }
1405
Jamie Gennisd1700752013-10-14 12:22:52 -07001406 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001407
Jamie Gennisd1700752013-10-14 12:22:52 -07001408 { // Scope for the lock
1409 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001410 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001411 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001412 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001413 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001414
1415 if (needsHwVsync) {
1416 enableHardwareVsync();
1417 } else {
1418 disableHardwareVsync(false);
1419 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001420}
1421
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001422void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001423 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1424 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001425}
1426
Lloyd Pique715a2c12017-12-14 17:18:08 -08001427void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1428 HWC2::Connection connection) {
1429 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1430 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001431
Lloyd Piqueba04e622017-12-14 17:11:26 -08001432 // Ignore events that do not have the right sequenceId.
1433 if (sequenceId != getBE().mComposerSequenceId) {
1434 return;
1435 }
1436
Steven Thomasb02664d2017-07-26 18:48:28 -07001437 // Only lock if we're not on the main thread. This function is normally
1438 // called on a hwbinder thread, but for the primary display it's called on
1439 // the main thread with the state lock already held, so don't attempt to
1440 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001441 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001442
Lloyd Pique715a2c12017-12-14 17:18:08 -08001443 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001444
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001445 if (std::this_thread::get_id() == mMainThreadId) {
1446 // Process all pending hot plug events immediately if we are on the main thread.
1447 processDisplayHotplugEventsLocked();
1448 }
1449
Lloyd Piqueba04e622017-12-14 17:11:26 -08001450 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001451}
1452
Steven Thomasb02664d2017-07-26 18:48:28 -07001453void SurfaceFlinger::onRefreshReceived(int sequenceId,
1454 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001455 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001456 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001457 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001458 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001459 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001460}
1461
Dan Stoza9e56aa02015-11-02 13:00:03 -08001462void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001463 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001464 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001465 getHwComposer().setVsyncEnabled(disp,
1466 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001467}
1468
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001469// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001470void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001471 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001472 // Clear the drawing state so that the logic inside of
1473 // handleTransactionLocked will fire. It will determine the delta between
1474 // mCurrentState and mDrawingState and re-apply all changes when we make the
1475 // transition.
1476 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001477 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001478 mDisplays.clear();
1479}
1480
Steven Thomas050b2c82017-03-06 11:45:16 -08001481void SurfaceFlinger::updateVrFlinger() {
1482 if (!mVrFlinger)
1483 return;
1484 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001485 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001486 return;
1487 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001488
David Sodman105b7dc2017-11-04 20:28:14 -07001489 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001490 ALOGE("Vr flinger is only supported for remote hardware composer"
1491 " service connections. Ignoring request to transition to vr"
1492 " flinger.");
1493 mVrFlingerRequestsDisplay = false;
1494 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001495 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001496
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001497 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001498
Steven Thomasb02664d2017-07-26 18:48:28 -07001499 int currentDisplayPowerMode = getDisplayDeviceLocked(
1500 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001501
Steven Thomasb02664d2017-07-26 18:48:28 -07001502 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001503 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001504 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001505
Steven Thomasb02664d2017-07-26 18:48:28 -07001506 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001507 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001508 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1509 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001510 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001511
David Sodman105b7dc2017-11-04 20:28:14 -07001512 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1513 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001514
1515 if (vrFlingerRequestsDisplay) {
1516 mVrFlinger->GrantDisplayOwnership();
1517 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001518 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001519 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001520
1521 mVisibleRegionsDirty = true;
1522 invalidateHwcGeometry();
1523
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001524 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001525 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1526 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1527 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001528
Steven Thomasb02664d2017-07-26 18:48:28 -07001529 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001530 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001531 const nsecs_t period = activeConfig->getVsyncPeriod();
1532 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001533
Steven Thomasb02664d2017-07-26 18:48:28 -07001534 // Use phase of 0 since phase is not known.
1535 // Use latency of 0, which will snap to the ideal latency.
1536 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001537
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001538 android_atomic_or(1, &mRepaintEverything);
1539 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001540}
1541
Mathias Agopian4fec8732012-06-29 14:12:52 -07001542void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001543 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001544 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001545 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001546 bool frameMissed = !mHadClientComposition &&
1547 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001548 (mPreviousPresentFence->getSignalTime() ==
1549 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001550 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001551 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001552 mTimeStats.incrementMissedFrames();
1553 if (mPropagateBackpressure) {
1554 signalLayerUpdate();
1555 break;
1556 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001557 }
Dan Stoza50182882016-07-08 12:02:20 -07001558
Steven Thomas050b2c82017-03-06 11:45:16 -08001559 // Now that we're going to make it to the handleMessageTransaction()
1560 // call below it's safe to call updateVrFlinger(), which will
1561 // potentially trigger a display handoff.
1562 updateVrFlinger();
1563
Dan Stoza6b9454d2014-11-07 16:00:59 -08001564 bool refreshNeeded = handleMessageTransaction();
1565 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001566 refreshNeeded |= mRepaintEverything;
Chia-I Wuad8d8272018-06-26 10:18:18 +08001567 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001568 // Signal a refresh if a transaction modified the window state,
1569 // a new buffer was latched, or if HWC has requested a full
1570 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001571 signalRefresh();
1572 }
1573 break;
1574 }
1575 case MessageQueue::REFRESH: {
1576 handleMessageRefresh();
1577 break;
1578 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001579 }
1580}
1581
Dan Stoza6b9454d2014-11-07 16:00:59 -08001582bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001583 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001584 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001585 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001586 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001587 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001588 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001589}
1590
Dan Stoza6b9454d2014-11-07 16:00:59 -08001591bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001592 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001593 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001594}
1595
1596void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001597 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001598
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001599 mRefreshPending = false;
1600
Pablo Ceballos40845df2016-01-25 17:41:15 -08001601 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001602
Brian Andersond6927fb2016-07-23 23:37:30 -07001603 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001604 rebuildLayerStacks();
1605 setUpHWComposer();
1606 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001607 doTracing("handleRefresh");
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001608 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001609 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001610 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001611
David Sodman105b7dc2017-11-04 20:28:14 -07001612 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001613
1614 mHadClientComposition = false;
1615 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1616 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1617 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001618 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001619 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001620 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001621
Dan Stoza9e56aa02015-11-02 13:00:03 -08001622 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001623}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001624
Mathias Agopiancd60f992012-08-16 16:28:27 -07001625void SurfaceFlinger::doDebugFlashRegions()
1626{
1627 // is debugging enabled
1628 if (CC_LIKELY(!mDebugRegion))
1629 return;
1630
1631 const bool repaintEverything = mRepaintEverything;
1632 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1633 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001634 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001635 // transform the dirty region into this screen's coordinate space
1636 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1637 if (!dirtyRegion.isEmpty()) {
1638 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001639 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001640
1641 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001642 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001643 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001644 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1645
Mathias Agopianda27af92012-09-13 18:17:13 -07001646 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001647 }
1648 }
1649 }
1650
1651 postFramebuffer();
1652
1653 if (mDebugRegion > 1) {
1654 usleep(mDebugRegion * 1000);
1655 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001656
Dan Stoza9e56aa02015-11-02 13:00:03 -08001657 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001658 auto& displayDevice = mDisplays[displayId];
1659 if (!displayDevice->isDisplayOn()) {
1660 continue;
1661 }
1662
David Sodman105b7dc2017-11-04 20:28:14 -07001663 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1664 ALOGE_IF(result != NO_ERROR,
1665 "prepareFrame for display %zd failed:"
1666 " %d (%s)",
1667 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001668 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001669}
1670
Adrian Roos1e1a1282017-11-01 19:05:31 +01001671void SurfaceFlinger::doTracing(const char* where) {
1672 ATRACE_CALL();
1673 ATRACE_NAME(where);
1674 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001675 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001676 }
1677}
1678
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001679void SurfaceFlinger::logLayerStats() {
1680 ATRACE_CALL();
1681 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1682 int32_t hwcId = -1;
1683 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1684 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1685 if (displayDevice->isPrimary()) {
1686 hwcId = displayDevice->getHwcDisplayId();
1687 break;
1688 }
1689 }
1690 if (hwcId < 0) {
1691 ALOGE("LayerStats: Hmmm, no primary display?");
1692 return;
1693 }
1694 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1695 }
1696}
1697
Brian Andersond6927fb2016-07-23 23:37:30 -07001698void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001699{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001700 ATRACE_CALL();
1701 ALOGV("preComposition");
1702
Mathias Agopiancd60f992012-08-16 16:28:27 -07001703 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001704 mDrawingState.traverseInZOrder([&](Layer* layer) {
1705 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001706 needExtraInvalidate = true;
1707 }
Robert Carr2047fae2016-11-28 14:09:09 -08001708 });
1709
Mathias Agopiancd60f992012-08-16 16:28:27 -07001710 if (needExtraInvalidate) {
1711 signalLayerUpdate();
1712 }
1713}
1714
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001715void SurfaceFlinger::updateCompositorTiming(
1716 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1717 std::shared_ptr<FenceTime>& presentFenceTime) {
1718 // Update queue of past composite+present times and determine the
1719 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001720 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001721 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001722 while (!getBE().mCompositePresentTimes.empty()) {
1723 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001724 // Cached values should have been updated before calling this method,
1725 // which helps avoid duplicate syscalls.
1726 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1727 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1728 break;
1729 }
1730 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001731 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001732 }
1733
1734 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001735 while (getBE().mCompositePresentTimes.size() > 16) {
1736 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001737 }
1738
Brian Andersond0010582017-03-07 13:20:31 -08001739 setCompositorTimingSnapped(
1740 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1741}
1742
1743void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1744 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001745 // Integer division and modulo round toward 0 not -inf, so we need to
1746 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001747 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001748 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1749 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1750
Brian Andersond0010582017-03-07 13:20:31 -08001751 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1752 if (idealLatency <= 0) {
1753 idealLatency = vsyncInterval;
1754 }
1755
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001756 // Snap the latency to a value that removes scheduling jitter from the
1757 // composition and present times, which often have >1ms of jitter.
1758 // Reducing jitter is important if an app attempts to extrapolate
1759 // something (such as user input) to an accurate diasplay time.
1760 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1761 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001762 nsecs_t bias = vsyncInterval / 2;
1763 int64_t extraVsyncs =
1764 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1765 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1766 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001767
David Sodman99974d22017-11-28 12:04:33 -08001768 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1769 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1770 getBE().mCompositorTiming.interval = vsyncInterval;
1771 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001772}
1773
1774void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001775{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001776 ATRACE_CALL();
1777 ALOGV("postComposition");
1778
Brian Anderson3546a3f2016-07-14 11:51:14 -07001779 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001780 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001781 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001782 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001783 }
1784
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001785 // |mStateLock| not needed as we are on the main thread
1786 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001787
David Sodman73beded2017-11-15 11:56:06 -08001788 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001789 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001790 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001791 glCompositionDoneFenceTime =
1792 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001793 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001794 } else {
1795 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1796 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001797
David Sodman73beded2017-11-15 11:56:06 -08001798 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001799 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001800 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001801 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001802
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001803 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1804 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1805
1806 // We use the refreshStartTime which might be sampled a little later than
1807 // when we started doing work for this frame, but that should be okay
1808 // since updateCompositorTiming has snapping logic.
1809 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001810 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001811 CompositorTiming compositorTiming;
1812 {
David Sodman99974d22017-11-28 12:04:33 -08001813 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1814 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001815 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001816
Robert Carr2047fae2016-11-28 14:09:09 -08001817 mDrawingState.traverseInZOrder([&](Layer* layer) {
1818 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001819 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001820 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001821 recordBufferingStats(layer->getName().string(),
1822 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001823 }
Robert Carr2047fae2016-11-28 14:09:09 -08001824 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001825
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001826 if (presentFenceTime->isValid()) {
1827 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001828 enableHardwareVsync();
1829 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001830 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001831 }
1832 }
1833
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001834 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001835 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001836 enableHardwareVsync();
1837 }
1838 }
1839
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001840 if (mAnimCompositionPending) {
1841 mAnimCompositionPending = false;
1842
Brian Anderson4e606e32017-03-16 15:34:57 -07001843 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001844 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001845 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001846 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001847 // The HWC doesn't support present fences, so use the refresh
1848 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001849 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001850 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001851 mAnimFrameTracker.setActualPresentTime(presentTime);
1852 }
1853 mAnimFrameTracker.advanceFrame();
1854 }
Dan Stozab90cf072015-03-05 11:05:59 -08001855
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001856 mTimeStats.incrementTotalFrames();
1857 if (mHadClientComposition) {
1858 mTimeStats.incrementClientCompositionFrames();
1859 }
1860
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001861 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1862 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001863 return;
1864 }
1865
1866 nsecs_t currentTime = systemTime();
1867 if (mHasPoweredOff) {
1868 mHasPoweredOff = false;
1869 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001870 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001871 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001872 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1873 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001874 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001875 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001876 }
David Sodman4a36e932017-11-07 14:29:47 -08001877 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001878 }
David Sodman4a36e932017-11-07 14:29:47 -08001879 getBE().mLastSwapTime = currentTime;
Dan Stoza9fdb7e02018-06-21 12:10:12 -07001880
1881 {
1882 std::lock_guard lock(mTexturePoolMutex);
1883 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1884 if (refillCount > 0) {
1885 const size_t offset = mTexturePool.size();
1886 mTexturePool.resize(mTexturePoolSize);
1887 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1888 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1889 }
1890 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001891}
1892
1893void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001894 ATRACE_CALL();
1895 ALOGV("rebuildLayerStacks");
1896
Mathias Agopiancd60f992012-08-16 16:28:27 -07001897 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001898 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001899 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001900 mVisibleRegionsDirty = false;
1901 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001902
Jeff Sharkey76488112017-02-27 14:15:18 -07001903 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1904 Region opaqueRegion;
1905 Region dirtyRegion;
1906 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001907 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001908 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1909 const Transform& tr(displayDevice->getTransform());
1910 const Rect bounds(displayDevice->getBounds());
1911 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001912 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001913
Jeff Sharkey76488112017-02-27 14:15:18 -07001914 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001915 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001916 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1917 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001918 Region drawRegion(tr.transform(
1919 layer->visibleNonTransparentRegion));
1920 drawRegion.andSelf(bounds);
1921 if (!drawRegion.isEmpty()) {
1922 layersSortedByZ.add(layer);
1923 } else {
1924 // Clear out the HWC layer if this layer was
1925 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001926 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001927 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001928 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001929 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001930 // WM changes displayDevice->layerStack upon sleep/awake.
1931 // Here we make sure we delete the HWC layers even if
1932 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001933 hwcLayerDestroyed = layer->destroyHwcLayer(
1934 displayDevice->getHwcDisplayId());
1935 }
1936
1937 // If a layer is not going to get a release fence because
1938 // it is invisible, but it is also going to release its
1939 // old buffer, add it to the list of layers needing
1940 // fences.
1941 if (hwcLayerDestroyed) {
1942 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1943 mLayersWithQueuedFrames.cend(), layer);
1944 if (found != mLayersWithQueuedFrames.cend()) {
1945 layersNeedingFences.add(layer);
1946 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001947 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001948 });
1949 }
1950 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001951 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001952 displayDevice->undefinedRegion.set(bounds);
1953 displayDevice->undefinedRegion.subtractSelf(
1954 tr.transform(opaqueRegion));
1955 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001956 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001957 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001958}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001959
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001960// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001961// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001962// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001963// - Dataspace::DISPLAY_P3
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001964// The returned HDR data space is one of
1965// - Dataspace::UNKNOWN
1966// - Dataspace::BT2020_HLG
1967// - Dataspace::BT2020_PQ
1968Dataspace SurfaceFlinger::getBestDataspace(
1969 const sp<const DisplayDevice>& displayDevice, Dataspace* outHdrDataSpace) const {
1970 Dataspace bestDataSpace = Dataspace::SRGB;
1971 *outHdrDataSpace = Dataspace::UNKNOWN;
1972
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001973 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu1b6bafc2018-05-22 12:03:00 -07001974 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001975 case Dataspace::V0_SCRGB:
1976 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001977 case Dataspace::DISPLAY_P3:
Chia-I Wu0607fbe2018-05-18 10:59:36 -07001978 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001979 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001980 case Dataspace::BT2020_PQ:
1981 case Dataspace::BT2020_ITU_PQ:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001982 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001983 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001984 case Dataspace::BT2020_HLG:
1985 case Dataspace::BT2020_ITU_HLG:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001986 // When there's mixed PQ content and HLG content, we set the HDR
1987 // data space to be BT2020_PQ and convert HLG to PQ.
1988 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1989 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001990 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001991 break;
1992 default:
1993 break;
1994 }
Romain Guy54f154a2017-10-24 21:40:32 +01001995 }
1996
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001997 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001998}
1999
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002000// Pick the ColorMode / Dataspace for the display device.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002001void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002002 ColorMode* outMode, Dataspace* outDataSpace,
2003 RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002004 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2005 *outMode = ColorMode::NATIVE;
2006 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002007 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002008 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002009 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002010
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002011 Dataspace hdrDataSpace;
2012 Dataspace bestDataSpace = getBestDataspace(displayDevice, &hdrDataSpace);
2013
Peiyong Lin3c6b7ef2018-06-05 10:58:41 -07002014 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002015 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lin3c6b7ef2018-06-05 10:58:41 -07002016 !displayDevice->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002017 if (isHdr) {
2018 bestDataSpace = hdrDataSpace;
2019 }
2020
Chia-I Wu0d711262018-05-21 15:19:35 -07002021 RenderIntent intent;
2022 switch (mDisplayColorSetting) {
2023 case DisplayColorSetting::MANAGED:
2024 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002025 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002026 break;
2027 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002028 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002029 break;
2030 default: // vendor display color setting
2031 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2032 break;
2033 }
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002034
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002035 displayDevice->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002036}
2037
Mathias Agopiancd60f992012-08-16 16:28:27 -07002038void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002039 ATRACE_CALL();
2040 ALOGV("setUpHWComposer");
2041
Jesse Hall028dc8f2013-08-20 16:35:32 -07002042 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07002043 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07002044 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
2045 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
2046
2047 // If nothing has changed (!dirty), don't recompose.
2048 // If something changed, but we don't currently have any visible layers,
2049 // and didn't when we last did a composition, then skip it this time.
2050 // The second rule does two things:
2051 // - When all layers are removed from a display, we'll emit one black
2052 // frame, then nothing more until we get new layers.
2053 // - When a display is created with a private layer stack, we won't
2054 // emit any black frames until a layer is added to the layer stack.
2055 bool mustRecompose = dirty && !(empty && wasEmpty);
2056
2057 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2058 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
2059 mustRecompose ? "doing" : "skipping",
2060 dirty ? "+" : "-",
2061 empty ? "+" : "-",
2062 wasEmpty ? "+" : "-");
2063
Dan Stoza71433162014-02-04 16:22:36 -08002064 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07002065
2066 if (mustRecompose) {
2067 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
2068 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07002069 }
2070
Dan Stoza9e56aa02015-11-02 13:00:03 -08002071 // build the h/w work list
2072 if (CC_UNLIKELY(mGeometryInvalid)) {
2073 mGeometryInvalid = false;
2074 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2075 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
2076 const auto hwcId = displayDevice->getHwcDisplayId();
2077 if (hwcId >= 0) {
2078 const Vector<sp<Layer>>& currentLayers(
2079 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08002080 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002081 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08002082 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07002083 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002084 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002085 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07002086 }
2087 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07002088
Robert Carrae060832016-11-28 10:51:00 -08002089 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002090 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002091 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07002092 }
2093 }
2094 }
2095 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002096 }
Riley Andrews03414a12014-07-01 14:22:59 -07002097
Dan Stoza9e56aa02015-11-02 13:00:03 -08002098 // Set the per-frame data
2099 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2100 auto& displayDevice = mDisplays[displayId];
2101 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002102
Dan Stoza9e56aa02015-11-02 13:00:03 -08002103 if (hwcId < 0) {
2104 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07002105 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07002106 if (mDrawingState.colorMatrixChanged) {
2107 displayDevice->setColorTransform(mDrawingState.colorMatrix);
2108 status_t result = getBE().mHwc->setColorTransform(hwcId, mDrawingState.colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002109 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2110 "display %zd: %d", displayId, result);
2111 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002112 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu07376a92018-06-05 15:46:58 -07002113 if (layer->isHdrY410()) {
2114 layer->forceClientComposition(hwcId);
2115 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2116 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002117 !displayDevice->hasHDR10Support()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002118 layer->forceClientComposition(hwcId);
Chia-I Wu07376a92018-06-05 15:46:58 -07002119 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2120 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Peiyong Linf59a7192018-04-25 11:19:31 -07002121 !displayDevice->hasHLGSupport()) {
2122 layer->forceClientComposition(hwcId);
2123 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002124
chaviwc9232ed2017-11-14 15:31:15 -08002125 if (layer->getForceClientComposition(hwcId)) {
2126 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2127 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2128 continue;
2129 }
2130
Dan Stoza9e56aa02015-11-02 13:00:03 -08002131 layer->setPerFrameData(displayDevice);
2132 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002133
2134 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002135 ColorMode colorMode;
2136 Dataspace dataSpace;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002137 RenderIntent renderIntent;
2138 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
2139 setActiveColorModeInternal(displayDevice, colorMode, dataSpace, renderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002140 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002141 }
2142
Chia-I Wu28f320b2018-05-03 11:02:56 -07002143 mDrawingState.colorMatrixChanged = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002144
Dan Stoza9e56aa02015-11-02 13:00:03 -08002145 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002146 auto& displayDevice = mDisplays[displayId];
2147 if (!displayDevice->isDisplayOn()) {
2148 continue;
2149 }
2150
David Sodman105b7dc2017-11-04 20:28:14 -07002151 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002152 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2153 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002154 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002155}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002156
Mathias Agopiancd60f992012-08-16 16:28:27 -07002157void SurfaceFlinger::doComposition() {
2158 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002159 ALOGV("doComposition");
2160
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002161 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002162 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002163 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002164 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002165 // transform the dirty region into this screen's coordinate space
2166 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002167
2168 // repaint the framebuffer (if needed)
2169 doDisplayComposition(hw, dirtyRegion);
2170
Mathias Agopiancd60f992012-08-16 16:28:27 -07002171 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002172 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002173 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002174 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002175 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002176}
2177
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002178void SurfaceFlinger::postFramebuffer()
2179{
Mathias Agopian841cde52012-03-01 15:44:37 -08002180 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002181 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002182
Mathias Agopiana44b0412011-10-16 18:46:35 -07002183 const nsecs_t now = systemTime();
2184 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002185
Dan Stoza9e56aa02015-11-02 13:00:03 -08002186 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2187 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002188 if (!displayDevice->isDisplayOn()) {
2189 continue;
2190 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002191 const auto hwcId = displayDevice->getHwcDisplayId();
2192 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002193 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002194 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002195 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002196 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002197 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu99b46192018-06-21 15:52:50 +08002198 sp<Fence> releaseFence = Fence::NO_FENCE;
2199
Chia-I Wu7b549592017-11-15 09:14:57 -08002200 // The layer buffer from the previous frame (if any) is released
2201 // by HWC only when the release fence from this frame (if any) is
2202 // signaled. Always get the release fence from HWC first.
2203 auto hwcLayer = layer->getHwcLayer(hwcId);
Chia-I Wu99b46192018-06-21 15:52:50 +08002204 if (hwcId >= 0) {
2205 releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
2206 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002207
2208 // If the layer was client composited in the previous frame, we
2209 // need to merge with the previous client target acquire fence.
2210 // Since we do not track that, always merge with the current
2211 // client target acquire fence when it is available, even though
2212 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002213 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002214 releaseFence = Fence::merge("LayerRelease", releaseFence,
2215 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002216 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002217
Dan Stoza9e56aa02015-11-02 13:00:03 -08002218 layer->onLayerDisplayed(releaseFence);
2219 }
Chia-I Wu83806892017-11-16 10:50:20 -08002220
2221 // We've got a list of layers needing fences, that are disjoint with
2222 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2223 // supply them with the present fence.
2224 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002225 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002226 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2227 layer->onLayerDisplayed(presentFence);
2228 }
2229 }
2230
Dan Stoza9e56aa02015-11-02 13:00:03 -08002231 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002232 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002233 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002234 }
2235
Mathias Agopiana44b0412011-10-16 18:46:35 -07002236 mLastSwapBufferTime = systemTime() - now;
2237 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002238
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002239 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002240 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2241 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2242 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2243 logFrameStats();
2244 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002245 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002246}
2247
Mathias Agopian87baae12012-07-31 12:38:26 -07002248void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002249{
Mathias Agopian841cde52012-03-01 15:44:37 -08002250 ATRACE_CALL();
2251
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002252 // here we keep a copy of the drawing state (that is the state that's
2253 // going to be overwritten by handleTransactionLocked()) outside of
2254 // mStateLock so that the side-effects of the State assignment
2255 // don't happen with mStateLock held (which can cause deadlocks).
2256 State drawingState(mDrawingState);
2257
Mathias Agopianca4d3602011-05-19 15:38:14 -07002258 Mutex::Autolock _l(mStateLock);
2259 const nsecs_t now = systemTime();
2260 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002261
Mathias Agopianca4d3602011-05-19 15:38:14 -07002262 // Here we're guaranteed that some transaction flags are set
2263 // so we can call handleTransactionLocked() unconditionally.
2264 // We call getTransactionFlags(), which will also clear the flags,
2265 // with mStateLock held to guarantee that mCurrentState won't change
2266 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002267
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002268 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002269 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002270 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002271
Mathias Agopianca4d3602011-05-19 15:38:14 -07002272 mLastTransactionTime = systemTime() - now;
2273 mDebugInTransaction = 0;
2274 invalidateHwcGeometry();
2275 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002276}
2277
Lloyd Pique715a2c12017-12-14 17:18:08 -08002278DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique09594832018-01-22 17:48:03 -08002279 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002280 // Figure out whether the event is for the primary display or an
2281 // external display by matching the Hwc display id against one for a
2282 // connected display. If we did not find a match, we then check what
2283 // displays are not already connected to determine the type. If we don't
2284 // have a connected primary display, we assume the new display is meant to
2285 // be the primary display, and then if we don't have an external display,
2286 // we assume it is that.
2287 const auto primaryDisplayId =
2288 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2289 const auto externalDisplayId =
2290 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2291 if (primaryDisplayId && primaryDisplayId == display) {
2292 return DisplayDevice::DISPLAY_PRIMARY;
2293 } else if (externalDisplayId && externalDisplayId == display) {
2294 return DisplayDevice::DISPLAY_EXTERNAL;
2295 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2296 return DisplayDevice::DISPLAY_PRIMARY;
2297 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2298 return DisplayDevice::DISPLAY_EXTERNAL;
2299 }
2300
2301 return DisplayDevice::DISPLAY_ID_INVALID;
2302}
2303
Lloyd Piqueba04e622017-12-14 17:11:26 -08002304void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2305 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002306 auto displayType = determineDisplayType(event.display, event.connection);
2307 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2308 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2309 continue;
2310 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002311
2312 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2313 ALOGE("External displays are not supported by the vr hardware composer.");
2314 continue;
2315 }
2316
Lloyd Pique715a2c12017-12-14 17:18:08 -08002317 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002318
2319 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002320 if (!mBuiltinDisplays[displayType].get()) {
2321 ALOGV("Creating built in display %d", displayType);
2322 mBuiltinDisplays[displayType] = new BBinder();
2323 // All non-virtual displays are currently considered secure.
2324 DisplayDeviceState info(displayType, true);
2325 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2326 "Built-in Screen" : "External Screen";
2327 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4d234852018-01-22 17:21:36 -08002328 mInterceptor->saveDisplayCreation(info);
Steven Thomas3bed0522018-03-20 15:40:48 -07002329 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002330 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002331 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002332
Lloyd Piquefcd86612017-12-14 17:15:36 -08002333 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2334 if (idx >= 0) {
2335 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4d234852018-01-22 17:21:36 -08002336 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002337 mCurrentState.displays.removeItemsAt(idx);
2338 }
2339 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002340 }
2341
2342 processDisplayChangesLocked();
2343 }
2344
2345 mPendingHotplugEvents.clear();
2346}
2347
Lloyd Pique09594832018-01-22 17:48:03 -08002348sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2349 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2350 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002351 bool hasWideColorGamut = false;
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002352 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu99b46192018-06-21 15:52:50 +08002353 HdrCapabilities hdrCapabilities;
2354 int32_t supportedPerFrameMetadata = 0;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002355
Chia-I Wu99b46192018-06-21 15:52:50 +08002356 if (hasWideColorDisplay && hwcId >= 0) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002357 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique09594832018-01-22 17:48:03 -08002358 for (ColorMode colorMode : modes) {
2359 switch (colorMode) {
2360 case ColorMode::DISPLAY_P3:
2361 case ColorMode::ADOBE_RGB:
2362 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002363 hasWideColorGamut = true;
Lloyd Pique09594832018-01-22 17:48:03 -08002364 break;
2365 default:
2366 break;
2367 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002368
2369 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2370 colorMode);
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002371 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique09594832018-01-22 17:48:03 -08002372 }
2373 }
2374
Chia-I Wu99b46192018-06-21 15:52:50 +08002375 if (hwcId >= 0) {
2376 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
2377 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(hwcId);
2378 }
Lloyd Pique09594832018-01-22 17:48:03 -08002379
2380 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2381 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2382
2383 /*
2384 * Create our display's surface
2385 */
2386 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2387 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2388 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2389 renderSurface->setNativeWindow(nativeWindow.get());
2390 const int displayWidth = renderSurface->queryWidth();
2391 const int displayHeight = renderSurface->queryHeight();
2392
2393 // Make sure that composition can never be stalled by a virtual display
2394 // consumer that isn't processing buffers fast enough. We have to do this
2395 // in two places:
2396 // * Here, in case the display is composed entirely by HWC.
2397 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2398 // window's swap interval in eglMakeCurrent, so they'll override the
2399 // interval we set here.
2400 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2401 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2402 }
2403
2404 // virtual displays are always considered enabled
2405 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2406 : HWC_POWER_MODE_OFF;
2407
2408 sp<DisplayDevice> hw =
2409 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2410 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin2c327ac2018-04-19 22:06:34 -07002411 hasWideColorGamut, hdrCapabilities,
Chia-I Wu99b46192018-06-21 15:52:50 +08002412 supportedPerFrameMetadata, hwcColorModes, initialPowerMode);
Lloyd Pique09594832018-01-22 17:48:03 -08002413
2414 if (maxFrameBufferAcquiredBuffers >= 3) {
2415 nativeWindowSurface->preallocateBuffers();
2416 }
2417
2418 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002419 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2420 if (hasWideColorGamut) {
Lloyd Pique09594832018-01-22 17:48:03 -08002421 defaultColorMode = ColorMode::SRGB;
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002422 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique09594832018-01-22 17:48:03 -08002423 }
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002424 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace,
2425 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002426 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
2427 hw->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
2428 }
Lloyd Pique09594832018-01-22 17:48:03 -08002429 hw->setLayerStack(state.layerStack);
2430 hw->setProjection(state.orientation, state.viewport, state.frame);
2431 hw->setDisplayName(state.displayName);
2432
2433 return hw;
2434}
2435
Lloyd Pique347200f2017-12-14 17:00:15 -08002436void SurfaceFlinger::processDisplayChangesLocked() {
2437 // here we take advantage of Vector's copy-on-write semantics to
2438 // improve performance by skipping the transaction entirely when
2439 // know that the lists are identical
2440 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2441 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2442 if (!curr.isIdenticalTo(draw)) {
2443 mVisibleRegionsDirty = true;
2444 const size_t cc = curr.size();
2445 size_t dc = draw.size();
2446
2447 // find the displays that were removed
2448 // (ie: in drawing state but not in current state)
2449 // also handle displays that changed
2450 // (ie: displays that are in both lists)
2451 for (size_t i = 0; i < dc;) {
2452 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2453 if (j < 0) {
2454 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002455 // Call makeCurrent() on the primary display so we can
2456 // be sure that nothing associated with this display
2457 // is current.
2458 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2459 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2460 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2461 if (hw != nullptr) hw->disconnect(getHwComposer());
2462 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2463 mEventThread->onHotplugReceived(draw[i].type, false);
2464 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002465 } else {
2466 // this display is in both lists. see if something changed.
2467 const DisplayDeviceState& state(curr[j]);
2468 const wp<IBinder>& display(curr.keyAt(j));
2469 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2470 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2471 if (state_binder != draw_binder) {
2472 // changing the surface is like destroying and
2473 // recreating the DisplayDevice, so we just remove it
2474 // from the drawing state, so that it get re-added
2475 // below.
2476 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2477 if (hw != nullptr) hw->disconnect(getHwComposer());
2478 mDisplays.removeItem(display);
2479 mDrawingState.displays.removeItemsAt(i);
2480 dc--;
2481 // at this point we must loop to the next item
2482 continue;
2483 }
2484
2485 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2486 if (disp != nullptr) {
2487 if (state.layerStack != draw[i].layerStack) {
2488 disp->setLayerStack(state.layerStack);
2489 }
2490 if ((state.orientation != draw[i].orientation) ||
2491 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2492 disp->setProjection(state.orientation, state.viewport, state.frame);
2493 }
2494 if (state.width != draw[i].width || state.height != draw[i].height) {
2495 disp->setDisplaySize(state.width, state.height);
2496 }
2497 }
2498 }
2499 ++i;
2500 }
2501
2502 // find displays that were added
2503 // (ie: in current state but not in drawing state)
2504 for (size_t i = 0; i < cc; i++) {
2505 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2506 const DisplayDeviceState& state(curr[i]);
2507
2508 sp<DisplaySurface> dispSurface;
2509 sp<IGraphicBufferProducer> producer;
2510 sp<IGraphicBufferProducer> bqProducer;
2511 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002512 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002513
2514 int32_t hwcId = -1;
2515 if (state.isVirtualDisplay()) {
2516 // Virtual displays without a surface are dormant:
2517 // they have external state (layer stack, projection,
2518 // etc.) but no internal state (i.e. a DisplayDevice).
2519 if (state.surface != nullptr) {
2520 // Allow VR composer to use virtual displays.
2521 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2522 int width = 0;
2523 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2524 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2525 int height = 0;
2526 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2527 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2528 int intFormat = 0;
2529 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2530 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002531 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002532
2533 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2534 }
2535
2536 // TODO: Plumb requested format back up to consumer
2537
2538 sp<VirtualDisplaySurface> vds =
2539 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2540 bqProducer, bqConsumer,
2541 state.displayName);
2542
2543 dispSurface = vds;
2544 producer = vds;
2545 }
2546 } else {
2547 ALOGE_IF(state.surface != nullptr,
2548 "adding a supported display, but rendering "
2549 "surface is provided (%p), ignoring it",
2550 state.surface.get());
2551
2552 hwcId = state.type;
2553 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2554 producer = bqProducer;
2555 }
2556
2557 const wp<IBinder>& display(curr.keyAt(i));
2558 if (dispSurface != nullptr) {
Lloyd Pique09594832018-01-22 17:48:03 -08002559 mDisplays.add(display,
2560 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2561 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002562 if (!state.isVirtualDisplay()) {
2563 mEventThread->onHotplugReceived(state.type, true);
2564 }
2565 }
2566 }
2567 }
2568 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002569
2570 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002571}
2572
Mathias Agopian87baae12012-07-31 12:38:26 -07002573void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002574{
Dan Stoza7dde5992015-05-22 09:51:44 -07002575 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002576 mCurrentState.traverseInZOrder([](Layer* layer) {
2577 layer->notifyAvailableFrames();
2578 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002579
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002580 /*
2581 * Traversal of the children
2582 * (perform the transaction for each of them if needed)
2583 */
2584
Mathias Agopian3559b072012-08-15 13:46:03 -07002585 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002586 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002587 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002588 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002589
2590 const uint32_t flags = layer->doTransaction(0);
2591 if (flags & Layer::eVisibleRegion)
2592 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002593 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002594 }
2595
2596 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002597 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002598 */
2599
Mathias Agopiane57f2922012-08-09 16:29:12 -07002600 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002601 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002602 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002603 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002604
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002605 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002606 // The transform hint might have changed for some layers
2607 // (either because a display has changed, or because a layer
2608 // as changed).
2609 //
2610 // Walk through all the layers in currentLayers,
2611 // and update their transform hint.
2612 //
2613 // If a layer is visible only on a single display, then that
2614 // display is used to calculate the hint, otherwise we use the
2615 // default display.
2616 //
2617 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2618 // the hint is set before we acquire a buffer from the surface texture.
2619 //
2620 // NOTE: layer transactions have taken place already, so we use their
2621 // drawing state. However, SurfaceFlinger's own transaction has not
2622 // happened yet, so we must use the current state layer list
2623 // (soon to become the drawing state list).
2624 //
2625 sp<const DisplayDevice> disp;
2626 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002627 bool first = true;
2628 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002629 // NOTE: we rely on the fact that layers are sorted by
2630 // layerStack first (so we don't have to traverse the list
2631 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002632 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002633 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002634 currentlayerStack = layerStack;
2635 // figure out if this layerstack is mirrored
2636 // (more than one display) if so, pick the default display,
2637 // if not, pick the only display it's on.
2638 disp.clear();
2639 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2640 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002641 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002642 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002643 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002644 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002645 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002646 break;
2647 }
2648 }
2649 }
2650 }
Chet Haase91d25932013-04-11 15:24:55 -07002651
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002652 if (disp == nullptr) {
2653 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2654 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002655
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002656 // could be null when this layer is using a layerStack
2657 // that is not visible on any display. Also can occur at
2658 // screen off/on times.
2659 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002660 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002661
2662 // disp can be null if there is no display available at all to get
2663 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002664 if (disp != nullptr) {
2665 layer->updateTransformHint(disp);
2666 }
Robert Carr2047fae2016-11-28 14:09:09 -08002667
2668 first = false;
2669 });
Mathias Agopian84300952012-11-21 16:02:13 -08002670 }
2671
2672
Mathias Agopian3559b072012-08-15 13:46:03 -07002673 /*
2674 * Perform our own transaction if needed
2675 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002676
2677 if (mLayersAdded) {
2678 mLayersAdded = false;
2679 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002680 mVisibleRegionsDirty = true;
2681 }
2682
2683 // some layers might have been removed, so
2684 // we need to update the regions they're exposing.
2685 if (mLayersRemoved) {
2686 mLayersRemoved = false;
2687 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002688 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002689 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002690 // this layer is not visible anymore
2691 // TODO: we could traverse the tree from front to back and
2692 // compute the actual visible region
2693 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002694 Region visibleReg;
2695 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002696 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002697 }
Robert Carr2047fae2016-11-28 14:09:09 -08002698 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002699 }
2700
2701 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002702
2703 updateCursorAsync();
2704}
2705
2706void SurfaceFlinger::updateCursorAsync()
2707{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002708 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2709 auto& displayDevice = mDisplays[displayId];
2710 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002711 continue;
2712 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002713
2714 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2715 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002716 }
2717 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002718}
2719
2720void SurfaceFlinger::commitTransaction()
2721{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002722 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002723 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002724 for (const auto& l : mLayersPendingRemoval) {
2725 recordBufferingStats(l->getName().string(),
2726 l->getOccupancyHistory(true));
2727 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002728 }
2729 mLayersPendingRemoval.clear();
2730 }
2731
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002732 // If this transaction is part of a window animation then the next frame
2733 // we composite should be considered an animation as well.
2734 mAnimCompositionPending = mAnimTransactionPending;
2735
Mathias Agopian4fec8732012-06-29 14:12:52 -07002736 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002737 // clear the "changed" flags in current state
2738 mCurrentState.colorMatrixChanged = false;
2739
Robert Carr1f0a16a2016-10-24 16:27:39 -07002740 mDrawingState.traverseInZOrder([](Layer* layer) {
2741 layer->commitChildList();
2742 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002743 mTransactionPending = false;
2744 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002745 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002746}
2747
Chia-I Wuab0c3192017-08-01 11:29:00 -07002748void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002749 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002750{
Mathias Agopian841cde52012-03-01 15:44:37 -08002751 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002752 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002753
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002754 Region aboveOpaqueLayers;
2755 Region aboveCoveredLayers;
2756 Region dirty;
2757
Mathias Agopian87baae12012-07-31 12:38:26 -07002758 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002759
Robert Carr2047fae2016-11-28 14:09:09 -08002760 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002761 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002762 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002763
Jesse Hall01e29052013-02-19 16:13:35 -08002764 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002765 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002766 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002767
Mathias Agopianab028732010-03-16 16:41:46 -07002768 /*
2769 * opaqueRegion: area of a surface that is fully opaque.
2770 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002771 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002772
2773 /*
2774 * visibleRegion: area of a surface that is visible on screen
2775 * and not fully transparent. This is essentially the layer's
2776 * footprint minus the opaque regions above it.
2777 * Areas covered by a translucent surface are considered visible.
2778 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002779 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002780
2781 /*
2782 * coveredRegion: area of a surface that is covered by all
2783 * visible regions above it (which includes the translucent areas).
2784 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002785 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002786
Jesse Halla8026d22012-09-25 13:25:04 -07002787 /*
2788 * transparentRegion: area of a surface that is hinted to be completely
2789 * transparent. This is only used to tell when the layer has no visible
2790 * non-transparent regions and can be removed from the layer list. It
2791 * does not affect the visibleRegion of this layer or any layers
2792 * beneath it. The hint may not be correct if apps don't respect the
2793 * SurfaceView restrictions (which, sadly, some don't).
2794 */
2795 Region transparentRegion;
2796
Mathias Agopianab028732010-03-16 16:41:46 -07002797
2798 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002799 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002800 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002801 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002802 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002803 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002804 if (!visibleRegion.isEmpty()) {
2805 // Remove the transparent area from the visible region
2806 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002807 if (tr.preserveRects()) {
2808 // transform the transparent region
2809 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002810 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002811 // transformation too complex, can't do the
2812 // transparent region optimization.
2813 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002814 }
Mathias Agopianab028732010-03-16 16:41:46 -07002815 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002816
Mathias Agopianab028732010-03-16 16:41:46 -07002817 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002818 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002819 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002820 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2821 // the opaque region is the layer's footprint
2822 opaqueRegion = visibleRegion;
2823 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002824 }
2825 }
2826
Robert Carre5f4f692018-01-12 13:12:28 -08002827 if (visibleRegion.isEmpty()) {
2828 layer->clearVisibilityRegions();
2829 return;
2830 }
2831
Mathias Agopianab028732010-03-16 16:41:46 -07002832 // Clip the covered region to the visible region
2833 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2834
2835 // Update aboveCoveredLayers for next (lower) layer
2836 aboveCoveredLayers.orSelf(visibleRegion);
2837
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002838 // subtract the opaque region covered by the layers above us
2839 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002840
2841 // compute this layer's dirty region
2842 if (layer->contentDirty) {
2843 // we need to invalidate the whole region
2844 dirty = visibleRegion;
2845 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002846 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002847 layer->contentDirty = false;
2848 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002849 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002850 * the exposed region consists of two components:
2851 * 1) what's VISIBLE now and was COVERED before
2852 * 2) what's EXPOSED now less what was EXPOSED before
2853 *
2854 * note that (1) is conservative, we start with the whole
2855 * visible region but only keep what used to be covered by
2856 * something -- which mean it may have been exposed.
2857 *
2858 * (2) handles areas that were not covered by anything but got
2859 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002860 */
Mathias Agopianab028732010-03-16 16:41:46 -07002861 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002862 const Region oldVisibleRegion = layer->visibleRegion;
2863 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002864 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2865 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002866 }
2867 dirty.subtractSelf(aboveOpaqueLayers);
2868
2869 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002870 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002871
Mathias Agopianab028732010-03-16 16:41:46 -07002872 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002873 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002874
Jesse Halla8026d22012-09-25 13:25:04 -07002875 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002876 layer->setVisibleRegion(visibleRegion);
2877 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002878 layer->setVisibleNonTransparentRegion(
2879 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002880 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002881
Mathias Agopian87baae12012-07-31 12:38:26 -07002882 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002883}
2884
Chia-I Wuab0c3192017-08-01 11:29:00 -07002885void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002886 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002887 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002888 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002889 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002890 }
2891 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002892}
2893
Dan Stoza6b9454d2014-11-07 16:00:59 -08002894bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002895{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002896 ALOGV("handlePageFlip");
2897
Brian Andersond6927fb2016-07-23 23:37:30 -07002898 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002899
Mathias Agopian4fec8732012-06-29 14:12:52 -07002900 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002901 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002902 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002903
2904 // Store the set of layers that need updates. This set must not change as
2905 // buffers are being latched, as this could result in a deadlock.
2906 // Example: Two producers share the same command stream and:
2907 // 1.) Layer 0 is latched
2908 // 2.) Layer 0 gets a new frame
2909 // 2.) Layer 1 gets a new frame
2910 // 3.) Layer 1 is latched.
2911 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2912 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002913 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002914 if (layer->hasQueuedFrame()) {
2915 frameQueued = true;
2916 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002917 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002918 } else {
2919 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002920 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002921 } else {
2922 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002923 }
Robert Carr2047fae2016-11-28 14:09:09 -08002924 });
2925
Dan Stoza9e56aa02015-11-02 13:00:03 -08002926 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002927 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002928 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002929 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002930 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002931 newDataLatched = true;
2932 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002933 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002934
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002935 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002936
2937 // If we will need to wake up at some time in the future to deal with a
2938 // queued frame that shouldn't be displayed during this vsync period, wake
2939 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002940 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002941 signalLayerUpdate();
2942 }
2943
Chia-I Wuad8d8272018-06-26 10:18:18 +08002944 // enter boot animation on first buffer latch
2945 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2946 ALOGI("Enter boot animation");
2947 mBootStage = BootStage::BOOTANIMATION;
2948 }
2949
Dan Stoza6b9454d2014-11-07 16:00:59 -08002950 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002951 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002952}
2953
Mathias Agopianad456f92011-01-13 17:53:01 -08002954void SurfaceFlinger::invalidateHwcGeometry()
2955{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002956 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002957}
2958
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002959
Fabien Sanglard830b8472016-11-30 16:35:58 -08002960void SurfaceFlinger::doDisplayComposition(
2961 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002962 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002963{
Dan Stoza71433162014-02-04 16:22:36 -08002964 // We only need to actually compose the display if:
2965 // 1) It is being handled by hardware composer, which may need this to
2966 // keep its virtual display state machine in sync, or
2967 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002968 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002969 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002970 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002971 return;
2972 }
2973
Dan Stoza9e56aa02015-11-02 13:00:03 -08002974 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002975 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002976
2977 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002978 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002979}
2980
Chia-I Wub02087d2017-11-09 10:19:54 -08002981bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002982{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002983 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002984
Chia-I Wub02087d2017-11-09 10:19:54 -08002985 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002986 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002987 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002988 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002989 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002990
Chia-I Wu8e50e692018-05-04 10:12:37 -07002991 bool applyColorMatrix = false;
Chia-I Wu6d844112018-06-27 07:17:41 +08002992 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002993
Dan Stoza9e56aa02015-11-02 13:00:03 -08002994 if (hasClientComposition) {
2995 ALOGV("hasClientComposition");
2996
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002997 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002998 if (displayDevice->hasWideColorGamut()) {
2999 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003000 }
3001 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003002 getBE().mRenderEngine->setDisplayMaxLuminance(
3003 displayDevice->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003004
Chia-I Wu8e50e692018-05-04 10:12:37 -07003005 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
3006 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3007 HWC2::Capability::SkipClientColorTransform);
3008
Chia-I Wu6d844112018-06-27 07:17:41 +08003009 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003010 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3011 if (applyColorMatrix) {
Chia-I Wu6d844112018-06-27 07:17:41 +08003012 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003013 }
3014
Chia-I Wu6d844112018-06-27 07:17:41 +08003015 // The current enhanced saturation matrix is designed to enhance Display P3,
3016 // thus we only apply this matrix when the render intent is not colorimetric
3017 // and the output color space is Display P3.
3018 needsEnhancedColorMatrix =
Chia-I Wu0d711262018-05-21 15:19:35 -07003019 (displayDevice->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
Chia-I Wu6d844112018-06-27 07:17:41 +08003020 outputDataspace == Dataspace::DISPLAY_P3);
3021 if (needsEnhancedColorMatrix) {
3022 colorMatrix *= mEnhancedSaturationMatrix;
3023 }
3024
3025 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003026
Chia-I Wu7f402902017-11-09 12:51:10 -08003027 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003028 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003029 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08003030 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003031
3032 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08003033 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07003034 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
3035 }
3036 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003037 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003038
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003039 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003040 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003041 // when using overlays, we assume a fully transparent framebuffer
3042 // NOTE: we could reduce how much we need to clear, for instance
3043 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003044 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003045 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003046 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003047 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003048 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003049 // we're left with the letterbox region
3050 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08003051 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07003052
3053 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08003054 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07003055
Mathias Agopianb9494d52012-04-18 02:28:45 -07003056 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003057 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003058 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08003059 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003060 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003061 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003062
Yiwei Zhangcf39b7b2018-08-22 13:59:12 -07003063 const Rect& bounds(displayDevice->getBounds());
3064 const Rect& scissor(displayDevice->getScissor());
3065 if (scissor != bounds) {
3066 // scissor doesn't match the screen's dimensions, so we
3067 // need to clear everything outside of it and enable
3068 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003069
Yiwei Zhangcf39b7b2018-08-22 13:59:12 -07003070 // enable scissor for this frame
3071 const uint32_t height = displayDevice->getHeight();
3072 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
3073 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003074 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003075 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003076
Mathias Agopian85d751c2012-08-29 16:59:24 -07003077 /*
3078 * and then, render the layers targeted at the framebuffer
3079 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003080
Dan Stoza9e56aa02015-11-02 13:00:03 -08003081 ALOGV("Rendering client layers");
3082 const Transform& displayTransform = displayDevice->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003083 bool firstLayer = true;
3084 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3085 const Region clip(bounds.intersect(
3086 displayTransform.transform(layer->visibleRegion)));
3087 ALOGV("Layer: %s", layer->getName().string());
3088 ALOGV(" Composition type: %s",
3089 to_string(layer->getCompositionType(hwcId)).c_str());
3090 if (!clip.isEmpty()) {
3091 switch (layer->getCompositionType(hwcId)) {
3092 case HWC2::Composition::Cursor:
3093 case HWC2::Composition::Device:
3094 case HWC2::Composition::Sideband:
3095 case HWC2::Composition::SolidColor: {
3096 const Layer::State& state(layer->getDrawingState());
3097 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
3098 layer->isOpaque(state) && (state.color.a == 1.0f)
3099 && hasClientComposition) {
3100 // never clear the very first layer since we're
3101 // guaranteed the FB is already cleared
3102 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003103 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003104 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003105 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003106 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003107 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003108 break;
3109 }
3110 default:
3111 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003112 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003113 } else {
3114 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003115 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003116 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003117 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003118
Chia-I Wu6d844112018-06-27 07:17:41 +08003119 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003120 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003121 }
3122
Mathias Agopianf45c5102012-10-24 16:29:17 -07003123 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003124 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003125 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003126}
3127
Fabien Sanglard830b8472016-11-30 16:35:58 -08003128void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3129 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003130 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003131 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003132}
3133
Valerie Hauc38310f2019-08-28 14:08:17 -07003134status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3135 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3136 const sp<IBinder>& parentHandle,
3137 const sp<Layer>& parentLayer) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003138 // add this layer to the current state list
3139 {
3140 Mutex::Autolock _l(mStateLock);
Valerie Hauc38310f2019-08-28 14:08:17 -07003141 sp<Layer> parent;
3142
3143 if (parentHandle != nullptr) {
3144 parent = fromHandle(parentHandle);
3145 if (parent == nullptr) {
3146 return NAME_NOT_FOUND;
3147 }
3148 } else {
3149 parent = parentLayer;
3150 }
3151
Robert Carr1f0a16a2016-10-24 16:27:39 -07003152 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003153 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3154 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003155 return NO_MEMORY;
3156 }
Valerie Hauc38310f2019-08-28 14:08:17 -07003157
3158 auto [itr, inserted] = mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3159 if (!inserted) {
3160 ALOGE("-----------ERROR REGISTERING HANDLE, layer pair: handle is already a key");
3161 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003162 if (parent == nullptr) {
3163 mCurrentState.layersSortedByZ.add(lbc);
3164 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003165 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003166 ALOGE("addClientLayer called with a removed parent");
3167 return NAME_NOT_FOUND;
3168 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003169 parent->addChild(lbc);
3170 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003171
Yiwei Zhang243b3782018-05-15 17:40:04 -07003172 if (gbc != nullptr) {
3173 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3174 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3175 mMaxGraphicBufferProducerListSize,
3176 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3177 mGraphicBufferProducerList.size(),
3178 mMaxGraphicBufferProducerListSize, mNumLayers);
3179 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003180 mLayersAdded = true;
3181 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003182 }
3183
Mathias Agopian96f08192010-06-02 23:28:45 -07003184 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003185 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003186
Dan Stoza7d89d062015-04-30 13:29:25 -07003187 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003188}
3189
Valerie Hau6a8f8af2019-12-20 11:39:23 -08003190status_t SurfaceFlinger::removeLayerFromMap(const wp<Layer>& layer) {
Valerie Hauc38310f2019-08-28 14:08:17 -07003191 auto it = mLayersByLocalBinderToken.begin();
3192 while (it != mLayersByLocalBinderToken.end()) {
Valerie Hau6a8f8af2019-12-20 11:39:23 -08003193 if (it->second == layer) {
Valerie Hauc38310f2019-08-28 14:08:17 -07003194 it = mLayersByLocalBinderToken.erase(it);
3195 break;
3196 } else {
3197 it++;
3198 }
3199 }
3200 if (it == mLayersByLocalBinderToken.end()) {
3201 ALOGE("Failed to remove layer from mapping - could not find matching layer");
3202 return BAD_VALUE;
3203 }
3204 return NO_ERROR;
3205}
3206
Valerie Hau6a8f8af2019-12-20 11:39:23 -08003207status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
3208 Mutex::Autolock _l(mStateLock);
3209 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3210}
3211
chaviwca27f252018-02-06 16:46:39 -08003212status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3213 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003214 if (layer->isPendingRemoval()) {
3215 return NO_ERROR;
3216 }
3217
Robert Carr1f0a16a2016-10-24 16:27:39 -07003218 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003219 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003220 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003221 if (topLevelOnly) {
3222 return NO_ERROR;
3223 }
3224
Chia-I Wu98f1c102017-05-30 14:54:08 -07003225 sp<Layer> ancestor = p;
3226 while (ancestor->getParent() != nullptr) {
3227 ancestor = ancestor->getParent();
3228 }
3229 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3230 ALOGE("removeLayer called with a layer whose parent has been removed");
3231 return NAME_NOT_FOUND;
3232 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003233
3234 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003235 } else {
3236 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003237 }
3238
Robert Carr136e2f62017-02-08 17:54:29 -08003239 // As a matter of normal operation, the LayerCleaner will produce a second
3240 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3241 // so we will succeed in promoting it, but it's already been removed
3242 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3243 // otherwise something has gone wrong and we are leaking the layer.
3244 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003245 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3246 layer->getName().string(),
3247 (p != nullptr) ? p->getName().string() : "no-parent");
3248 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003249 } else if (index < 0) {
3250 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003251 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003252
Chia-I Wuc6657022017-08-15 11:18:17 -07003253 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003254 mLayersPendingRemoval.add(layer);
3255 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003256 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003257 setTransactionFlags(eTransactionNeeded);
3258 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003259}
3260
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003261uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003262 return android_atomic_release_load(&mTransactionFlags);
3263}
3264
Mathias Agopian3f844832013-08-07 21:24:32 -07003265uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003266 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3267}
3268
Mathias Agopian3f844832013-08-07 21:24:32 -07003269uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza2713c302018-03-28 17:07:36 -07003270 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3271}
3272
3273uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3274 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003275 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza2713c302018-03-28 17:07:36 -07003276 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003277 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003278 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003279 }
3280 return old;
3281}
3282
chaviwca27f252018-02-06 16:46:39 -08003283bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3284 for (const ComposerState& state : states) {
3285 // Here we need to check that the interface we're given is indeed
3286 // one of our own. A malicious client could give us a nullptr
3287 // IInterface, or one of its own or even one of our own but a
3288 // different type. All these situations would cause us to crash.
3289 if (state.client == nullptr) {
3290 return true;
3291 }
3292
3293 sp<IBinder> binder = IInterface::asBinder(state.client);
3294 if (binder == nullptr) {
3295 return true;
3296 }
3297
3298 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3299 return true;
3300 }
3301 }
3302 return false;
3303}
3304
Mathias Agopian8b33f032012-07-24 20:43:54 -07003305void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003306 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003307 const Vector<DisplayState>& displays,
3308 uint32_t flags)
3309{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003310 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003311 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003312 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003313
chaviwca27f252018-02-06 16:46:39 -08003314 if (containsAnyInvalidClientState(states)) {
3315 return;
3316 }
3317
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003318 if (flags & eAnimation) {
3319 // For window updates that are part of an animation we must wait for
3320 // previous animation "frames" to be handled.
3321 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003322 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003323 if (CC_UNLIKELY(err != NO_ERROR)) {
3324 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003325 // caller after a few seconds.
3326 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3327 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003328 mAnimTransactionPending = false;
3329 break;
3330 }
3331 }
3332 }
3333
chaviwca27f252018-02-06 16:46:39 -08003334 for (const DisplayState& display : displays) {
3335 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003336 }
3337
chaviwca27f252018-02-06 16:46:39 -08003338 for (const ComposerState& state : states) {
3339 transactionFlags |= setClientStateLocked(state);
3340 }
3341
3342 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3343 // as destroyed should only occur after setting all other states. This is to allow for a
3344 // child re-parent to happen before marking its original parent as destroyed (which would
3345 // then mark the child as destroyed).
3346 for (const ComposerState& state : states) {
3347 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003348 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003349
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003350 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3351 // anyway. This can be used as a flush mechanism for previous async transactions.
3352 // Empty animation transaction can be used to simulate back-pressure, so also force a
3353 // transaction for empty animation transactions.
3354 if (transactionFlags == 0 &&
3355 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003356 transactionFlags = eTransactionNeeded;
3357 }
3358
Mathias Agopian386aa982011-11-07 21:58:03 -08003359 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003360 if (mInterceptor->isEnabled()) {
3361 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003362 }
Irvel468051e2016-06-13 16:44:44 -07003363
Mathias Agopian386aa982011-11-07 21:58:03 -08003364 // this triggers the transaction
Dan Stoza2713c302018-03-28 17:07:36 -07003365 const auto start = (flags & eEarlyWakeup)
3366 ? VSyncModulator::TransactionStart::EARLY
3367 : VSyncModulator::TransactionStart::NORMAL;
3368 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003369
3370 // if this is a synchronous transaction, wait for it to take effect
3371 // before returning.
3372 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003373 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003374 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003375 if (flags & eAnimation) {
3376 mAnimTransactionPending = true;
3377 }
3378 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003379 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3380 if (CC_UNLIKELY(err != NO_ERROR)) {
3381 // just in case something goes wrong in SF, return to the
3382 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003383 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3384 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003385 break;
3386 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003387 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003388 }
3389}
3390
Mathias Agopiane57f2922012-08-09 16:29:12 -07003391uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3392{
Jesse Hall9a143922012-10-04 16:29:19 -07003393 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3394 if (dpyIdx < 0)
3395 return 0;
3396
Mathias Agopiane57f2922012-08-09 16:29:12 -07003397 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003398 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003399 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003400 const uint32_t what = s.what;
3401 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003402 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003403 disp.surface = s.surface;
3404 flags |= eDisplayTransactionNeeded;
3405 }
3406 }
3407 if (what & DisplayState::eLayerStackChanged) {
3408 if (disp.layerStack != s.layerStack) {
3409 disp.layerStack = s.layerStack;
3410 flags |= eDisplayTransactionNeeded;
3411 }
3412 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003413 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003414 if (disp.orientation != s.orientation) {
3415 disp.orientation = s.orientation;
3416 flags |= eDisplayTransactionNeeded;
3417 }
3418 if (disp.frame != s.frame) {
3419 disp.frame = s.frame;
3420 flags |= eDisplayTransactionNeeded;
3421 }
3422 if (disp.viewport != s.viewport) {
3423 disp.viewport = s.viewport;
3424 flags |= eDisplayTransactionNeeded;
3425 }
3426 }
Michael Lentine47e45402014-07-18 15:34:25 -07003427 if (what & DisplayState::eDisplaySizeChanged) {
3428 if (disp.width != s.width) {
3429 disp.width = s.width;
3430 flags |= eDisplayTransactionNeeded;
3431 }
3432 if (disp.height != s.height) {
3433 disp.height = s.height;
3434 flags |= eDisplayTransactionNeeded;
3435 }
3436 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003437 }
3438 return flags;
3439}
3440
Robert Carrd4ae7f32018-06-07 16:10:57 -07003441bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3442 IPCThreadState* ipc = IPCThreadState::self();
3443 const int pid = ipc->getCallingPid();
3444 const int uid = ipc->getCallingUid();
3445
3446 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3447 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3448 return false;
3449 }
3450 return true;
3451}
3452
chaviwca27f252018-02-06 16:46:39 -08003453uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3454 const layer_state_t& s = composerState.state;
3455 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3456
Valerie Hau6a8f8af2019-12-20 11:39:23 -08003457 sp<Layer> layer = fromHandle(s.surface);
3458 if (layer == nullptr || !(client->isAttached(s.surface))) {
chaviw8b3871a2017-11-01 17:41:01 -07003459 return 0;
3460 }
3461
3462 if (layer->isPendingRemoval()) {
3463 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3464 return 0;
3465 }
3466
3467 uint32_t flags = 0;
3468
3469 const uint32_t what = s.what;
3470 bool geometryAppliesWithResize =
3471 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003472
3473 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3474 // pending state will also be deferred.
3475 if (what & layer_state_t::eDeferTransaction) {
3476 layer->pushPendingState();
3477 }
3478
chaviw8b3871a2017-11-01 17:41:01 -07003479 if (what & layer_state_t::ePositionChanged) {
3480 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3481 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003482 }
chaviw8b3871a2017-11-01 17:41:01 -07003483 }
3484 if (what & layer_state_t::eLayerChanged) {
3485 // NOTE: index needs to be calculated before we update the state
3486 const auto& p = layer->getParent();
3487 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003488 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003489 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003490 mCurrentState.layersSortedByZ.removeAt(idx);
3491 mCurrentState.layersSortedByZ.add(layer);
3492 // we need traversal (state changed)
3493 // AND transaction (list changed)
3494 flags |= eTransactionNeeded|eTraversalNeeded;
3495 }
chaviw8b3871a2017-11-01 17:41:01 -07003496 } else {
3497 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003498 flags |= eTransactionNeeded|eTraversalNeeded;
3499 }
3500 }
chaviw8b3871a2017-11-01 17:41:01 -07003501 }
3502 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003503 // NOTE: index needs to be calculated before we update the state
3504 const auto& p = layer->getParent();
3505 if (p == nullptr) {
3506 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3507 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3508 mCurrentState.layersSortedByZ.removeAt(idx);
3509 mCurrentState.layersSortedByZ.add(layer);
3510 // we need traversal (state changed)
3511 // AND transaction (list changed)
3512 flags |= eTransactionNeeded|eTraversalNeeded;
3513 }
3514 } else {
3515 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3516 flags |= eTransactionNeeded|eTraversalNeeded;
3517 }
chaviw8b3871a2017-11-01 17:41:01 -07003518 }
3519 }
3520 if (what & layer_state_t::eSizeChanged) {
3521 if (layer->setSize(s.w, s.h)) {
3522 flags |= eTraversalNeeded;
3523 }
3524 }
3525 if (what & layer_state_t::eAlphaChanged) {
3526 if (layer->setAlpha(s.alpha))
3527 flags |= eTraversalNeeded;
3528 }
3529 if (what & layer_state_t::eColorChanged) {
3530 if (layer->setColor(s.color))
3531 flags |= eTraversalNeeded;
3532 }
3533 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003534 // TODO: b/109894387
3535 //
3536 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3537 // rotation. To see the problem observe that if we have a square parent, and a child
3538 // of the same size, then we rotate the child 45 degrees around it's center, the child
3539 // must now be cropped to a non rectangular 8 sided region.
3540 //
3541 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3542 // private API, and the WindowManager only uses rotation in one case, which is on a top
3543 // level layer in which cropping is not an issue.
3544 //
3545 // However given that abuse of rotation matrices could lead to surfaces extending outside
3546 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3547 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3548 // transformations.
3549 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003550 flags |= eTraversalNeeded;
3551 }
3552 if (what & layer_state_t::eTransparentRegionChanged) {
3553 if (layer->setTransparentRegionHint(s.transparentRegion))
3554 flags |= eTraversalNeeded;
3555 }
3556 if (what & layer_state_t::eFlagsChanged) {
3557 if (layer->setFlags(s.flags, s.mask))
3558 flags |= eTraversalNeeded;
3559 }
3560 if (what & layer_state_t::eCropChanged) {
3561 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3562 flags |= eTraversalNeeded;
3563 }
3564 if (what & layer_state_t::eFinalCropChanged) {
3565 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3566 flags |= eTraversalNeeded;
3567 }
3568 if (what & layer_state_t::eLayerStackChanged) {
3569 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3570 // We only allow setting layer stacks for top level layers,
3571 // everything else inherits layer stack from its parent.
3572 if (layer->hasParent()) {
3573 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3574 layer->getName().string());
3575 } else if (idx < 0) {
3576 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3577 "that also does not appear in the top level layer list. Something"
3578 " has gone wrong.", layer->getName().string());
3579 } else if (layer->setLayerStack(s.layerStack)) {
3580 mCurrentState.layersSortedByZ.removeAt(idx);
3581 mCurrentState.layersSortedByZ.add(layer);
3582 // we need traversal (state changed)
3583 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003584 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003585 }
3586 }
3587 if (what & layer_state_t::eDeferTransaction) {
3588 if (s.barrierHandle != nullptr) {
3589 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3590 } else if (s.barrierGbp != nullptr) {
3591 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3592 if (authenticateSurfaceTextureLocked(gbp)) {
3593 const auto& otherLayer =
3594 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3595 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3596 } else {
3597 ALOGE("Attempt to defer transaction to to an"
3598 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003599 }
3600 }
chaviw8b3871a2017-11-01 17:41:01 -07003601 // We don't trigger a traversal here because if no other state is
3602 // changed, we don't want this to cause any more work
3603 }
3604 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003605 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003606 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003607 if (!hadParent) {
3608 mCurrentState.layersSortedByZ.remove(layer);
3609 }
chaviw8b3871a2017-11-01 17:41:01 -07003610 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003611 }
chaviw8b3871a2017-11-01 17:41:01 -07003612 }
3613 if (what & layer_state_t::eReparentChildren) {
3614 if (layer->reparentChildren(s.reparentHandle)) {
3615 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003616 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003617 }
chaviw8b3871a2017-11-01 17:41:01 -07003618 if (what & layer_state_t::eDetachChildren) {
3619 layer->detachChildren();
3620 }
3621 if (what & layer_state_t::eOverrideScalingModeChanged) {
3622 layer->setOverrideScalingMode(s.overrideScalingMode);
3623 // We don't trigger a traversal here because if no other state is
3624 // changed, we don't want this to cause any more work
3625 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003626 return flags;
3627}
3628
chaviwca27f252018-02-06 16:46:39 -08003629void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3630 const layer_state_t& state = composerState.state;
3631 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3632
Valerie Hau6a8f8af2019-12-20 11:39:23 -08003633 sp<Layer> layer = fromHandle(state.surface);
3634 if (layer == nullptr || !(client->isAttached(state.surface))) {
chaviwca27f252018-02-06 16:46:39 -08003635 return;
3636 }
3637
3638 if (layer->isPendingRemoval()) {
3639 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3640 return;
3641 }
3642
3643 if (state.what & layer_state_t::eDestroySurface) {
3644 removeLayerLocked(mStateLock, layer);
3645 }
3646}
3647
Valerie Hauc38310f2019-08-28 14:08:17 -07003648status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3649 uint32_t h, PixelFormat format, uint32_t flags,
3650 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
3651 sp<IGraphicBufferProducer>* gbp,
3652 const sp<IBinder>& parentHandle,
3653 const sp<Layer>& parentLayer) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003654 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003655 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003656 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003657 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003658 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003659
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003660 status_t result = NO_ERROR;
3661
3662 sp<Layer> layer;
3663
Cody Northropbc755282017-03-31 12:00:08 -06003664 String8 uniqueName = getUniqueLayerName(name);
3665
Mathias Agopian3165cc22012-08-08 19:42:09 -07003666 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3667 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003668 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003669 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003670 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003671
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003672 break;
chaviw13fdc492017-06-27 12:40:18 -07003673 case ISurfaceComposerClient::eFXSurfaceColor:
3674 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003675 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003676 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003677 break;
3678 default:
3679 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003680 break;
3681 }
3682
Dan Stoza7d89d062015-04-30 13:29:25 -07003683 if (result != NO_ERROR) {
3684 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003685 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003686
Chia-I Wuab0c3192017-08-01 11:29:00 -07003687 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3688 // TODO b/64227542
3689 if (windowType == 441731) {
3690 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3691 layer->setPrimaryDisplayOnly();
3692 }
3693
Albert Chaulk479c60c2017-01-27 14:21:34 -05003694 layer->setInfo(windowType, ownerUid);
3695
Valerie Hauc38310f2019-08-28 14:08:17 -07003696 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003697 if (result != NO_ERROR) {
3698 return result;
3699 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003700 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003701
3702 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003703 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003704}
3705
Cody Northropbc755282017-03-31 12:00:08 -06003706String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3707{
3708 bool matchFound = true;
3709 uint32_t dupeCounter = 0;
3710
3711 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3712 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3713
Dan Stoza9fdb7e02018-06-21 12:10:12 -07003714 // Grab the state lock since we're accessing mCurrentState
3715 Mutex::Autolock lock(mStateLock);
3716
Cody Northropbc755282017-03-31 12:00:08 -06003717 // Loop over layers until we're sure there is no matching name
3718 while (matchFound) {
3719 matchFound = false;
Dan Stoza9fdb7e02018-06-21 12:10:12 -07003720 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003721 if (layer->getName() == uniqueName) {
3722 matchFound = true;
3723 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3724 }
3725 });
3726 }
3727
3728 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3729
3730 return uniqueName;
3731}
3732
David Sodman0c69cad2017-08-21 12:12:51 -07003733status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003734 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3735 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003736{
3737 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003738 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003739 case PIXEL_FORMAT_TRANSPARENT:
3740 case PIXEL_FORMAT_TRANSLUCENT:
3741 format = PIXEL_FORMAT_RGBA_8888;
3742 break;
3743 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003744 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003745 break;
3746 }
3747
David Sodman0c69cad2017-08-21 12:12:51 -07003748 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3749 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003750 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003751 *handle = layer->getHandle();
3752 *gbp = layer->getProducer();
3753 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003754 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003755
David Sodman0c69cad2017-08-21 12:12:51 -07003756 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003757 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003758}
3759
chaviw13fdc492017-06-27 12:40:18 -07003760status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003761 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003762 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003763{
chaviw13fdc492017-06-27 12:40:18 -07003764 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003765 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003766 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003767}
3768
Valerie Hau6a8f8af2019-12-20 11:39:23 -08003769status_t SurfaceFlinger::clearLayerFrameStats(const sp<const Client>& client, const sp<IBinder>& handle) {
3770 Mutex::Autolock _l(mStateLock);
3771 sp<Layer> layer = fromHandle(handle);
3772 if (layer == nullptr || !(client->isAttached(handle))) {
3773 return NAME_NOT_FOUND;
3774 }
3775 layer->clearFrameStats();
3776 return NO_ERROR;
3777}
3778
3779status_t SurfaceFlinger::getLayerFrameStats(const sp<const Client>& client, const sp<IBinder>& handle, FrameStats* outStats) {
3780 Mutex::Autolock _l(mStateLock);
3781 sp<Layer> layer = fromHandle(handle);
3782 if (layer == nullptr || !(client->isAttached(handle))) {
3783 return NAME_NOT_FOUND;
3784 }
3785 layer->getFrameStats(outStats);
3786 return NO_ERROR;
3787}
3788
Mathias Agopianac9fa422013-02-11 16:40:36 -08003789status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003790{
Valerie Hau6a8f8af2019-12-20 11:39:23 -08003791 Mutex::Autolock _l(mStateLock);
Robert Carr9524cb32017-02-13 11:32:32 -08003792 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003793 status_t err = NO_ERROR;
Valerie Hau6a8f8af2019-12-20 11:39:23 -08003794 sp<Layer> l = fromHandle(handle);
3795 if (l != nullptr || client->isAttached(handle)) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003796 mInterceptor->saveSurfaceDeletion(l);
Valerie Hau6a8f8af2019-12-20 11:39:23 -08003797 err = removeLayerLocked(mStateLock, l);
Mathias Agopian67106042013-03-14 19:18:13 -07003798 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3799 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003800 }
3801 return err;
3802}
3803
Mathias Agopian13127d82013-03-05 17:47:11 -08003804status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003805{
Valerie Hau6a8f8af2019-12-20 11:39:23 -08003806 Mutex::Autolock _l(mStateLock);
Mathias Agopian67106042013-03-14 19:18:13 -07003807 // called by ~LayerCleaner() when all references to the IBinder (handle)
3808 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003809 sp<Layer> l = layer.promote();
3810 if (l == nullptr) {
Valerie Hau6a8f8af2019-12-20 11:39:23 -08003811 removeLayerFromMap(layer);
Robert Carr9524cb32017-02-13 11:32:32 -08003812 // The layer has already been removed, carry on
3813 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003814 }
Valerie Hau6a8f8af2019-12-20 11:39:23 -08003815 removeLayerFromMap(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003816 // If we have a parent, then we can continue to live as long as it does.
Valerie Hau6a8f8af2019-12-20 11:39:23 -08003817 return removeLayerLocked(mStateLock, l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003818}
3819
Mathias Agopianb60314a2012-04-10 22:09:54 -07003820// ---------------------------------------------------------------------------
3821
Andy McFadden13a082e2012-08-24 10:16:42 -07003822void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003823 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003824 Vector<ComposerState> state;
3825 Vector<DisplayState> displays;
3826 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003827 d.what = DisplayState::eDisplayProjectionChanged |
3828 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003829 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003830 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003831 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003832 d.frame.makeInvalid();
3833 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003834 d.width = 0;
3835 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003836 displays.add(d);
3837 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003838 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3839 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003840
David Sodman105b7dc2017-11-04 20:28:14 -07003841 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003842 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003843 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003844
Brian Andersond0010582017-03-07 13:20:31 -08003845 // Use phase of 0 since phase is not known.
3846 // Use latency of 0, which will snap to the ideal latency.
3847 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003848}
3849
3850void SurfaceFlinger::initializeDisplays() {
3851 class MessageScreenInitialized : public MessageBase {
3852 SurfaceFlinger* flinger;
3853 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003854 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003855 virtual bool handler() {
3856 flinger->onInitializeDisplays();
3857 return true;
3858 }
3859 };
3860 sp<MessageBase> msg = new MessageScreenInitialized(this);
3861 postMessageAsync(msg); // we may be called from main thread, use async message
3862}
3863
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003864void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003865 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003866 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3867 this);
3868 int32_t type = hw->getDisplayType();
3869 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003870
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003871 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003872 return;
3873 }
3874
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003875 hw->setPowerMode(mode);
3876 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3877 ALOGW("Trying to set power mode for virtual display");
3878 return;
3879 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003880
Lloyd Pique4d234852018-01-22 17:21:36 -08003881 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003882 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003883 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3884 if (idx < 0) {
3885 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3886 return;
3887 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003888 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003889 }
3890
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003891 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003892 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003893 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003894 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3895 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003896 // FIXME: eventthread only knows about the main display right now
3897 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003898 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003899 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003900
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003901 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003902 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003903 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003904
3905 struct sched_param param = {0};
3906 param.sched_priority = 1;
3907 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3908 ALOGW("Couldn't set SCHED_FIFO on display on");
3909 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003910 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003911 // Turn off the display
3912 struct sched_param param = {0};
3913 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3914 ALOGW("Couldn't set SCHED_OTHER on display off");
3915 }
3916
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003917 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3918 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003919 disableHardwareVsync(true); // also cancels any in-progress resync
3920
Mathias Agopiancde87a32012-09-13 14:09:01 -07003921 // FIXME: eventthread only knows about the main display right now
3922 mEventThread->onScreenReleased();
3923 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003924
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003925 getHwComposer().setPowerMode(type, mode);
3926 mVisibleRegionsDirty = true;
3927 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003928 } else if (mode == HWC_POWER_MODE_DOZE ||
3929 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003930 // Update display while dozing
3931 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003932 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3933 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003934 // FIXME: eventthread only knows about the main display right now
3935 mEventThread->onScreenAcquired();
3936 resyncToHardwareVsync(true);
3937 }
3938 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3939 // Leave display going to doze
3940 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3941 disableHardwareVsync(true); // also cancels any in-progress resync
3942 // FIXME: eventthread only knows about the main display right now
3943 mEventThread->onScreenReleased();
3944 }
3945 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003946 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003947 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003948 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003949 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003950 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003951}
3952
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003953void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3954 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003955 SurfaceFlinger& mFlinger;
3956 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003957 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003958 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003959 MessageSetPowerMode(SurfaceFlinger& flinger,
3960 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3961 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003962 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003963 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003964 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003965 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003966 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003967 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003968 ALOGW("Attempt to set power mode = %d for virtual display",
3969 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003970 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003971 mFlinger.setPowerModeInternal(
3972 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003973 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003974 return true;
3975 }
3976 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003977 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003978 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003979}
3980
3981// ---------------------------------------------------------------------------
3982
Lloyd Pique755e3192018-01-31 16:46:15 -08003983status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3984 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003985 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003986
Mathias Agopianbd115332013-04-18 16:41:04 -07003987 IPCThreadState* ipc = IPCThreadState::self();
3988 const int pid = ipc->getCallingPid();
3989 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003990
Mathias Agopianbd115332013-04-18 16:41:04 -07003991 if ((uid != AID_SHELL) &&
3992 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003993 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003994 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003995 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003996 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003997 // (this would indicate SF is stuck, but we want to be able to
3998 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003999 status_t err = mStateLock.timedLock(s2ns(1));
4000 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004001 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004002 result.appendFormat(
4003 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4004 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004005 }
4006
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004007 bool dumpAll = true;
4008 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004009 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004010
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004011 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004012 if ((index < numArgs) &&
4013 (args[index] == String16("--list"))) {
4014 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004015 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004016 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004017 }
4018
4019 if ((index < numArgs) &&
4020 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004021 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004022 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004023 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004024 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004025
4026 if ((index < numArgs) &&
4027 (args[index] == String16("--latency-clear"))) {
4028 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004029 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004030 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004031 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004032
4033 if ((index < numArgs) &&
4034 (args[index] == String16("--dispsync"))) {
4035 index++;
4036 mPrimaryDispSync.dump(result);
4037 dumpAll = false;
4038 }
Dan Stozab90cf072015-03-05 11:05:59 -08004039
4040 if ((index < numArgs) &&
4041 (args[index] == String16("--static-screen"))) {
4042 index++;
4043 dumpStaticScreenStats(result);
4044 dumpAll = false;
4045 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004046
4047 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004048 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004049 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004050 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004051 dumpAll = false;
4052 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004053
4054 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4055 index++;
4056 dumpWideColorInfo(result);
4057 dumpAll = false;
4058 }
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004059
4060 if ((index < numArgs) &&
4061 (args[index] == String16("--enable-layer-stats"))) {
4062 index++;
4063 mLayerStats.enable();
4064 dumpAll = false;
4065 }
4066
4067 if ((index < numArgs) &&
4068 (args[index] == String16("--disable-layer-stats"))) {
4069 index++;
4070 mLayerStats.disable();
4071 dumpAll = false;
4072 }
4073
4074 if ((index < numArgs) &&
4075 (args[index] == String16("--clear-layer-stats"))) {
4076 index++;
4077 mLayerStats.clear();
4078 dumpAll = false;
4079 }
4080
4081 if ((index < numArgs) &&
4082 (args[index] == String16("--dump-layer-stats"))) {
4083 index++;
4084 mLayerStats.dump(result);
4085 dumpAll = false;
4086 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07004087
4088 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4089 index++;
4090 mTimeStats.parseArgs(asProto, args, index, result);
4091 dumpAll = false;
4092 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004093 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004094
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004095 if (dumpAll) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07004096 if (asProto) {
4097 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4098 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4099 } else {
4100 dumpAllLocked(args, index, result);
4101 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004102 }
4103
Mathias Agopian9795c422009-08-26 16:36:26 -07004104 if (locked) {
4105 mStateLock.unlock();
4106 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004107 }
4108 write(fd, result.string(), result.size());
4109 return NO_ERROR;
4110}
4111
Dan Stozac7014012014-02-14 15:03:43 -08004112void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4113 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004114{
Robert Carr2047fae2016-11-28 14:09:09 -08004115 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004116 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004117 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004118}
4119
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004120void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004121 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004122{
4123 String8 name;
4124 if (index < args.size()) {
4125 name = String8(args[index]);
4126 index++;
4127 }
4128
David Sodman105b7dc2017-11-04 20:28:14 -07004129 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004130 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08004131 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004132
4133 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004134 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004135 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004136 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004137 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004138 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004139 }
Robert Carr2047fae2016-11-28 14:09:09 -08004140 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004141 }
4142}
4143
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004144void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004145 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004146{
4147 String8 name;
4148 if (index < args.size()) {
4149 name = String8(args[index]);
4150 index++;
4151 }
4152
Robert Carr2047fae2016-11-28 14:09:09 -08004153 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004154 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004155 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004156 }
Robert Carr2047fae2016-11-28 14:09:09 -08004157 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004158
Svetoslavd85084b2014-03-20 10:28:31 -07004159 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004160}
4161
Jamie Gennis6547ff42013-07-16 20:12:42 -07004162// This should only be called from the main thread. Otherwise it would need
4163// the lock and should use mCurrentState rather than mDrawingState.
4164void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004165 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004166 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004167 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004168
4169 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4170}
4171
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004172void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004173{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004174 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004175
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004176 if (isLayerTripleBufferingDisabled())
4177 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004178
4179 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004180 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004181 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004182 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004183 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4184 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004185 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004186}
4187
Dan Stozab90cf072015-03-05 11:05:59 -08004188void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4189{
4190 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004191 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4192 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004193 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004194 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004195 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4196 b + 1, bucketTimeSec, percent);
4197 }
David Sodman4a36e932017-11-07 14:29:47 -08004198 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004199 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004200 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004201 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004202 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004203}
4204
Dan Stozae77c7662016-05-13 11:37:28 -07004205void SurfaceFlinger::recordBufferingStats(const char* layerName,
4206 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004207 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4208 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004209 for (const auto& segment : history) {
4210 if (!segment.usedThirdBuffer) {
4211 stats.twoBufferTime += segment.totalTime;
4212 }
4213 if (segment.occupancyAverage < 1.0f) {
4214 stats.doubleBufferedTime += segment.totalTime;
4215 } else if (segment.occupancyAverage < 2.0f) {
4216 stats.tripleBufferedTime += segment.totalTime;
4217 }
4218 ++stats.numSegments;
4219 stats.totalTime += segment.totalTime;
4220 }
4221}
4222
Brian Andersond6927fb2016-07-23 23:37:30 -07004223void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4224 result.appendFormat("Layer frame timestamps:\n");
4225
4226 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4227 const size_t count = currentLayers.size();
4228 for (size_t i=0 ; i<count ; i++) {
4229 currentLayers[i]->dumpFrameEvents(result);
4230 }
4231}
4232
Dan Stozae77c7662016-05-13 11:37:28 -07004233void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4234 result.append("Buffering stats:\n");
4235 result.append(" [Layer name] <Active time> <Two buffer> "
4236 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004237 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004238 typedef std::tuple<std::string, float, float, float> BufferTuple;
4239 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004240 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004241 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004242 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004243 if (stats.numSegments == 0) {
4244 continue;
4245 }
4246 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4247 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4248 stats.totalTime;
4249 float doubleBufferRatio = static_cast<float>(
4250 stats.doubleBufferedTime) / stats.totalTime;
4251 float tripleBufferRatio = static_cast<float>(
4252 stats.tripleBufferedTime) / stats.totalTime;
4253 sorted.insert({activeTime, {name, twoBufferRatio,
4254 doubleBufferRatio, tripleBufferRatio}});
4255 }
4256 for (const auto& sortedPair : sorted) {
4257 float activeTime = sortedPair.first;
4258 const BufferTuple& values = sortedPair.second;
4259 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4260 std::get<0>(values).c_str(), activeTime,
4261 std::get<1>(values), std::get<2>(values),
4262 std::get<3>(values));
4263 }
4264 result.append("\n");
4265}
4266
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004267void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4268 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004269 result.appendFormat("DisplayColorSetting: %s\n",
4270 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004271
4272 // TODO: print out if wide-color mode is active or not
4273
4274 for (size_t d = 0; d < mDisplays.size(); d++) {
4275 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4276 int32_t hwcId = displayDevice->getHwcDisplayId();
4277 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4278 continue;
4279 }
4280
4281 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004282 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004283 for (auto&& mode : modes) {
4284 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4285 }
4286
Peiyong Lina52f0292018-03-14 17:26:31 -07004287 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004288 result.appendFormat(" Current color mode: %s (%d)\n",
4289 decodeColorMode(currentMode).c_str(), currentMode);
4290 }
4291 result.append("\n");
4292}
4293
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004294LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004295 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004296 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4297 const State& state = useDrawing ? mDrawingState : mCurrentState;
4298 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004299 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004300 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004301 });
4302
4303 return layersProto;
4304}
4305
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004306LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4307 LayersProto layersProto;
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004308 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004309
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004310 SizeProto* resolution = layersProto.mutable_resolution();
4311 resolution->set_w(displayDevice->getWidth());
4312 resolution->set_h(displayDevice->getHeight());
4313
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004314 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4315 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4316 layersProto.set_global_transform(
4317 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4318
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004319 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004320 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004321 LayerProto* layerProto = layersProto.add_layers();
4322 layer->writeToProto(layerProto, hwcId);
4323 }
4324 });
4325
4326 return layersProto;
4327}
4328
Mathias Agopian74d211a2013-04-22 16:55:35 +02004329void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4330 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004331{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004332 bool colorize = false;
4333 if (index < args.size()
4334 && (args[index] == String16("--color"))) {
4335 colorize = true;
4336 index++;
4337 }
4338
4339 Colorizer colorizer(colorize);
4340
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004341 // figure out if we're stuck somewhere
4342 const nsecs_t now = systemTime();
4343 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4344 const nsecs_t inTransaction(mDebugInTransaction);
4345 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4346 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4347
4348 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004349 * Dump library configuration.
4350 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004351
4352 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004353 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004354 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004355 appendSfConfigString(result);
4356 appendUiConfigString(result);
4357 appendGuiConfigString(result);
4358 result.append("\n");
4359
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004360 result.append("\nWide-Color information:\n");
4361 dumpWideColorInfo(result);
4362
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004363 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004364 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004365 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004366 result.append(SyncFeatures::getInstance().toString());
4367 result.append("\n");
4368
David Sodman105b7dc2017-11-04 20:28:14 -07004369 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004370
Andy McFadden41d67d72014-04-25 16:58:34 -07004371 colorizer.bold(result);
4372 result.append("DispSync configuration: ");
4373 colorizer.reset(result);
Jorim Jaggie203e042018-06-19 15:57:08 +02004374 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4375 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
4376 result.appendFormat(
4377 "app phase %" PRId64 " ns, "
4378 "sf phase %" PRId64 " ns, "
4379 "early app phase %" PRId64 " ns, "
4380 "early sf phase %" PRId64 " ns, "
4381 "early app gl phase %" PRId64 " ns, "
4382 "early sf gl phase %" PRId64 " ns, "
4383 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4384 vsyncPhaseOffsetNs,
4385 sfVsyncPhaseOffsetNs,
4386 appEarlyOffset,
4387 sfEarlyOffset,
4388 appEarlyGlOffset,
4389 sfEarlyOffset,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004390 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004391 result.append("\n");
4392
Dan Stozab90cf072015-03-05 11:05:59 -08004393 // Dump static screen stats
4394 result.append("\n");
4395 dumpStaticScreenStats(result);
4396 result.append("\n");
4397
Dan Stozae77c7662016-05-13 11:37:28 -07004398 dumpBufferingStats(result);
4399
Andy McFadden4803b742012-09-24 19:07:20 -07004400 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004401 * Dump the visible layer list
4402 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004403 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004404 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004405 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4406 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004407 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004408
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004409 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004410 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004411 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004412 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004413
4414 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004415 * Dump Display state
4416 */
4417
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004418 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004419 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004420 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004421 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4422 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004423 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004424 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004425 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004426
4427 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004428 * Dump SurfaceFlinger global state
4429 */
4430
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004431 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004432 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004433 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004434
Mathias Agopian888c8222012-08-04 21:10:38 -07004435 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004436 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004437
David Sodmanbc815282017-11-05 18:57:52 -08004438 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004439
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004440 if (hw) {
4441 hw->undefinedRegion.dump(result, "undefinedRegion");
4442 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4443 hw->getOrientation(), hw->isDisplayOn());
4444 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004445 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004446 " last eglSwapBuffers() time: %f us\n"
4447 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004448 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004449 " refresh-rate : %f fps\n"
4450 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004451 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004452 " gpu_to_cpu_unsupported : %d\n"
4453 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004454 mLastSwapBufferTime/1000.0,
4455 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004456 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004457 1e9 / activeConfig->getVsyncPeriod(),
4458 activeConfig->getDpiX(),
4459 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004460 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004461
Mathias Agopian74d211a2013-04-22 16:55:35 +02004462 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004463 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004464
Mathias Agopian74d211a2013-04-22 16:55:35 +02004465 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004466 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004467
4468 /*
4469 * VSYNC state
4470 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004471 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004472 result.append("\n");
4473
4474 /*
Yichi Chen738966b2018-09-15 14:51:18 +08004475 * Tracing state
4476 */
4477 mTracing.dump(result);
4478 result.append("\n");
4479
4480 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004481 * HWC layer minidump
4482 */
4483 for (size_t d = 0; d < mDisplays.size(); d++) {
4484 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4485 int32_t hwcId = displayDevice->getHwcDisplayId();
4486 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4487 continue;
4488 }
4489
4490 result.appendFormat("Display %d HWC layers:\n", hwcId);
4491 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004492 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004493 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004494 });
Dan Stozae22aec72016-08-01 13:20:59 -07004495 result.append("\n");
4496 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004497
4498 /*
4499 * Dump HWComposer state
4500 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004501 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004502 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004503 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004504 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004505 result.appendFormat(" h/w composer %s\n",
4506 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004507 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004508
4509 /*
4510 * Dump gralloc state
4511 */
4512 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4513 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004514
4515 /*
4516 * Dump VrFlinger state if in use.
4517 */
4518 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4519 result.append("VrFlinger state:\n");
4520 result.append(mVrFlinger->Dump().c_str());
4521 result.append("\n");
4522 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004523}
4524
Mathias Agopian13127d82013-03-05 17:47:11 -08004525const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004526SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004527 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004528 wp<IBinder> dpy;
4529 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4530 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4531 dpy = mDisplays.keyAt(i);
4532 break;
4533 }
4534 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004535 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004536 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4537 // Just use the primary display so we have something to return
4538 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4539 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004540 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004541}
4542
Keun young Park63f165f2012-08-31 10:53:36 -07004543bool SurfaceFlinger::startDdmConnection()
4544{
4545 void* libddmconnection_dso =
4546 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4547 if (!libddmconnection_dso) {
4548 return false;
4549 }
4550 void (*DdmConnection_start)(const char* name);
4551 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004552 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004553 if (!DdmConnection_start) {
4554 dlclose(libddmconnection_dso);
4555 return false;
4556 }
4557 (*DdmConnection_start)(getServiceName());
4558 return true;
4559}
4560
Chia-I Wu28f320b2018-05-03 11:02:56 -07004561void SurfaceFlinger::updateColorMatrixLocked() {
4562 mat4 colorMatrix;
4563 if (mGlobalSaturationFactor != 1.0f) {
4564 // Rec.709 luma coefficients
4565 float3 luminance{0.213f, 0.715f, 0.072f};
4566 luminance *= 1.0f - mGlobalSaturationFactor;
4567 mat4 saturationMatrix = mat4(
4568 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4569 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4570 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4571 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4572 );
4573 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4574 } else {
4575 colorMatrix = mClientColorMatrix * mDaltonizer();
4576 }
4577
4578 if (mCurrentState.colorMatrix != colorMatrix) {
4579 mCurrentState.colorMatrix = colorMatrix;
4580 mCurrentState.colorMatrixChanged = true;
4581 setTransactionFlags(eTransactionNeeded);
4582 }
4583}
4584
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004585status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004586 switch (code) {
4587 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004588 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004589 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004590 case CLEAR_ANIMATION_FRAME_STATS:
4591 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004592 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004593 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004594 case ENABLE_VSYNC_INJECTIONS:
4595 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004596 {
4597 // codes that require permission check
Robert Carrd4ae7f32018-06-07 16:10:57 -07004598 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4599 IPCThreadState* ipc = IPCThreadState::self();
4600 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4601 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004602 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004603 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004604 break;
4605 }
Robert Carr1db73f62016-12-21 12:58:51 -08004606 /*
4607 * Calling setTransactionState is safe, because you need to have been
4608 * granted a reference to Client* and Handle* to do anything with it.
4609 *
4610 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4611 */
4612 case SET_TRANSACTION_STATE:
4613 case CREATE_SCOPED_CONNECTION:
4614 {
4615 return OK;
4616 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004617 case CAPTURE_SCREEN:
4618 {
4619 // codes that require permission check
4620 IPCThreadState* ipc = IPCThreadState::self();
4621 const int pid = ipc->getCallingPid();
4622 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004623 if ((uid != AID_GRAPHICS) &&
4624 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004625 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004626 return PERMISSION_DENIED;
4627 }
4628 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004629 }
chaviwa76b2712017-09-20 12:02:26 -07004630 case CAPTURE_LAYERS: {
4631 IPCThreadState* ipc = IPCThreadState::self();
4632 const int pid = ipc->getCallingPid();
4633 const int uid = ipc->getCallingUid();
4634 if ((uid != AID_GRAPHICS) &&
4635 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4636 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4637 return PERMISSION_DENIED;
4638 }
4639 break;
4640 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004641 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004642 return OK;
4643}
4644
4645status_t SurfaceFlinger::onTransact(
4646 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4647{
4648 status_t credentialCheck = CheckTransactCodeCredentials(code);
4649 if (credentialCheck != OK) {
4650 return credentialCheck;
4651 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004652
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004653 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4654 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004655 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004656 IPCThreadState* ipc = IPCThreadState::self();
4657 const int uid = ipc->getCallingUid();
4658 if (CC_UNLIKELY(uid != AID_SYSTEM
4659 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004660 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004661 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004662 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004663 return PERMISSION_DENIED;
4664 }
4665 int n;
4666 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004667 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004668 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004669 return NO_ERROR;
4670 case 1002: // SHOW_UPDATES
4671 n = data.readInt32();
4672 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004673 invalidateHwcGeometry();
4674 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004675 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004676 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004677 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004678 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004679 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004680 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004681 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004682 setTransactionFlags(
4683 eTransactionNeeded|
4684 eDisplayTransactionNeeded|
4685 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004686 return NO_ERROR;
4687 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004688 case 1006:{ // send empty update
4689 signalRefresh();
4690 return NO_ERROR;
4691 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004692 case 1008: // toggle use of hw composer
4693 n = data.readInt32();
4694 mDebugDisableHWC = n ? 1 : 0;
4695 invalidateHwcGeometry();
4696 repaintEverything();
4697 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004698 case 1009: // toggle use of transform hint
4699 n = data.readInt32();
4700 mDebugDisableTransformHint = n ? 1 : 0;
4701 invalidateHwcGeometry();
4702 repaintEverything();
4703 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004704 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004705 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004706 reply->writeInt32(0);
4707 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004708 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004709 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004710 return NO_ERROR;
4711 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004712 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004713 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004714 return NO_ERROR;
4715 }
4716 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004717 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004718 // daltonize
4719 n = data.readInt32();
4720 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004721 case 1:
4722 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4723 break;
4724 case 2:
4725 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4726 break;
4727 case 3:
4728 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4729 break;
4730 default:
4731 mDaltonizer.setType(ColorBlindnessType::None);
4732 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004733 }
4734 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004735 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004736 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004737 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004738 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004739
4740 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004741 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004742 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004743 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004744 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004745 // apply a color matrix
4746 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004747 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004748 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004749 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004750 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004751 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004752 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004753 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004754 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004755 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004756 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004757
4758 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4759 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004760 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004761 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4762 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4763 }
4764
Chia-I Wu28f320b2018-05-03 11:02:56 -07004765 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004766 return NO_ERROR;
4767 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004768 // This is an experimental interface
4769 // Needs to be shifted to proper binder interface when we productize
4770 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004771 n = data.readInt32();
4772 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004773 return NO_ERROR;
4774 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004775 case 1017: {
4776 n = data.readInt32();
4777 mForceFullDamage = static_cast<bool>(n);
4778 return NO_ERROR;
4779 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004780 case 1018: { // Modify Choreographer's phase offset
4781 n = data.readInt32();
4782 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4783 return NO_ERROR;
4784 }
4785 case 1019: { // Modify SurfaceFlinger's phase offset
4786 n = data.readInt32();
4787 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4788 return NO_ERROR;
4789 }
Irvel468051e2016-06-13 16:44:44 -07004790 case 1020: { // Layer updates interceptor
4791 n = data.readInt32();
4792 if (n) {
4793 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004794 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004795 }
4796 else{
4797 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004798 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004799 }
4800 return NO_ERROR;
4801 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004802 case 1021: { // Disable HWC virtual displays
4803 n = data.readInt32();
4804 mUseHwcVirtualDisplays = !n;
4805 return NO_ERROR;
4806 }
Romain Guy0147a172017-06-01 13:53:56 -07004807 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004808 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004809 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004810
Chia-I Wu28f320b2018-05-03 11:02:56 -07004811 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004812 return NO_ERROR;
4813 }
Romain Guy54f154a2017-10-24 21:40:32 +01004814 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004815 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004816 invalidateHwcGeometry();
4817 repaintEverything();
4818 return NO_ERROR;
4819 }
4820 case 1024: { // Is wide color gamut rendering/color management supported?
4821 reply->writeBool(hasWideColorDisplay);
4822 return NO_ERROR;
4823 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004824 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004825 n = data.readInt32();
4826 if (n) {
Yichi Chen738966b2018-09-15 14:51:18 +08004827 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004828 mTracing.enable();
4829 doTracing("tracing.enable");
4830 reply->writeInt32(NO_ERROR);
4831 } else {
Yichi Chen738966b2018-09-15 14:51:18 +08004832 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004833 status_t err = mTracing.disable();
4834 reply->writeInt32(err);
4835 }
4836 return NO_ERROR;
4837 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004838 case 1026: { // Get layer tracing status
4839 reply->writeBool(mTracing.isEnabled());
4840 return NO_ERROR;
4841 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004842 // Is a DisplayColorSetting supported?
4843 case 1027: {
Chia-I Wu0d711262018-05-21 15:19:35 -07004844 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
4845 if (!hw) {
4846 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004847 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004848
4849 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4850 switch (setting) {
4851 case DisplayColorSetting::MANAGED:
4852 reply->writeBool(hasWideColorDisplay);
4853 break;
4854 case DisplayColorSetting::UNMANAGED:
4855 reply->writeBool(true);
4856 break;
4857 case DisplayColorSetting::ENHANCED:
4858 reply->writeBool(hw->hasRenderIntent(RenderIntent::ENHANCE));
4859 break;
4860 default: // vendor display color setting
4861 reply->writeBool(hw->hasRenderIntent(static_cast<RenderIntent>(setting)));
4862 break;
4863 }
4864 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004865 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004866 }
4867 }
4868 return err;
4869}
4870
Steven Thomas6d8110b2017-08-31 18:24:21 -07004871void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004872 android_atomic_or(1, &mRepaintEverything);
4873 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004874}
4875
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004876// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4877class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004878public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004879 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4880 ~WindowDisconnector() {
4881 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004882 }
4883
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004884private:
4885 ANativeWindow* mWindow;
4886 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004887};
4888
Robert Carra1586de2019-04-02 16:32:58 -07004889status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4890 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004891 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4892 int32_t minLayerZ, int32_t maxLayerZ,
4893 bool useIdentityTransform,
Robert Carr5c999012019-02-19 10:05:00 -08004894 ISurfaceComposer::Rotation rotation,
4895 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004896 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004897
chaviwa76b2712017-09-20 12:02:26 -07004898 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4899
4900 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004901 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4902
Yiwei Zhangf4e02872018-08-20 16:42:23 -07004903 const Rect& dispScissor = device->getScissor();
4904 if (!dispScissor.isEmpty()) {
4905 sourceCrop.set(dispScissor);
4906 // adb shell screencap will default reqWidth and reqHeight to zeros.
4907 if (reqWidth == 0 || reqHeight == 0) {
Yiwei Zhang9ad73bc2018-08-21 22:11:37 -07004908 reqWidth = uint32_t(device->getViewport().width());
4909 reqHeight = uint32_t(device->getViewport().height());
Yiwei Zhangf4e02872018-08-20 16:42:23 -07004910 }
4911 }
4912
Robert Carr5c999012019-02-19 10:05:00 -08004913 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation,
4914 captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07004915
4916 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4917 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Robert Carra1586de2019-04-02 16:32:58 -07004918 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform,
4919 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07004920}
4921
4922status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004923 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004924 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004925 ATRACE_CALL();
4926
4927 class LayerRenderArea : public RenderArea {
4928 public:
Robert Carr578038f2018-03-09 12:25:24 -08004929 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4930 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004931 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004932 mLayer(layer),
4933 mCrop(crop),
4934 mFlinger(flinger),
4935 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004936 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004937 Rect getBounds() const override {
4938 const Layer::State& layerState(mLayer->getDrawingState());
4939 return Rect(layerState.active.w, layerState.active.h);
4940 }
4941 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4942 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4943 bool isSecure() const override { return false; }
4944 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004945 Rect getSourceCrop() const override {
4946 if (mCrop.isEmpty()) {
4947 return getBounds();
4948 } else {
4949 return mCrop;
4950 }
4951 }
Robert Carr578038f2018-03-09 12:25:24 -08004952 class ReparentForDrawing {
4953 public:
4954 const sp<Layer>& oldParent;
4955 const sp<Layer>& newParent;
4956
4957 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4958 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004959 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004960 }
Robert Carr15eae092018-03-23 13:43:53 -07004961 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004962 };
4963
4964 void render(std::function<void()> drawLayers) override {
4965 if (!mChildrenOnly) {
4966 mTransform = mLayer->getTransform().inverse();
4967 drawLayers();
4968 } else {
4969 Rect bounds = getBounds();
4970 screenshotParentLayer =
4971 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4972 bounds.getWidth(), bounds.getHeight(), 0);
4973
4974 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4975 drawLayers();
4976 }
4977 }
chaviwa76b2712017-09-20 12:02:26 -07004978
chaviwa76b2712017-09-20 12:02:26 -07004979 private:
chaviw7206d492017-11-10 16:16:12 -08004980 const sp<Layer> mLayer;
4981 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004982
4983 // In the "childrenOnly" case we reparent the children to a screenshot
4984 // layer which has no properties set and which does not draw.
4985 sp<ContainerLayer> screenshotParentLayer;
4986 Transform mTransform;
4987
4988 SurfaceFlinger* mFlinger;
4989 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004990 };
4991
Valerie Hauc38310f2019-08-28 14:08:17 -07004992 int reqWidth = 0;
4993 int reqHeight = 0;
4994 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08004995 Rect crop(sourceCrop);
chaviw7206d492017-11-10 16:16:12 -08004996
Valerie Hauc38310f2019-08-28 14:08:17 -07004997 {
4998 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08004999
Valerie Hauc38310f2019-08-28 14:08:17 -07005000 parent = fromHandle(layerHandleBinder);
5001 if (parent == nullptr || parent->isPendingRemoval()) {
5002 ALOGE("captureLayers called with an invalid or removed parent");
5003 return NAME_NOT_FOUND;
5004 }
5005
5006 const int uid = IPCThreadState::self()->getCallingUid();
5007 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5008 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5009 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5010 return PERMISSION_DENIED;
5011 }
5012
5013 if (sourceCrop.width() <= 0) {
5014 crop.left = 0;
5015 crop.right = parent->getCurrentState().active.w;
5016 }
5017
5018 if (sourceCrop.height() <= 0) {
5019 crop.top = 0;
5020 crop.bottom = parent->getCurrentState().active.h;
5021 }
5022
5023 reqWidth = crop.width() * frameScale;
5024 reqHeight = crop.height() * frameScale;
5025 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005026
Robert Carr578038f2018-03-09 12:25:24 -08005027 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005028
Robert Carr578038f2018-03-09 12:25:24 -08005029 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005030 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5031 if (!layer->isVisible()) {
5032 return;
Robert Carr578038f2018-03-09 12:25:24 -08005033 } else if (childrenOnly && layer == parent.get()) {
5034 return;
chaviwa76b2712017-09-20 12:02:26 -07005035 }
5036 visitor(layer);
5037 });
5038 };
Robert Carra1586de2019-04-02 16:32:58 -07005039 bool outCapturedSecureLayers = false;
5040 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false,
5041 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005042}
5043
5044status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5045 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005046 sp<GraphicBuffer>* outBuffer,
Robert Carra1586de2019-04-02 16:32:58 -07005047 bool useIdentityTransform,
5048 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005049 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005050
Iris Chang7501ed62018-04-30 14:45:42 +08005051 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07005052
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005053 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5054 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5055 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5056 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005057
5058 // This mutex protects syncFd and captureResult for communication of the return values from the
5059 // main thread back to this Binder thread
5060 std::mutex captureMutex;
5061 std::condition_variable captureCondition;
5062 std::unique_lock<std::mutex> captureLock(captureMutex);
5063 int syncFd = -1;
5064 std::optional<status_t> captureResult;
5065
Robert Carr03480e22018-01-04 16:02:06 -08005066 const int uid = IPCThreadState::self()->getCallingUid();
5067 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5068
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005069 sp<LambdaMessage> message = new LambdaMessage([&]() {
5070 // If there is a refresh pending, bug out early and tell the binder thread to try again
5071 // after the refresh.
5072 if (mRefreshPending) {
5073 ATRACE_NAME("Skipping screenshot for now");
5074 std::unique_lock<std::mutex> captureLock(captureMutex);
5075 captureResult = std::make_optional<status_t>(EAGAIN);
5076 captureCondition.notify_one();
5077 return;
5078 }
5079
5080 status_t result = NO_ERROR;
5081 int fd = -1;
5082 {
5083 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08005084 renderArea.render([&]() {
5085 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
Robert Carra1586de2019-04-02 16:32:58 -07005086 useIdentityTransform, forSystem, &fd,
5087 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005088 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005089 }
5090
5091 {
5092 std::unique_lock<std::mutex> captureLock(captureMutex);
5093 syncFd = fd;
5094 captureResult = std::make_optional<status_t>(result);
5095 captureCondition.notify_one();
5096 }
5097 });
5098
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005099 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005100 if (result == NO_ERROR) {
5101 captureCondition.wait(captureLock, [&]() { return captureResult; });
5102 while (*captureResult == EAGAIN) {
5103 captureResult.reset();
5104 result = postMessageAsync(message);
5105 if (result != NO_ERROR) {
5106 return result;
5107 }
5108 captureCondition.wait(captureLock, [&]() { return captureResult; });
5109 }
5110 result = *captureResult;
5111 }
5112
5113 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005114 sync_wait(syncFd, -1);
5115 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005116 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005117
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005118 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005119}
5120
chaviwa76b2712017-09-20 12:02:26 -07005121void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5122 TraverseLayersFunction traverseLayers, bool yswap,
5123 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005124 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005125
Lloyd Pique144e1162017-12-20 16:44:52 -08005126 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005127
5128 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005129 const auto raWidth = renderArea.getWidth();
5130 const auto raHeight = renderArea.getHeight();
5131
5132 const auto reqWidth = renderArea.getReqWidth();
5133 const auto reqHeight = renderArea.getReqHeight();
5134 Rect sourceCrop = renderArea.getSourceCrop();
5135
Iris Chang7501ed62018-04-30 14:45:42 +08005136 bool filtering = false;
5137 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5138 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5139 static_cast<int32_t>(reqHeight) != raWidth;
5140 } else {
5141 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5142 static_cast<int32_t>(reqHeight) != raHeight;
5143 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005144
Dan Stozac1879002014-05-22 15:59:05 -07005145 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005146 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005147 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005148 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005149 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5150 Transform tr;
5151 uint32_t flags = 0x00;
5152 switch (mPrimaryDisplayOrientation) {
5153 case DisplayState::eOrientation90:
5154 flags = Transform::ROT_90;
5155 break;
5156 case DisplayState::eOrientation180:
5157 flags = Transform::ROT_180;
5158 break;
5159 case DisplayState::eOrientation270:
5160 flags = Transform::ROT_270;
5161 break;
5162 }
5163 tr.set(flags, raWidth, raHeight);
5164 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005165 }
5166
5167 // ensure that sourceCrop is inside screen
5168 if (sourceCrop.left < 0) {
5169 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5170 }
chaviwa76b2712017-09-20 12:02:26 -07005171 if (sourceCrop.right > raWidth) {
5172 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005173 }
5174 if (sourceCrop.top < 0) {
5175 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5176 }
chaviwa76b2712017-09-20 12:02:26 -07005177 if (sourceCrop.bottom > raHeight) {
5178 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005179 }
5180
Chia-I Wu36574d92018-05-16 10:54:36 -07005181 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5182 engine.setOutputDataSpace(Dataspace::SRGB);
5183 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005184
Mathias Agopian180f10d2013-04-10 22:55:41 -07005185 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005186 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005187
Iris Chang7501ed62018-04-30 14:45:42 +08005188 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5189 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5190 // convert hw orientation into flag presentation
5191 // here inverse transform needed
5192 uint8_t hw_rot_90 = 0x00;
5193 uint8_t hw_flip_hv = 0x00;
5194 switch (mPrimaryDisplayOrientation) {
5195 case DisplayState::eOrientation90:
5196 hw_rot_90 = Transform::ROT_90;
5197 hw_flip_hv = Transform::ROT_180;
5198 break;
5199 case DisplayState::eOrientation180:
5200 hw_flip_hv = Transform::ROT_180;
5201 break;
5202 case DisplayState::eOrientation270:
5203 hw_rot_90 = Transform::ROT_90;
5204 break;
5205 }
5206
5207 // transform flags operation
5208 // 1) flip H V if both have ROT_90 flag
5209 // 2) XOR these flags
5210 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5211 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5212 if (rotation_rot_90 & hw_rot_90) {
5213 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5214 }
5215 rotation = static_cast<Transform::orientation_flags>
5216 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5217 }
5218
Mathias Agopian180f10d2013-04-10 22:55:41 -07005219 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005220 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005221 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005222 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005223
chaviw50da5042018-04-09 13:49:37 -07005224 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005225 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005226 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005227
chaviwa76b2712017-09-20 12:02:26 -07005228 traverseLayers([&](Layer* layer) {
5229 if (filtering) layer->setFiltering(true);
5230 layer->draw(renderArea, useIdentityTransform);
5231 if (filtering) layer->setFiltering(false);
5232 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005233}
5234
chaviwa76b2712017-09-20 12:02:26 -07005235status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5236 TraverseLayersFunction traverseLayers,
5237 ANativeWindowBuffer* buffer,
Robert Carra1586de2019-04-02 16:32:58 -07005238 bool useIdentityTransform, bool forSystem,
5239 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005240 ATRACE_CALL();
5241
chaviwa76b2712017-09-20 12:02:26 -07005242 traverseLayers([&](Layer* layer) {
Robert Carra1586de2019-04-02 16:32:58 -07005243 outCapturedSecureLayers =
5244 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005245 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005246
Robert Carr03480e22018-01-04 16:02:06 -08005247 // We allow the system server to take screenshots of secure layers for
5248 // use in situations like the Screen-rotation animation and place
5249 // the impetus on WindowManager to not persist them.
Robert Carra1586de2019-04-02 16:32:58 -07005250 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005251 ALOGW("FB is protected: PERMISSION_DENIED");
5252 return PERMISSION_DENIED;
5253 }
5254
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005255 // this binds the given EGLImage as a framebuffer for the
5256 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005257 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005258 if (bufferBond.getStatus() != NO_ERROR) {
5259 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005260 return INVALID_OPERATION;
5261 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005262
Dan Stozaabcda352017-06-01 14:37:39 -07005263 // this will in fact render into our dequeued buffer
5264 // via an FBO, which means we didn't have to create
5265 // an EGLSurface and therefore we're not
5266 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005267 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005268
Dan Stozaabcda352017-06-01 14:37:39 -07005269 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005270 getRenderEngine().finish();
5271 *outSyncFd = -1;
5272
chaviwa76b2712017-09-20 12:02:26 -07005273 const auto reqWidth = renderArea.getReqWidth();
5274 const auto reqHeight = renderArea.getReqHeight();
5275
Dan Stozaabcda352017-06-01 14:37:39 -07005276 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5277 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005278 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005279 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005280 } else {
5281 base::unique_fd syncFd = getRenderEngine().flush();
5282 if (syncFd < 0) {
5283 getRenderEngine().finish();
5284 }
5285 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005286 }
5287
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005288 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005289}
5290
Mathias Agopiand5556842013-09-19 17:08:37 -07005291void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005292 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005293 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005294 for (size_t y = 0; y < h; y++) {
5295 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5296 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005297 if (p[x] != 0xFF000000) return;
5298 }
5299 }
chaviwa76b2712017-09-20 12:02:26 -07005300 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005301
Robert Carr2047fae2016-11-28 14:09:09 -08005302 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005303 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005304 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005305 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5306 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5307 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5308 static_cast<float>(state.color.a));
5309 i++;
5310 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005311 }
5312}
5313
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005314// ---------------------------------------------------------------------------
5315
Dan Stoza412903f2017-04-27 13:42:17 -07005316void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5317 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005318}
5319
Dan Stoza412903f2017-04-27 13:42:17 -07005320void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5321 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005322}
5323
chaviwa76b2712017-09-20 12:02:26 -07005324void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5325 int32_t maxLayerZ,
5326 const LayerVector::Visitor& visitor) {
5327 // We loop through the first level of layers without traversing,
5328 // as we need to interpret min/max layer Z in the top level Z space.
5329 for (const auto& layer : mDrawingState.layersSortedByZ) {
5330 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5331 continue;
5332 }
5333 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005334 // relative layers are traversed in Layer::traverseInZOrder
5335 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005336 continue;
5337 }
5338 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005339 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5340 return;
5341 }
chaviwa76b2712017-09-20 12:02:26 -07005342 if (!layer->isVisible()) {
5343 return;
5344 }
5345 visitor(layer);
5346 });
5347 }
5348}
5349
Valerie Hauc38310f2019-08-28 14:08:17 -07005350sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
5351 BBinder *b = handle->localBinder();
5352 if (b == nullptr) {
5353 return nullptr;
5354 }
5355 auto it = mLayersByLocalBinderToken.find(b);
5356 if (it != mLayersByLocalBinderToken.end()) {
5357 auto ret = it->second.promote();
5358 return ret;
5359 }
5360 return nullptr;
5361}
Mathias Agopian3f844832013-08-07 21:24:32 -07005362
Valerie Hauc38310f2019-08-28 14:08:17 -07005363} // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005364
5365#if defined(__gl_h_)
5366#error "don't include gl/gl.h in this file"
5367#endif
5368
5369#if defined(__gl2_h_)
5370#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005371#endif