blob: 58dfc82066e1278fe42589042ebf19333e3ad608 [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
Dan Stoza9e56aa02015-11-02 13:00:03 -08003063 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07003064 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07003065 // scissor on the main display. It should never be needed
3066 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08003067 const Rect& bounds(displayDevice->getBounds());
3068 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003069 if (scissor != bounds) {
3070 // scissor doesn't match the screen's dimensions, so we
3071 // need to clear everything outside of it and enable
3072 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003073
Mathias Agopianf45c5102012-10-24 16:29:17 -07003074 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08003075 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08003076 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07003077 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003078 }
3079 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003080 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003081
Mathias Agopian85d751c2012-08-29 16:59:24 -07003082 /*
3083 * and then, render the layers targeted at the framebuffer
3084 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003085
Dan Stoza9e56aa02015-11-02 13:00:03 -08003086 ALOGV("Rendering client layers");
3087 const Transform& displayTransform = displayDevice->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003088 bool firstLayer = true;
3089 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3090 const Region clip(bounds.intersect(
3091 displayTransform.transform(layer->visibleRegion)));
3092 ALOGV("Layer: %s", layer->getName().string());
3093 ALOGV(" Composition type: %s",
3094 to_string(layer->getCompositionType(hwcId)).c_str());
3095 if (!clip.isEmpty()) {
3096 switch (layer->getCompositionType(hwcId)) {
3097 case HWC2::Composition::Cursor:
3098 case HWC2::Composition::Device:
3099 case HWC2::Composition::Sideband:
3100 case HWC2::Composition::SolidColor: {
3101 const Layer::State& state(layer->getDrawingState());
3102 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
3103 layer->isOpaque(state) && (state.color.a == 1.0f)
3104 && hasClientComposition) {
3105 // never clear the very first layer since we're
3106 // guaranteed the FB is already cleared
3107 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003108 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003109 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003110 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003111 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003112 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003113 break;
3114 }
3115 default:
3116 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003117 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003118 } else {
3119 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003120 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003121 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003122 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003123
Chia-I Wu6d844112018-06-27 07:17:41 +08003124 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003125 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003126 }
3127
Mathias Agopianf45c5102012-10-24 16:29:17 -07003128 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003129 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003130 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003131}
3132
Fabien Sanglard830b8472016-11-30 16:35:58 -08003133void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3134 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003135 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003136 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003137}
3138
Dan Stoza7d89d062015-04-30 13:29:25 -07003139status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003140 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003141 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003142 const sp<Layer>& lbc,
3143 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003144{
Dan Stoza7d89d062015-04-30 13:29:25 -07003145 // add this layer to the current state list
3146 {
3147 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003148 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003149 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3150 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003151 return NO_MEMORY;
3152 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003153 if (parent == nullptr) {
3154 mCurrentState.layersSortedByZ.add(lbc);
3155 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003156 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003157 ALOGE("addClientLayer called with a removed parent");
3158 return NAME_NOT_FOUND;
3159 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003160 parent->addChild(lbc);
3161 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003162
Yiwei Zhang243b3782018-05-15 17:40:04 -07003163 if (gbc != nullptr) {
3164 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3165 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3166 mMaxGraphicBufferProducerListSize,
3167 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3168 mGraphicBufferProducerList.size(),
3169 mMaxGraphicBufferProducerListSize, mNumLayers);
3170 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003171 mLayersAdded = true;
3172 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003173 }
3174
Mathias Agopian96f08192010-06-02 23:28:45 -07003175 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003176 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003177
Dan Stoza7d89d062015-04-30 13:29:25 -07003178 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003179}
3180
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003181status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003182 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003183 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3184}
Robert Carr7f9b8992017-03-10 11:08:39 -08003185
chaviwca27f252018-02-06 16:46:39 -08003186status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3187 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003188 if (layer->isPendingRemoval()) {
3189 return NO_ERROR;
3190 }
3191
Robert Carr1f0a16a2016-10-24 16:27:39 -07003192 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003193 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003194 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003195 if (topLevelOnly) {
3196 return NO_ERROR;
3197 }
3198
Chia-I Wu98f1c102017-05-30 14:54:08 -07003199 sp<Layer> ancestor = p;
3200 while (ancestor->getParent() != nullptr) {
3201 ancestor = ancestor->getParent();
3202 }
3203 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3204 ALOGE("removeLayer called with a layer whose parent has been removed");
3205 return NAME_NOT_FOUND;
3206 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003207
3208 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003209 } else {
3210 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003211 }
3212
Robert Carr136e2f62017-02-08 17:54:29 -08003213 // As a matter of normal operation, the LayerCleaner will produce a second
3214 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3215 // so we will succeed in promoting it, but it's already been removed
3216 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3217 // otherwise something has gone wrong and we are leaking the layer.
3218 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003219 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3220 layer->getName().string(),
3221 (p != nullptr) ? p->getName().string() : "no-parent");
3222 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003223 } else if (index < 0) {
3224 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003225 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003226
Chia-I Wuc6657022017-08-15 11:18:17 -07003227 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003228 mLayersPendingRemoval.add(layer);
3229 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003230 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003231 setTransactionFlags(eTransactionNeeded);
3232 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003233}
3234
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003235uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003236 return android_atomic_release_load(&mTransactionFlags);
3237}
3238
Mathias Agopian3f844832013-08-07 21:24:32 -07003239uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003240 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3241}
3242
Mathias Agopian3f844832013-08-07 21:24:32 -07003243uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza2713c302018-03-28 17:07:36 -07003244 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3245}
3246
3247uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3248 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003249 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza2713c302018-03-28 17:07:36 -07003250 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003251 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003252 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003253 }
3254 return old;
3255}
3256
chaviwca27f252018-02-06 16:46:39 -08003257bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3258 for (const ComposerState& state : states) {
3259 // Here we need to check that the interface we're given is indeed
3260 // one of our own. A malicious client could give us a nullptr
3261 // IInterface, or one of its own or even one of our own but a
3262 // different type. All these situations would cause us to crash.
3263 if (state.client == nullptr) {
3264 return true;
3265 }
3266
3267 sp<IBinder> binder = IInterface::asBinder(state.client);
3268 if (binder == nullptr) {
3269 return true;
3270 }
3271
3272 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3273 return true;
3274 }
3275 }
3276 return false;
3277}
3278
Mathias Agopian8b33f032012-07-24 20:43:54 -07003279void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003280 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003281 const Vector<DisplayState>& displays,
3282 uint32_t flags)
3283{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003284 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003285 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003286 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003287
chaviwca27f252018-02-06 16:46:39 -08003288 if (containsAnyInvalidClientState(states)) {
3289 return;
3290 }
3291
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003292 if (flags & eAnimation) {
3293 // For window updates that are part of an animation we must wait for
3294 // previous animation "frames" to be handled.
3295 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003296 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003297 if (CC_UNLIKELY(err != NO_ERROR)) {
3298 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003299 // caller after a few seconds.
3300 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3301 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003302 mAnimTransactionPending = false;
3303 break;
3304 }
3305 }
3306 }
3307
chaviwca27f252018-02-06 16:46:39 -08003308 for (const DisplayState& display : displays) {
3309 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003310 }
3311
chaviwca27f252018-02-06 16:46:39 -08003312 for (const ComposerState& state : states) {
3313 transactionFlags |= setClientStateLocked(state);
3314 }
3315
3316 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3317 // as destroyed should only occur after setting all other states. This is to allow for a
3318 // child re-parent to happen before marking its original parent as destroyed (which would
3319 // then mark the child as destroyed).
3320 for (const ComposerState& state : states) {
3321 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003322 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003323
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003324 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3325 // anyway. This can be used as a flush mechanism for previous async transactions.
3326 // Empty animation transaction can be used to simulate back-pressure, so also force a
3327 // transaction for empty animation transactions.
3328 if (transactionFlags == 0 &&
3329 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003330 transactionFlags = eTransactionNeeded;
3331 }
3332
Mathias Agopian386aa982011-11-07 21:58:03 -08003333 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003334 if (mInterceptor->isEnabled()) {
3335 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003336 }
Irvel468051e2016-06-13 16:44:44 -07003337
Mathias Agopian386aa982011-11-07 21:58:03 -08003338 // this triggers the transaction
Dan Stoza2713c302018-03-28 17:07:36 -07003339 const auto start = (flags & eEarlyWakeup)
3340 ? VSyncModulator::TransactionStart::EARLY
3341 : VSyncModulator::TransactionStart::NORMAL;
3342 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003343
3344 // if this is a synchronous transaction, wait for it to take effect
3345 // before returning.
3346 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003347 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003348 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003349 if (flags & eAnimation) {
3350 mAnimTransactionPending = true;
3351 }
3352 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003353 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3354 if (CC_UNLIKELY(err != NO_ERROR)) {
3355 // just in case something goes wrong in SF, return to the
3356 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003357 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3358 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003359 break;
3360 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003361 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003362 }
3363}
3364
Mathias Agopiane57f2922012-08-09 16:29:12 -07003365uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3366{
Jesse Hall9a143922012-10-04 16:29:19 -07003367 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3368 if (dpyIdx < 0)
3369 return 0;
3370
Mathias Agopiane57f2922012-08-09 16:29:12 -07003371 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003372 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003373 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003374 const uint32_t what = s.what;
3375 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003376 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003377 disp.surface = s.surface;
3378 flags |= eDisplayTransactionNeeded;
3379 }
3380 }
3381 if (what & DisplayState::eLayerStackChanged) {
3382 if (disp.layerStack != s.layerStack) {
3383 disp.layerStack = s.layerStack;
3384 flags |= eDisplayTransactionNeeded;
3385 }
3386 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003387 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003388 if (disp.orientation != s.orientation) {
3389 disp.orientation = s.orientation;
3390 flags |= eDisplayTransactionNeeded;
3391 }
3392 if (disp.frame != s.frame) {
3393 disp.frame = s.frame;
3394 flags |= eDisplayTransactionNeeded;
3395 }
3396 if (disp.viewport != s.viewport) {
3397 disp.viewport = s.viewport;
3398 flags |= eDisplayTransactionNeeded;
3399 }
3400 }
Michael Lentine47e45402014-07-18 15:34:25 -07003401 if (what & DisplayState::eDisplaySizeChanged) {
3402 if (disp.width != s.width) {
3403 disp.width = s.width;
3404 flags |= eDisplayTransactionNeeded;
3405 }
3406 if (disp.height != s.height) {
3407 disp.height = s.height;
3408 flags |= eDisplayTransactionNeeded;
3409 }
3410 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003411 }
3412 return flags;
3413}
3414
Robert Carrd4ae7f32018-06-07 16:10:57 -07003415bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3416 IPCThreadState* ipc = IPCThreadState::self();
3417 const int pid = ipc->getCallingPid();
3418 const int uid = ipc->getCallingUid();
3419
3420 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3421 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3422 return false;
3423 }
3424 return true;
3425}
3426
chaviwca27f252018-02-06 16:46:39 -08003427uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3428 const layer_state_t& s = composerState.state;
3429 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3430
Mathias Agopian13127d82013-03-05 17:47:11 -08003431 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003432 if (layer == nullptr) {
3433 return 0;
3434 }
3435
3436 if (layer->isPendingRemoval()) {
3437 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3438 return 0;
3439 }
3440
3441 uint32_t flags = 0;
3442
3443 const uint32_t what = s.what;
3444 bool geometryAppliesWithResize =
3445 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003446
3447 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3448 // pending state will also be deferred.
3449 if (what & layer_state_t::eDeferTransaction) {
3450 layer->pushPendingState();
3451 }
3452
chaviw8b3871a2017-11-01 17:41:01 -07003453 if (what & layer_state_t::ePositionChanged) {
3454 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3455 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003456 }
chaviw8b3871a2017-11-01 17:41:01 -07003457 }
3458 if (what & layer_state_t::eLayerChanged) {
3459 // NOTE: index needs to be calculated before we update the state
3460 const auto& p = layer->getParent();
3461 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003462 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003463 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003464 mCurrentState.layersSortedByZ.removeAt(idx);
3465 mCurrentState.layersSortedByZ.add(layer);
3466 // we need traversal (state changed)
3467 // AND transaction (list changed)
3468 flags |= eTransactionNeeded|eTraversalNeeded;
3469 }
chaviw8b3871a2017-11-01 17:41:01 -07003470 } else {
3471 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003472 flags |= eTransactionNeeded|eTraversalNeeded;
3473 }
3474 }
chaviw8b3871a2017-11-01 17:41:01 -07003475 }
3476 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003477 // NOTE: index needs to be calculated before we update the state
3478 const auto& p = layer->getParent();
3479 if (p == nullptr) {
3480 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3481 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3482 mCurrentState.layersSortedByZ.removeAt(idx);
3483 mCurrentState.layersSortedByZ.add(layer);
3484 // we need traversal (state changed)
3485 // AND transaction (list changed)
3486 flags |= eTransactionNeeded|eTraversalNeeded;
3487 }
3488 } else {
3489 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3490 flags |= eTransactionNeeded|eTraversalNeeded;
3491 }
chaviw8b3871a2017-11-01 17:41:01 -07003492 }
3493 }
3494 if (what & layer_state_t::eSizeChanged) {
3495 if (layer->setSize(s.w, s.h)) {
3496 flags |= eTraversalNeeded;
3497 }
3498 }
3499 if (what & layer_state_t::eAlphaChanged) {
3500 if (layer->setAlpha(s.alpha))
3501 flags |= eTraversalNeeded;
3502 }
3503 if (what & layer_state_t::eColorChanged) {
3504 if (layer->setColor(s.color))
3505 flags |= eTraversalNeeded;
3506 }
3507 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003508 // TODO: b/109894387
3509 //
3510 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3511 // rotation. To see the problem observe that if we have a square parent, and a child
3512 // of the same size, then we rotate the child 45 degrees around it's center, the child
3513 // must now be cropped to a non rectangular 8 sided region.
3514 //
3515 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3516 // private API, and the WindowManager only uses rotation in one case, which is on a top
3517 // level layer in which cropping is not an issue.
3518 //
3519 // However given that abuse of rotation matrices could lead to surfaces extending outside
3520 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3521 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3522 // transformations.
3523 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003524 flags |= eTraversalNeeded;
3525 }
3526 if (what & layer_state_t::eTransparentRegionChanged) {
3527 if (layer->setTransparentRegionHint(s.transparentRegion))
3528 flags |= eTraversalNeeded;
3529 }
3530 if (what & layer_state_t::eFlagsChanged) {
3531 if (layer->setFlags(s.flags, s.mask))
3532 flags |= eTraversalNeeded;
3533 }
3534 if (what & layer_state_t::eCropChanged) {
3535 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3536 flags |= eTraversalNeeded;
3537 }
3538 if (what & layer_state_t::eFinalCropChanged) {
3539 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3540 flags |= eTraversalNeeded;
3541 }
3542 if (what & layer_state_t::eLayerStackChanged) {
3543 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3544 // We only allow setting layer stacks for top level layers,
3545 // everything else inherits layer stack from its parent.
3546 if (layer->hasParent()) {
3547 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3548 layer->getName().string());
3549 } else if (idx < 0) {
3550 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3551 "that also does not appear in the top level layer list. Something"
3552 " has gone wrong.", layer->getName().string());
3553 } else if (layer->setLayerStack(s.layerStack)) {
3554 mCurrentState.layersSortedByZ.removeAt(idx);
3555 mCurrentState.layersSortedByZ.add(layer);
3556 // we need traversal (state changed)
3557 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003558 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003559 }
3560 }
3561 if (what & layer_state_t::eDeferTransaction) {
3562 if (s.barrierHandle != nullptr) {
3563 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3564 } else if (s.barrierGbp != nullptr) {
3565 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3566 if (authenticateSurfaceTextureLocked(gbp)) {
3567 const auto& otherLayer =
3568 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3569 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3570 } else {
3571 ALOGE("Attempt to defer transaction to to an"
3572 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003573 }
3574 }
chaviw8b3871a2017-11-01 17:41:01 -07003575 // We don't trigger a traversal here because if no other state is
3576 // changed, we don't want this to cause any more work
3577 }
3578 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003579 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003580 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003581 if (!hadParent) {
3582 mCurrentState.layersSortedByZ.remove(layer);
3583 }
chaviw8b3871a2017-11-01 17:41:01 -07003584 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003585 }
chaviw8b3871a2017-11-01 17:41:01 -07003586 }
3587 if (what & layer_state_t::eReparentChildren) {
3588 if (layer->reparentChildren(s.reparentHandle)) {
3589 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003590 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003591 }
chaviw8b3871a2017-11-01 17:41:01 -07003592 if (what & layer_state_t::eDetachChildren) {
3593 layer->detachChildren();
3594 }
3595 if (what & layer_state_t::eOverrideScalingModeChanged) {
3596 layer->setOverrideScalingMode(s.overrideScalingMode);
3597 // We don't trigger a traversal here because if no other state is
3598 // changed, we don't want this to cause any more work
3599 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003600 return flags;
3601}
3602
chaviwca27f252018-02-06 16:46:39 -08003603void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3604 const layer_state_t& state = composerState.state;
3605 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3606
3607 sp<Layer> layer(client->getLayerUser(state.surface));
3608 if (layer == nullptr) {
3609 return;
3610 }
3611
3612 if (layer->isPendingRemoval()) {
3613 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3614 return;
3615 }
3616
3617 if (state.what & layer_state_t::eDestroySurface) {
3618 removeLayerLocked(mStateLock, layer);
3619 }
3620}
3621
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003622status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003623 const String8& name,
3624 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003625 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliuccd34842018-03-14 12:26:23 -07003626 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003627 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003628{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003629 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003630 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003631 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003632 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003633 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003634
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003635 status_t result = NO_ERROR;
3636
3637 sp<Layer> layer;
3638
Cody Northropbc755282017-03-31 12:00:08 -06003639 String8 uniqueName = getUniqueLayerName(name);
3640
Mathias Agopian3165cc22012-08-08 19:42:09 -07003641 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3642 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003643 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003644 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003645 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003646
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003647 break;
chaviw13fdc492017-06-27 12:40:18 -07003648 case ISurfaceComposerClient::eFXSurfaceColor:
3649 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003650 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003651 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003652 break;
3653 default:
3654 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003655 break;
3656 }
3657
Dan Stoza7d89d062015-04-30 13:29:25 -07003658 if (result != NO_ERROR) {
3659 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003660 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003661
Chia-I Wuab0c3192017-08-01 11:29:00 -07003662 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3663 // TODO b/64227542
3664 if (windowType == 441731) {
3665 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3666 layer->setPrimaryDisplayOnly();
3667 }
3668
Albert Chaulk479c60c2017-01-27 14:21:34 -05003669 layer->setInfo(windowType, ownerUid);
3670
Robert Carr1f0a16a2016-10-24 16:27:39 -07003671 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003672 if (result != NO_ERROR) {
3673 return result;
3674 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003675 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003676
3677 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003678 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003679}
3680
Cody Northropbc755282017-03-31 12:00:08 -06003681String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3682{
3683 bool matchFound = true;
3684 uint32_t dupeCounter = 0;
3685
3686 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3687 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3688
Dan Stoza9fdb7e02018-06-21 12:10:12 -07003689 // Grab the state lock since we're accessing mCurrentState
3690 Mutex::Autolock lock(mStateLock);
3691
Cody Northropbc755282017-03-31 12:00:08 -06003692 // Loop over layers until we're sure there is no matching name
3693 while (matchFound) {
3694 matchFound = false;
Dan Stoza9fdb7e02018-06-21 12:10:12 -07003695 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003696 if (layer->getName() == uniqueName) {
3697 matchFound = true;
3698 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3699 }
3700 });
3701 }
3702
3703 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3704
3705 return uniqueName;
3706}
3707
David Sodman0c69cad2017-08-21 12:12:51 -07003708status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003709 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3710 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003711{
3712 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003713 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003714 case PIXEL_FORMAT_TRANSPARENT:
3715 case PIXEL_FORMAT_TRANSLUCENT:
3716 format = PIXEL_FORMAT_RGBA_8888;
3717 break;
3718 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003719 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003720 break;
3721 }
3722
David Sodman0c69cad2017-08-21 12:12:51 -07003723 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3724 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003725 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003726 *handle = layer->getHandle();
3727 *gbp = layer->getProducer();
3728 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003729 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003730
David Sodman0c69cad2017-08-21 12:12:51 -07003731 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003732 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003733}
3734
chaviw13fdc492017-06-27 12:40:18 -07003735status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003736 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003737 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003738{
chaviw13fdc492017-06-27 12:40:18 -07003739 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003740 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003741 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003742}
3743
Mathias Agopianac9fa422013-02-11 16:40:36 -08003744status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003745{
Robert Carr9524cb32017-02-13 11:32:32 -08003746 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003747 status_t err = NO_ERROR;
3748 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003749 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003750 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003751 err = removeLayer(l);
3752 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3753 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003754 }
3755 return err;
3756}
3757
Mathias Agopian13127d82013-03-05 17:47:11 -08003758status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003759{
Mathias Agopian67106042013-03-14 19:18:13 -07003760 // called by ~LayerCleaner() when all references to the IBinder (handle)
3761 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003762 sp<Layer> l = layer.promote();
3763 if (l == nullptr) {
3764 // The layer has already been removed, carry on
3765 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003766 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003767 // If we have a parent, then we can continue to live as long as it does.
3768 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003769}
3770
Mathias Agopianb60314a2012-04-10 22:09:54 -07003771// ---------------------------------------------------------------------------
3772
Andy McFadden13a082e2012-08-24 10:16:42 -07003773void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003774 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003775 Vector<ComposerState> state;
3776 Vector<DisplayState> displays;
3777 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003778 d.what = DisplayState::eDisplayProjectionChanged |
3779 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003780 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003781 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003782 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003783 d.frame.makeInvalid();
3784 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003785 d.width = 0;
3786 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003787 displays.add(d);
3788 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003789 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3790 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003791
David Sodman105b7dc2017-11-04 20:28:14 -07003792 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003793 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003794 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003795
Brian Andersond0010582017-03-07 13:20:31 -08003796 // Use phase of 0 since phase is not known.
3797 // Use latency of 0, which will snap to the ideal latency.
3798 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003799}
3800
3801void SurfaceFlinger::initializeDisplays() {
3802 class MessageScreenInitialized : public MessageBase {
3803 SurfaceFlinger* flinger;
3804 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003805 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003806 virtual bool handler() {
3807 flinger->onInitializeDisplays();
3808 return true;
3809 }
3810 };
3811 sp<MessageBase> msg = new MessageScreenInitialized(this);
3812 postMessageAsync(msg); // we may be called from main thread, use async message
3813}
3814
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003815void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003816 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003817 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3818 this);
3819 int32_t type = hw->getDisplayType();
3820 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003821
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003822 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003823 return;
3824 }
3825
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003826 hw->setPowerMode(mode);
3827 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3828 ALOGW("Trying to set power mode for virtual display");
3829 return;
3830 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003831
Lloyd Pique4d234852018-01-22 17:21:36 -08003832 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003833 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003834 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3835 if (idx < 0) {
3836 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3837 return;
3838 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003839 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003840 }
3841
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003842 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003843 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003844 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003845 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3846 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003847 // FIXME: eventthread only knows about the main display right now
3848 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003849 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003850 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003851
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003852 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003853 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003854 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003855
3856 struct sched_param param = {0};
3857 param.sched_priority = 1;
3858 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3859 ALOGW("Couldn't set SCHED_FIFO on display on");
3860 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003861 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003862 // Turn off the display
3863 struct sched_param param = {0};
3864 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3865 ALOGW("Couldn't set SCHED_OTHER on display off");
3866 }
3867
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003868 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3869 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003870 disableHardwareVsync(true); // also cancels any in-progress resync
3871
Mathias Agopiancde87a32012-09-13 14:09:01 -07003872 // FIXME: eventthread only knows about the main display right now
3873 mEventThread->onScreenReleased();
3874 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003875
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003876 getHwComposer().setPowerMode(type, mode);
3877 mVisibleRegionsDirty = true;
3878 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003879 } else if (mode == HWC_POWER_MODE_DOZE ||
3880 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003881 // Update display while dozing
3882 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003883 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3884 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003885 // FIXME: eventthread only knows about the main display right now
3886 mEventThread->onScreenAcquired();
3887 resyncToHardwareVsync(true);
3888 }
3889 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3890 // Leave display going to doze
3891 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3892 disableHardwareVsync(true); // also cancels any in-progress resync
3893 // FIXME: eventthread only knows about the main display right now
3894 mEventThread->onScreenReleased();
3895 }
3896 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003897 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003898 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003899 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003900 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003901 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003902}
3903
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003904void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3905 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003906 SurfaceFlinger& mFlinger;
3907 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003908 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003909 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003910 MessageSetPowerMode(SurfaceFlinger& flinger,
3911 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3912 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003913 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003914 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003915 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003916 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003917 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003918 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003919 ALOGW("Attempt to set power mode = %d for virtual display",
3920 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003921 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003922 mFlinger.setPowerModeInternal(
3923 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003924 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003925 return true;
3926 }
3927 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003928 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003929 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003930}
3931
3932// ---------------------------------------------------------------------------
3933
Lloyd Pique755e3192018-01-31 16:46:15 -08003934status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3935 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003936 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003937
Mathias Agopianbd115332013-04-18 16:41:04 -07003938 IPCThreadState* ipc = IPCThreadState::self();
3939 const int pid = ipc->getCallingPid();
3940 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003941
Mathias Agopianbd115332013-04-18 16:41:04 -07003942 if ((uid != AID_SHELL) &&
3943 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003944 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003945 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003946 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003947 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003948 // (this would indicate SF is stuck, but we want to be able to
3949 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003950 status_t err = mStateLock.timedLock(s2ns(1));
3951 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003952 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003953 result.appendFormat(
3954 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3955 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003956 }
3957
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003958 bool dumpAll = true;
3959 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003960 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003961
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003962 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003963 if ((index < numArgs) &&
3964 (args[index] == String16("--list"))) {
3965 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003966 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003967 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003968 }
3969
3970 if ((index < numArgs) &&
3971 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003972 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003973 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003974 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003975 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003976
3977 if ((index < numArgs) &&
3978 (args[index] == String16("--latency-clear"))) {
3979 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003980 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003981 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003982 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003983
3984 if ((index < numArgs) &&
3985 (args[index] == String16("--dispsync"))) {
3986 index++;
3987 mPrimaryDispSync.dump(result);
3988 dumpAll = false;
3989 }
Dan Stozab90cf072015-03-05 11:05:59 -08003990
3991 if ((index < numArgs) &&
3992 (args[index] == String16("--static-screen"))) {
3993 index++;
3994 dumpStaticScreenStats(result);
3995 dumpAll = false;
3996 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003997
3998 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003999 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004000 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004001 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004002 dumpAll = false;
4003 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004004
4005 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4006 index++;
4007 dumpWideColorInfo(result);
4008 dumpAll = false;
4009 }
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004010
4011 if ((index < numArgs) &&
4012 (args[index] == String16("--enable-layer-stats"))) {
4013 index++;
4014 mLayerStats.enable();
4015 dumpAll = false;
4016 }
4017
4018 if ((index < numArgs) &&
4019 (args[index] == String16("--disable-layer-stats"))) {
4020 index++;
4021 mLayerStats.disable();
4022 dumpAll = false;
4023 }
4024
4025 if ((index < numArgs) &&
4026 (args[index] == String16("--clear-layer-stats"))) {
4027 index++;
4028 mLayerStats.clear();
4029 dumpAll = false;
4030 }
4031
4032 if ((index < numArgs) &&
4033 (args[index] == String16("--dump-layer-stats"))) {
4034 index++;
4035 mLayerStats.dump(result);
4036 dumpAll = false;
4037 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07004038
4039 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4040 index++;
4041 mTimeStats.parseArgs(asProto, args, index, result);
4042 dumpAll = false;
4043 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004044 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004045
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004046 if (dumpAll) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07004047 if (asProto) {
4048 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4049 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4050 } else {
4051 dumpAllLocked(args, index, result);
4052 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004053 }
4054
Mathias Agopian9795c422009-08-26 16:36:26 -07004055 if (locked) {
4056 mStateLock.unlock();
4057 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004058 }
4059 write(fd, result.string(), result.size());
4060 return NO_ERROR;
4061}
4062
Dan Stozac7014012014-02-14 15:03:43 -08004063void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4064 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004065{
Robert Carr2047fae2016-11-28 14:09:09 -08004066 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004067 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004068 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004069}
4070
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004071void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004072 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004073{
4074 String8 name;
4075 if (index < args.size()) {
4076 name = String8(args[index]);
4077 index++;
4078 }
4079
David Sodman105b7dc2017-11-04 20:28:14 -07004080 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004081 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08004082 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004083
4084 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004085 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004086 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004087 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004088 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004089 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004090 }
Robert Carr2047fae2016-11-28 14:09:09 -08004091 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004092 }
4093}
4094
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004095void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004096 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004097{
4098 String8 name;
4099 if (index < args.size()) {
4100 name = String8(args[index]);
4101 index++;
4102 }
4103
Robert Carr2047fae2016-11-28 14:09:09 -08004104 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004105 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004106 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004107 }
Robert Carr2047fae2016-11-28 14:09:09 -08004108 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004109
Svetoslavd85084b2014-03-20 10:28:31 -07004110 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004111}
4112
Jamie Gennis6547ff42013-07-16 20:12:42 -07004113// This should only be called from the main thread. Otherwise it would need
4114// the lock and should use mCurrentState rather than mDrawingState.
4115void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004116 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004117 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004118 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004119
4120 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4121}
4122
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004123void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004124{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004125 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004126
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004127 if (isLayerTripleBufferingDisabled())
4128 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004129
4130 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004131 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004132 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004133 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004134 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4135 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004136 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004137}
4138
Dan Stozab90cf072015-03-05 11:05:59 -08004139void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4140{
4141 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004142 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4143 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004144 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004145 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004146 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4147 b + 1, bucketTimeSec, percent);
4148 }
David Sodman4a36e932017-11-07 14:29:47 -08004149 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004150 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004151 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004152 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004153 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004154}
4155
Dan Stozae77c7662016-05-13 11:37:28 -07004156void SurfaceFlinger::recordBufferingStats(const char* layerName,
4157 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004158 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4159 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004160 for (const auto& segment : history) {
4161 if (!segment.usedThirdBuffer) {
4162 stats.twoBufferTime += segment.totalTime;
4163 }
4164 if (segment.occupancyAverage < 1.0f) {
4165 stats.doubleBufferedTime += segment.totalTime;
4166 } else if (segment.occupancyAverage < 2.0f) {
4167 stats.tripleBufferedTime += segment.totalTime;
4168 }
4169 ++stats.numSegments;
4170 stats.totalTime += segment.totalTime;
4171 }
4172}
4173
Brian Andersond6927fb2016-07-23 23:37:30 -07004174void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4175 result.appendFormat("Layer frame timestamps:\n");
4176
4177 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4178 const size_t count = currentLayers.size();
4179 for (size_t i=0 ; i<count ; i++) {
4180 currentLayers[i]->dumpFrameEvents(result);
4181 }
4182}
4183
Dan Stozae77c7662016-05-13 11:37:28 -07004184void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4185 result.append("Buffering stats:\n");
4186 result.append(" [Layer name] <Active time> <Two buffer> "
4187 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004188 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004189 typedef std::tuple<std::string, float, float, float> BufferTuple;
4190 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004191 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004192 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004193 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004194 if (stats.numSegments == 0) {
4195 continue;
4196 }
4197 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4198 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4199 stats.totalTime;
4200 float doubleBufferRatio = static_cast<float>(
4201 stats.doubleBufferedTime) / stats.totalTime;
4202 float tripleBufferRatio = static_cast<float>(
4203 stats.tripleBufferedTime) / stats.totalTime;
4204 sorted.insert({activeTime, {name, twoBufferRatio,
4205 doubleBufferRatio, tripleBufferRatio}});
4206 }
4207 for (const auto& sortedPair : sorted) {
4208 float activeTime = sortedPair.first;
4209 const BufferTuple& values = sortedPair.second;
4210 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4211 std::get<0>(values).c_str(), activeTime,
4212 std::get<1>(values), std::get<2>(values),
4213 std::get<3>(values));
4214 }
4215 result.append("\n");
4216}
4217
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004218void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4219 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004220 result.appendFormat("DisplayColorSetting: %s\n",
4221 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004222
4223 // TODO: print out if wide-color mode is active or not
4224
4225 for (size_t d = 0; d < mDisplays.size(); d++) {
4226 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4227 int32_t hwcId = displayDevice->getHwcDisplayId();
4228 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4229 continue;
4230 }
4231
4232 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004233 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004234 for (auto&& mode : modes) {
4235 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4236 }
4237
Peiyong Lina52f0292018-03-14 17:26:31 -07004238 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004239 result.appendFormat(" Current color mode: %s (%d)\n",
4240 decodeColorMode(currentMode).c_str(), currentMode);
4241 }
4242 result.append("\n");
4243}
4244
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004245LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004246 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004247 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4248 const State& state = useDrawing ? mDrawingState : mCurrentState;
4249 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004250 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004251 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004252 });
4253
4254 return layersProto;
4255}
4256
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004257LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4258 LayersProto layersProto;
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004259 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004260
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004261 SizeProto* resolution = layersProto.mutable_resolution();
4262 resolution->set_w(displayDevice->getWidth());
4263 resolution->set_h(displayDevice->getHeight());
4264
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004265 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4266 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4267 layersProto.set_global_transform(
4268 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4269
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004270 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004271 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004272 LayerProto* layerProto = layersProto.add_layers();
4273 layer->writeToProto(layerProto, hwcId);
4274 }
4275 });
4276
4277 return layersProto;
4278}
4279
Mathias Agopian74d211a2013-04-22 16:55:35 +02004280void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4281 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004282{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004283 bool colorize = false;
4284 if (index < args.size()
4285 && (args[index] == String16("--color"))) {
4286 colorize = true;
4287 index++;
4288 }
4289
4290 Colorizer colorizer(colorize);
4291
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004292 // figure out if we're stuck somewhere
4293 const nsecs_t now = systemTime();
4294 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4295 const nsecs_t inTransaction(mDebugInTransaction);
4296 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4297 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4298
4299 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004300 * Dump library configuration.
4301 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004302
4303 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004304 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004305 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004306 appendSfConfigString(result);
4307 appendUiConfigString(result);
4308 appendGuiConfigString(result);
4309 result.append("\n");
4310
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004311 result.append("\nWide-Color information:\n");
4312 dumpWideColorInfo(result);
4313
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004314 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004315 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004316 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004317 result.append(SyncFeatures::getInstance().toString());
4318 result.append("\n");
4319
David Sodman105b7dc2017-11-04 20:28:14 -07004320 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004321
Andy McFadden41d67d72014-04-25 16:58:34 -07004322 colorizer.bold(result);
4323 result.append("DispSync configuration: ");
4324 colorizer.reset(result);
Jorim Jaggie203e042018-06-19 15:57:08 +02004325 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4326 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
4327 result.appendFormat(
4328 "app phase %" PRId64 " ns, "
4329 "sf phase %" PRId64 " ns, "
4330 "early app phase %" PRId64 " ns, "
4331 "early sf phase %" PRId64 " ns, "
4332 "early app gl phase %" PRId64 " ns, "
4333 "early sf gl phase %" PRId64 " ns, "
4334 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4335 vsyncPhaseOffsetNs,
4336 sfVsyncPhaseOffsetNs,
4337 appEarlyOffset,
4338 sfEarlyOffset,
4339 appEarlyGlOffset,
4340 sfEarlyOffset,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004341 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004342 result.append("\n");
4343
Dan Stozab90cf072015-03-05 11:05:59 -08004344 // Dump static screen stats
4345 result.append("\n");
4346 dumpStaticScreenStats(result);
4347 result.append("\n");
4348
Dan Stozae77c7662016-05-13 11:37:28 -07004349 dumpBufferingStats(result);
4350
Andy McFadden4803b742012-09-24 19:07:20 -07004351 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004352 * Dump the visible layer list
4353 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004354 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004355 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004356 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4357 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004358 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004359
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004360 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004361 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004362 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004363 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004364
4365 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004366 * Dump Display state
4367 */
4368
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004369 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004370 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004371 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004372 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4373 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004374 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004375 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004376 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004377
4378 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004379 * Dump SurfaceFlinger global state
4380 */
4381
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004382 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004383 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004384 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004385
Mathias Agopian888c8222012-08-04 21:10:38 -07004386 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004387 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004388
David Sodmanbc815282017-11-05 18:57:52 -08004389 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004390
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004391 if (hw) {
4392 hw->undefinedRegion.dump(result, "undefinedRegion");
4393 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4394 hw->getOrientation(), hw->isDisplayOn());
4395 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004396 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004397 " last eglSwapBuffers() time: %f us\n"
4398 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004399 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004400 " refresh-rate : %f fps\n"
4401 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004402 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004403 " gpu_to_cpu_unsupported : %d\n"
4404 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004405 mLastSwapBufferTime/1000.0,
4406 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004407 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004408 1e9 / activeConfig->getVsyncPeriod(),
4409 activeConfig->getDpiX(),
4410 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004411 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004412
Mathias Agopian74d211a2013-04-22 16:55:35 +02004413 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004414 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004415
Mathias Agopian74d211a2013-04-22 16:55:35 +02004416 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004417 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004418
4419 /*
4420 * VSYNC state
4421 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004422 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004423 result.append("\n");
4424
4425 /*
4426 * HWC layer minidump
4427 */
4428 for (size_t d = 0; d < mDisplays.size(); d++) {
4429 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4430 int32_t hwcId = displayDevice->getHwcDisplayId();
4431 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4432 continue;
4433 }
4434
4435 result.appendFormat("Display %d HWC layers:\n", hwcId);
4436 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004437 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004438 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004439 });
Dan Stozae22aec72016-08-01 13:20:59 -07004440 result.append("\n");
4441 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004442
4443 /*
4444 * Dump HWComposer state
4445 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004446 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004447 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004448 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004449 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004450 result.appendFormat(" h/w composer %s\n",
4451 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004452 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004453
4454 /*
4455 * Dump gralloc state
4456 */
4457 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4458 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004459
4460 /*
4461 * Dump VrFlinger state if in use.
4462 */
4463 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4464 result.append("VrFlinger state:\n");
4465 result.append(mVrFlinger->Dump().c_str());
4466 result.append("\n");
4467 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004468}
4469
Mathias Agopian13127d82013-03-05 17:47:11 -08004470const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004471SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004472 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004473 wp<IBinder> dpy;
4474 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4475 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4476 dpy = mDisplays.keyAt(i);
4477 break;
4478 }
4479 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004480 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004481 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4482 // Just use the primary display so we have something to return
4483 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4484 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004485 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004486}
4487
Keun young Park63f165f2012-08-31 10:53:36 -07004488bool SurfaceFlinger::startDdmConnection()
4489{
4490 void* libddmconnection_dso =
4491 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4492 if (!libddmconnection_dso) {
4493 return false;
4494 }
4495 void (*DdmConnection_start)(const char* name);
4496 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004497 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004498 if (!DdmConnection_start) {
4499 dlclose(libddmconnection_dso);
4500 return false;
4501 }
4502 (*DdmConnection_start)(getServiceName());
4503 return true;
4504}
4505
Chia-I Wu28f320b2018-05-03 11:02:56 -07004506void SurfaceFlinger::updateColorMatrixLocked() {
4507 mat4 colorMatrix;
4508 if (mGlobalSaturationFactor != 1.0f) {
4509 // Rec.709 luma coefficients
4510 float3 luminance{0.213f, 0.715f, 0.072f};
4511 luminance *= 1.0f - mGlobalSaturationFactor;
4512 mat4 saturationMatrix = mat4(
4513 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4514 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4515 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4516 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4517 );
4518 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4519 } else {
4520 colorMatrix = mClientColorMatrix * mDaltonizer();
4521 }
4522
4523 if (mCurrentState.colorMatrix != colorMatrix) {
4524 mCurrentState.colorMatrix = colorMatrix;
4525 mCurrentState.colorMatrixChanged = true;
4526 setTransactionFlags(eTransactionNeeded);
4527 }
4528}
4529
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004530status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004531 switch (code) {
4532 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004533 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004534 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004535 case CLEAR_ANIMATION_FRAME_STATS:
4536 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004537 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004538 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004539 case ENABLE_VSYNC_INJECTIONS:
4540 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004541 {
4542 // codes that require permission check
Robert Carrd4ae7f32018-06-07 16:10:57 -07004543 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4544 IPCThreadState* ipc = IPCThreadState::self();
4545 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4546 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004547 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004548 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004549 break;
4550 }
Robert Carr1db73f62016-12-21 12:58:51 -08004551 /*
4552 * Calling setTransactionState is safe, because you need to have been
4553 * granted a reference to Client* and Handle* to do anything with it.
4554 *
4555 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4556 */
4557 case SET_TRANSACTION_STATE:
4558 case CREATE_SCOPED_CONNECTION:
4559 {
4560 return OK;
4561 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004562 case CAPTURE_SCREEN:
4563 {
4564 // codes that require permission check
4565 IPCThreadState* ipc = IPCThreadState::self();
4566 const int pid = ipc->getCallingPid();
4567 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004568 if ((uid != AID_GRAPHICS) &&
4569 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004570 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004571 return PERMISSION_DENIED;
4572 }
4573 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004574 }
chaviwa76b2712017-09-20 12:02:26 -07004575 case CAPTURE_LAYERS: {
4576 IPCThreadState* ipc = IPCThreadState::self();
4577 const int pid = ipc->getCallingPid();
4578 const int uid = ipc->getCallingUid();
4579 if ((uid != AID_GRAPHICS) &&
4580 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4581 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4582 return PERMISSION_DENIED;
4583 }
4584 break;
4585 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004586 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004587 return OK;
4588}
4589
4590status_t SurfaceFlinger::onTransact(
4591 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4592{
4593 status_t credentialCheck = CheckTransactCodeCredentials(code);
4594 if (credentialCheck != OK) {
4595 return credentialCheck;
4596 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004597
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004598 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4599 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004600 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004601 IPCThreadState* ipc = IPCThreadState::self();
4602 const int uid = ipc->getCallingUid();
4603 if (CC_UNLIKELY(uid != AID_SYSTEM
4604 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004605 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004606 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004607 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004608 return PERMISSION_DENIED;
4609 }
4610 int n;
4611 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004612 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004613 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004614 return NO_ERROR;
4615 case 1002: // SHOW_UPDATES
4616 n = data.readInt32();
4617 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004618 invalidateHwcGeometry();
4619 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004620 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004621 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004622 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004623 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004624 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004625 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004626 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004627 setTransactionFlags(
4628 eTransactionNeeded|
4629 eDisplayTransactionNeeded|
4630 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004631 return NO_ERROR;
4632 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004633 case 1006:{ // send empty update
4634 signalRefresh();
4635 return NO_ERROR;
4636 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004637 case 1008: // toggle use of hw composer
4638 n = data.readInt32();
4639 mDebugDisableHWC = n ? 1 : 0;
4640 invalidateHwcGeometry();
4641 repaintEverything();
4642 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004643 case 1009: // toggle use of transform hint
4644 n = data.readInt32();
4645 mDebugDisableTransformHint = n ? 1 : 0;
4646 invalidateHwcGeometry();
4647 repaintEverything();
4648 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004649 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004650 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004651 reply->writeInt32(0);
4652 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004653 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004654 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004655 return NO_ERROR;
4656 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004657 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004658 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004659 return NO_ERROR;
4660 }
4661 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004662 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004663 // daltonize
4664 n = data.readInt32();
4665 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004666 case 1:
4667 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4668 break;
4669 case 2:
4670 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4671 break;
4672 case 3:
4673 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4674 break;
4675 default:
4676 mDaltonizer.setType(ColorBlindnessType::None);
4677 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004678 }
4679 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004680 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004681 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004682 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004683 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004684
4685 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004686 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004687 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004688 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004689 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004690 // apply a color matrix
4691 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004692 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004693 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004694 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004695 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004696 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004697 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004698 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004699 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004700 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004701 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004702
4703 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4704 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004705 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004706 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4707 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4708 }
4709
Chia-I Wu28f320b2018-05-03 11:02:56 -07004710 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004711 return NO_ERROR;
4712 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004713 // This is an experimental interface
4714 // Needs to be shifted to proper binder interface when we productize
4715 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004716 n = data.readInt32();
4717 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004718 return NO_ERROR;
4719 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004720 case 1017: {
4721 n = data.readInt32();
4722 mForceFullDamage = static_cast<bool>(n);
4723 return NO_ERROR;
4724 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004725 case 1018: { // Modify Choreographer's phase offset
4726 n = data.readInt32();
4727 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4728 return NO_ERROR;
4729 }
4730 case 1019: { // Modify SurfaceFlinger's phase offset
4731 n = data.readInt32();
4732 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4733 return NO_ERROR;
4734 }
Irvel468051e2016-06-13 16:44:44 -07004735 case 1020: { // Layer updates interceptor
4736 n = data.readInt32();
4737 if (n) {
4738 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004739 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004740 }
4741 else{
4742 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004743 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004744 }
4745 return NO_ERROR;
4746 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004747 case 1021: { // Disable HWC virtual displays
4748 n = data.readInt32();
4749 mUseHwcVirtualDisplays = !n;
4750 return NO_ERROR;
4751 }
Romain Guy0147a172017-06-01 13:53:56 -07004752 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004753 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004754 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004755
Chia-I Wu28f320b2018-05-03 11:02:56 -07004756 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004757 return NO_ERROR;
4758 }
Romain Guy54f154a2017-10-24 21:40:32 +01004759 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004760 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004761 invalidateHwcGeometry();
4762 repaintEverything();
4763 return NO_ERROR;
4764 }
4765 case 1024: { // Is wide color gamut rendering/color management supported?
4766 reply->writeBool(hasWideColorDisplay);
4767 return NO_ERROR;
4768 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004769 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004770 n = data.readInt32();
4771 if (n) {
4772 ALOGV("LayerTracing enabled");
4773 mTracing.enable();
4774 doTracing("tracing.enable");
4775 reply->writeInt32(NO_ERROR);
4776 } else {
4777 ALOGV("LayerTracing disabled");
4778 status_t err = mTracing.disable();
4779 reply->writeInt32(err);
4780 }
4781 return NO_ERROR;
4782 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004783 case 1026: { // Get layer tracing status
4784 reply->writeBool(mTracing.isEnabled());
4785 return NO_ERROR;
4786 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004787 // Is a DisplayColorSetting supported?
4788 case 1027: {
Chia-I Wu0d711262018-05-21 15:19:35 -07004789 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
4790 if (!hw) {
4791 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004792 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004793
4794 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4795 switch (setting) {
4796 case DisplayColorSetting::MANAGED:
4797 reply->writeBool(hasWideColorDisplay);
4798 break;
4799 case DisplayColorSetting::UNMANAGED:
4800 reply->writeBool(true);
4801 break;
4802 case DisplayColorSetting::ENHANCED:
4803 reply->writeBool(hw->hasRenderIntent(RenderIntent::ENHANCE));
4804 break;
4805 default: // vendor display color setting
4806 reply->writeBool(hw->hasRenderIntent(static_cast<RenderIntent>(setting)));
4807 break;
4808 }
4809 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004810 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004811 }
4812 }
4813 return err;
4814}
4815
Steven Thomas6d8110b2017-08-31 18:24:21 -07004816void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004817 android_atomic_or(1, &mRepaintEverything);
4818 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004819}
4820
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004821// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4822class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004823public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004824 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4825 ~WindowDisconnector() {
4826 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004827 }
4828
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004829private:
4830 ANativeWindow* mWindow;
4831 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004832};
4833
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004834status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4835 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4836 int32_t minLayerZ, int32_t maxLayerZ,
4837 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004838 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004839 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004840
chaviwa76b2712017-09-20 12:02:26 -07004841 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4842
4843 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004844 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4845
Yiwei Zhangf4e02872018-08-20 16:42:23 -07004846 const Rect& dispScissor = device->getScissor();
4847 if (!dispScissor.isEmpty()) {
4848 sourceCrop.set(dispScissor);
4849 // adb shell screencap will default reqWidth and reqHeight to zeros.
4850 if (reqWidth == 0 || reqHeight == 0) {
Yiwei Zhang9ad73bc2018-08-21 22:11:37 -07004851 reqWidth = uint32_t(device->getViewport().width());
4852 reqHeight = uint32_t(device->getViewport().height());
Yiwei Zhangf4e02872018-08-20 16:42:23 -07004853 }
4854 }
4855
chaviwa76b2712017-09-20 12:02:26 -07004856 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4857
4858 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4859 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004860 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004861}
4862
4863status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004864 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004865 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004866 ATRACE_CALL();
4867
4868 class LayerRenderArea : public RenderArea {
4869 public:
Robert Carr578038f2018-03-09 12:25:24 -08004870 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4871 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004872 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004873 mLayer(layer),
4874 mCrop(crop),
4875 mFlinger(flinger),
4876 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004877 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004878 Rect getBounds() const override {
4879 const Layer::State& layerState(mLayer->getDrawingState());
4880 return Rect(layerState.active.w, layerState.active.h);
4881 }
4882 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4883 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4884 bool isSecure() const override { return false; }
4885 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004886 Rect getSourceCrop() const override {
4887 if (mCrop.isEmpty()) {
4888 return getBounds();
4889 } else {
4890 return mCrop;
4891 }
4892 }
Robert Carr578038f2018-03-09 12:25:24 -08004893 class ReparentForDrawing {
4894 public:
4895 const sp<Layer>& oldParent;
4896 const sp<Layer>& newParent;
4897
4898 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4899 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004900 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004901 }
Robert Carr15eae092018-03-23 13:43:53 -07004902 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004903 };
4904
4905 void render(std::function<void()> drawLayers) override {
4906 if (!mChildrenOnly) {
4907 mTransform = mLayer->getTransform().inverse();
4908 drawLayers();
4909 } else {
4910 Rect bounds = getBounds();
4911 screenshotParentLayer =
4912 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4913 bounds.getWidth(), bounds.getHeight(), 0);
4914
4915 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4916 drawLayers();
4917 }
4918 }
chaviwa76b2712017-09-20 12:02:26 -07004919
chaviwa76b2712017-09-20 12:02:26 -07004920 private:
chaviw7206d492017-11-10 16:16:12 -08004921 const sp<Layer> mLayer;
4922 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004923
4924 // In the "childrenOnly" case we reparent the children to a screenshot
4925 // layer which has no properties set and which does not draw.
4926 sp<ContainerLayer> screenshotParentLayer;
4927 Transform mTransform;
4928
4929 SurfaceFlinger* mFlinger;
4930 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004931 };
4932
4933 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4934 auto parent = layerHandle->owner.promote();
4935
chaviw7206d492017-11-10 16:16:12 -08004936 if (parent == nullptr || parent->isPendingRemoval()) {
4937 ALOGE("captureLayers called with a removed parent");
4938 return NAME_NOT_FOUND;
4939 }
4940
Robert Carr578038f2018-03-09 12:25:24 -08004941 const int uid = IPCThreadState::self()->getCallingUid();
4942 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4943 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4944 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4945 return PERMISSION_DENIED;
4946 }
4947
chaviw7206d492017-11-10 16:16:12 -08004948 Rect crop(sourceCrop);
4949 if (sourceCrop.width() <= 0) {
4950 crop.left = 0;
4951 crop.right = parent->getCurrentState().active.w;
4952 }
4953
4954 if (sourceCrop.height() <= 0) {
4955 crop.top = 0;
4956 crop.bottom = parent->getCurrentState().active.h;
4957 }
4958
4959 int32_t reqWidth = crop.width() * frameScale;
4960 int32_t reqHeight = crop.height() * frameScale;
4961
Robert Carr578038f2018-03-09 12:25:24 -08004962 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004963
Robert Carr578038f2018-03-09 12:25:24 -08004964 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004965 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4966 if (!layer->isVisible()) {
4967 return;
Robert Carr578038f2018-03-09 12:25:24 -08004968 } else if (childrenOnly && layer == parent.get()) {
4969 return;
chaviwa76b2712017-09-20 12:02:26 -07004970 }
4971 visitor(layer);
4972 });
4973 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004974 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004975}
4976
4977status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4978 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004979 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004980 bool useIdentityTransform) {
4981 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004982
Iris Chang7501ed62018-04-30 14:45:42 +08004983 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004984
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004985 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4986 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4987 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4988 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004989
4990 // This mutex protects syncFd and captureResult for communication of the return values from the
4991 // main thread back to this Binder thread
4992 std::mutex captureMutex;
4993 std::condition_variable captureCondition;
4994 std::unique_lock<std::mutex> captureLock(captureMutex);
4995 int syncFd = -1;
4996 std::optional<status_t> captureResult;
4997
Robert Carr03480e22018-01-04 16:02:06 -08004998 const int uid = IPCThreadState::self()->getCallingUid();
4999 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5000
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005001 sp<LambdaMessage> message = new LambdaMessage([&]() {
5002 // If there is a refresh pending, bug out early and tell the binder thread to try again
5003 // after the refresh.
5004 if (mRefreshPending) {
5005 ATRACE_NAME("Skipping screenshot for now");
5006 std::unique_lock<std::mutex> captureLock(captureMutex);
5007 captureResult = std::make_optional<status_t>(EAGAIN);
5008 captureCondition.notify_one();
5009 return;
5010 }
5011
5012 status_t result = NO_ERROR;
5013 int fd = -1;
5014 {
5015 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08005016 renderArea.render([&]() {
5017 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5018 useIdentityTransform, forSystem, &fd);
5019 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005020 }
5021
5022 {
5023 std::unique_lock<std::mutex> captureLock(captureMutex);
5024 syncFd = fd;
5025 captureResult = std::make_optional<status_t>(result);
5026 captureCondition.notify_one();
5027 }
5028 });
5029
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005030 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005031 if (result == NO_ERROR) {
5032 captureCondition.wait(captureLock, [&]() { return captureResult; });
5033 while (*captureResult == EAGAIN) {
5034 captureResult.reset();
5035 result = postMessageAsync(message);
5036 if (result != NO_ERROR) {
5037 return result;
5038 }
5039 captureCondition.wait(captureLock, [&]() { return captureResult; });
5040 }
5041 result = *captureResult;
5042 }
5043
5044 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005045 sync_wait(syncFd, -1);
5046 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005047 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005048
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005049 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005050}
5051
chaviwa76b2712017-09-20 12:02:26 -07005052void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5053 TraverseLayersFunction traverseLayers, bool yswap,
5054 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005055 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005056
Lloyd Pique144e1162017-12-20 16:44:52 -08005057 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005058
5059 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005060 const auto raWidth = renderArea.getWidth();
5061 const auto raHeight = renderArea.getHeight();
5062
5063 const auto reqWidth = renderArea.getReqWidth();
5064 const auto reqHeight = renderArea.getReqHeight();
5065 Rect sourceCrop = renderArea.getSourceCrop();
5066
Iris Chang7501ed62018-04-30 14:45:42 +08005067 bool filtering = false;
5068 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5069 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5070 static_cast<int32_t>(reqHeight) != raWidth;
5071 } else {
5072 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5073 static_cast<int32_t>(reqHeight) != raHeight;
5074 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005075
Dan Stozac1879002014-05-22 15:59:05 -07005076 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005077 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005078 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005079 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005080 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5081 Transform tr;
5082 uint32_t flags = 0x00;
5083 switch (mPrimaryDisplayOrientation) {
5084 case DisplayState::eOrientation90:
5085 flags = Transform::ROT_90;
5086 break;
5087 case DisplayState::eOrientation180:
5088 flags = Transform::ROT_180;
5089 break;
5090 case DisplayState::eOrientation270:
5091 flags = Transform::ROT_270;
5092 break;
5093 }
5094 tr.set(flags, raWidth, raHeight);
5095 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005096 }
5097
5098 // ensure that sourceCrop is inside screen
5099 if (sourceCrop.left < 0) {
5100 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5101 }
chaviwa76b2712017-09-20 12:02:26 -07005102 if (sourceCrop.right > raWidth) {
5103 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005104 }
5105 if (sourceCrop.top < 0) {
5106 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5107 }
chaviwa76b2712017-09-20 12:02:26 -07005108 if (sourceCrop.bottom > raHeight) {
5109 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005110 }
5111
Chia-I Wu36574d92018-05-16 10:54:36 -07005112 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5113 engine.setOutputDataSpace(Dataspace::SRGB);
5114 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005115
Mathias Agopian180f10d2013-04-10 22:55:41 -07005116 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005117 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005118
Iris Chang7501ed62018-04-30 14:45:42 +08005119 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5120 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5121 // convert hw orientation into flag presentation
5122 // here inverse transform needed
5123 uint8_t hw_rot_90 = 0x00;
5124 uint8_t hw_flip_hv = 0x00;
5125 switch (mPrimaryDisplayOrientation) {
5126 case DisplayState::eOrientation90:
5127 hw_rot_90 = Transform::ROT_90;
5128 hw_flip_hv = Transform::ROT_180;
5129 break;
5130 case DisplayState::eOrientation180:
5131 hw_flip_hv = Transform::ROT_180;
5132 break;
5133 case DisplayState::eOrientation270:
5134 hw_rot_90 = Transform::ROT_90;
5135 break;
5136 }
5137
5138 // transform flags operation
5139 // 1) flip H V if both have ROT_90 flag
5140 // 2) XOR these flags
5141 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5142 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5143 if (rotation_rot_90 & hw_rot_90) {
5144 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5145 }
5146 rotation = static_cast<Transform::orientation_flags>
5147 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5148 }
5149
Mathias Agopian180f10d2013-04-10 22:55:41 -07005150 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005151 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005152 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005153 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005154
chaviw50da5042018-04-09 13:49:37 -07005155 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005156 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005157 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005158
chaviwa76b2712017-09-20 12:02:26 -07005159 traverseLayers([&](Layer* layer) {
5160 if (filtering) layer->setFiltering(true);
5161 layer->draw(renderArea, useIdentityTransform);
5162 if (filtering) layer->setFiltering(false);
5163 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005164}
5165
chaviwa76b2712017-09-20 12:02:26 -07005166status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5167 TraverseLayersFunction traverseLayers,
5168 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005169 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005170 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005171 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005172 ATRACE_CALL();
5173
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005174 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005175
5176 traverseLayers([&](Layer* layer) {
5177 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5178 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005179
Robert Carr03480e22018-01-04 16:02:06 -08005180 // We allow the system server to take screenshots of secure layers for
5181 // use in situations like the Screen-rotation animation and place
5182 // the impetus on WindowManager to not persist them.
5183 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005184 ALOGW("FB is protected: PERMISSION_DENIED");
5185 return PERMISSION_DENIED;
5186 }
5187
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005188 // this binds the given EGLImage as a framebuffer for the
5189 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005190 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005191 if (bufferBond.getStatus() != NO_ERROR) {
5192 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005193 return INVALID_OPERATION;
5194 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005195
Dan Stozaabcda352017-06-01 14:37:39 -07005196 // this will in fact render into our dequeued buffer
5197 // via an FBO, which means we didn't have to create
5198 // an EGLSurface and therefore we're not
5199 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005200 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005201
Dan Stozaabcda352017-06-01 14:37:39 -07005202 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005203 getRenderEngine().finish();
5204 *outSyncFd = -1;
5205
chaviwa76b2712017-09-20 12:02:26 -07005206 const auto reqWidth = renderArea.getReqWidth();
5207 const auto reqHeight = renderArea.getReqHeight();
5208
Dan Stozaabcda352017-06-01 14:37:39 -07005209 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5210 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005211 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005212 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005213 } else {
5214 base::unique_fd syncFd = getRenderEngine().flush();
5215 if (syncFd < 0) {
5216 getRenderEngine().finish();
5217 }
5218 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005219 }
5220
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005221 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005222}
5223
Mathias Agopiand5556842013-09-19 17:08:37 -07005224void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005225 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005226 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005227 for (size_t y = 0; y < h; y++) {
5228 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5229 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005230 if (p[x] != 0xFF000000) return;
5231 }
5232 }
chaviwa76b2712017-09-20 12:02:26 -07005233 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005234
Robert Carr2047fae2016-11-28 14:09:09 -08005235 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005236 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005237 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005238 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5239 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5240 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5241 static_cast<float>(state.color.a));
5242 i++;
5243 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005244 }
5245}
5246
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005247// ---------------------------------------------------------------------------
5248
Dan Stoza412903f2017-04-27 13:42:17 -07005249void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5250 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005251}
5252
Dan Stoza412903f2017-04-27 13:42:17 -07005253void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5254 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005255}
5256
chaviwa76b2712017-09-20 12:02:26 -07005257void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5258 int32_t maxLayerZ,
5259 const LayerVector::Visitor& visitor) {
5260 // We loop through the first level of layers without traversing,
5261 // as we need to interpret min/max layer Z in the top level Z space.
5262 for (const auto& layer : mDrawingState.layersSortedByZ) {
5263 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5264 continue;
5265 }
5266 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005267 // relative layers are traversed in Layer::traverseInZOrder
5268 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005269 continue;
5270 }
5271 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005272 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5273 return;
5274 }
chaviwa76b2712017-09-20 12:02:26 -07005275 if (!layer->isVisible()) {
5276 return;
5277 }
5278 visitor(layer);
5279 });
5280 }
5281}
5282
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005283}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005284
5285
5286#if defined(__gl_h_)
5287#error "don't include gl/gl.h in this file"
5288#endif
5289
5290#if defined(__gl2_h_)
5291#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005292#endif