blob: cd51dd1d61adcceb605c24bfd24dcbf2527467b8 [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),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800226 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700227 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700228 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700229 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700230 mDebugInSwapBuffers(0),
231 mLastSwapBufferTime(0),
232 mDebugInTransaction(0),
233 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700234 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700235 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000236 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700237 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700238 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800239 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800240 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700241 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800242 mMainThreadId(std::this_thread::get_id()),
Lloyd 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();
501 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700502 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800503}
504
Mathias Agopian3f844832013-08-07 21:24:32 -0700505void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700506 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800507 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700508 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700509 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800510 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
511 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700512 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700513 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700514 return true;
515 }
516 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700517 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700518}
519
Lloyd Piquee83f9312018-02-01 12:53:17 -0800520class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700521public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700522 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000523 const char* name) :
524 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700525 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700526 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000527 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
528 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700529 mDispSync(dispSync),
530 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700531 mVsyncMutex(),
532 mPhaseOffset(phaseOffset),
533 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700534
Lloyd Piquee83f9312018-02-01 12:53:17 -0800535 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700536
Lloyd Piquee83f9312018-02-01 12:53:17 -0800537 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700538 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700539 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000540 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700541 static_cast<DispSync::Callback*>(this));
542 if (err != NO_ERROR) {
543 ALOGE("error registering vsync callback: %s (%d)",
544 strerror(-err), err);
545 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700546 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700547 } else {
548 status_t err = mDispSync->removeEventListener(
549 static_cast<DispSync::Callback*>(this));
550 if (err != NO_ERROR) {
551 ALOGE("error unregistering vsync callback: %s (%d)",
552 strerror(-err), err);
553 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700554 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700555 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700556 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700557 }
558
Lloyd Piquee83f9312018-02-01 12:53:17 -0800559 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700560 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700561 mCallback = callback;
562 }
563
Lloyd Piquee83f9312018-02-01 12:53:17 -0800564 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700565 Mutex::Autolock lock(mVsyncMutex);
566
567 // Normalize phaseOffset to [0, period)
568 auto period = mDispSync->getPeriod();
569 phaseOffset %= period;
570 if (phaseOffset < 0) {
571 // If we're here, then phaseOffset is in (-period, 0). After this
572 // operation, it will be in (0, period)
573 phaseOffset += period;
574 }
575 mPhaseOffset = phaseOffset;
576
577 // If we're not enabled, we don't need to mess with the listeners
578 if (!mEnabled) {
579 return;
580 }
581
Dan Stoza2713c302018-03-28 17:07:36 -0700582 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
583 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700584 if (err != NO_ERROR) {
Dan Stoza2713c302018-03-28 17:07:36 -0700585 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700586 strerror(-err), err);
587 }
588 }
589
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700590private:
591 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800592 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700593 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700594 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700595 callback = mCallback;
596
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700597 if (mTraceVsync) {
598 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700599 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700600 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700601 }
602
Peiyong Lin566a3b42018-01-09 18:22:43 -0800603 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700604 callback->onVSyncEvent(when);
605 }
606 }
607
Tim Murray4a4e4a22016-04-19 16:29:23 +0000608 const char* const mName;
609
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700610 int mValue;
611
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700612 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700613 const String8 mVsyncOnLabel;
614 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700615
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700616 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700617
618 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800619 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700620
621 Mutex mVsyncMutex; // Protects the following
622 nsecs_t mPhaseOffset;
623 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700624};
625
Lloyd Piquee83f9312018-02-01 12:53:17 -0800626class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700627public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800628 InjectVSyncSource() = default;
629 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700630
Lloyd Piquee83f9312018-02-01 12:53:17 -0800631 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700632 std::lock_guard<std::mutex> lock(mCallbackMutex);
633 mCallback = callback;
634 }
635
Lloyd Piquee83f9312018-02-01 12:53:17 -0800636 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700637 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700638 if (mCallback) {
639 mCallback->onVSyncEvent(when);
640 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700641 }
642
Lloyd Piquee83f9312018-02-01 12:53:17 -0800643 void setVSyncEnabled(bool) override {}
644 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700645
646private:
647 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800648 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700649};
650
Wei Wangf9b05ee2017-07-19 20:59:39 -0700651// Do not call property_set on main thread which will be blocked by init
652// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700653void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700654 ALOGI( "SurfaceFlinger's main thread ready to run. "
655 "Initializing graphics H/W...");
656
Thierry Strudel2924d012017-08-14 15:19:37 -0700657 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900658
Steven Thomasb02664d2017-07-26 18:48:28 -0700659 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800660
Steven Thomasb02664d2017-07-26 18:48:28 -0700661 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800662 mEventThreadSource =
663 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
664 true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800665 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
666 [this]() { resyncWithRateLimit(); },
667 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800668 "appEventThread");
669 mSfEventThreadSource =
670 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
671 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800672
Lloyd Pique24b0a482018-03-09 18:52:26 -0800673 mSFEventThread =
674 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
675 [this]() { resyncWithRateLimit(); },
676 [this](nsecs_t timestamp) {
677 mInterceptor->saveVSyncEvent(timestamp);
678 },
679 "sfEventThread");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800680 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggie203e042018-06-19 15:57:08 +0200681 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800682
Steven Thomasb02664d2017-07-26 18:48:28 -0700683 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800684 getBE().mRenderEngine =
685 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
686 hasWideColorDisplay
687 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
688 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800689 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700690
691 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
692 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800693 getBE().mHwc.reset(
694 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700695 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800696 // Process any initial hotplug and resulting display changes.
697 processDisplayHotplugEventsLocked();
698 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
699 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800700
Lloyd Piquefcd86612017-12-14 17:15:36 -0800701 // make the default display GLContext current so that we can create textures
702 // when creating Layers (which may happens before we render something)
703 getDefaultDisplayDeviceLocked()->makeCurrent();
704
Steven Thomas050b2c82017-03-06 11:45:16 -0800705 if (useVrFlinger) {
706 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700707 // This callback is called from the vr flinger dispatch thread. We
708 // need to call signalTransaction(), which requires holding
709 // mStateLock when we're not on the main thread. Acquiring
710 // mStateLock from the vr flinger dispatch thread might trigger a
711 // deadlock in surface flinger (see b/66916578), so post a message
712 // to be handled on the main thread instead.
713 sp<LambdaMessage> message = new LambdaMessage([=]() {
714 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
715 mVrFlingerRequestsDisplay = requestDisplay;
716 signalTransaction();
717 });
718 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800719 };
David Sodman105b7dc2017-11-04 20:28:14 -0700720 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
721 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800722 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800723 if (!mVrFlinger) {
724 ALOGE("Failed to start vrflinger");
725 }
726 }
727
Lloyd Pique0c3a8832018-01-22 17:31:47 -0800728 mEventControlThread = std::make_unique<impl::EventControlThread>(
729 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700730
Mathias Agopian92a979a2012-08-02 18:32:23 -0700731 // initialize our drawing state
732 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700733
Andy McFadden13a082e2012-08-24 10:16:42 -0700734 // set initial conditions (e.g. unblank default device)
735 initializeDisplays();
736
David Sodmanbc815282017-11-05 18:57:52 -0800737 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700738
Wei Wangf9b05ee2017-07-19 20:59:39 -0700739 // Inform native graphics APIs whether the present timestamp is supported:
740 if (getHwComposer().hasCapability(
741 HWC2::Capability::PresentFenceIsNotReliable)) {
742 mStartPropertySetThread = new StartPropertySetThread(false);
743 } else {
744 mStartPropertySetThread = new StartPropertySetThread(true);
745 }
746
747 if (mStartPropertySetThread->Start() != NO_ERROR) {
748 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800749 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800750
Chia-I Wu6d844112018-06-27 07:17:41 +0800751 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
752 // is used to saturate legacy sRGB content. However, to make sure the same color under
753 // Display P3 will be saturated to the same color, we intentionally break the API spec
754 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
755 // such saturation matrix on Display P3 is understood fully, the API should always return
756 // identify matrix.
757 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800758 Dataspace::SRGB_LINEAR);
759
Chia-I Wu6d844112018-06-27 07:17:41 +0800760 // we will apply this on Display P3.
761 if (mEnhancedSaturationMatrix != mat4()) {
762 ColorSpace srgb(ColorSpace::sRGB());
763 ColorSpace displayP3(ColorSpace::DisplayP3());
764 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
765 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
766 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
767 }
768
Dan Stoza9e56aa02015-11-02 13:00:03 -0800769 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700770}
771
Romain Guy11d63f42017-07-20 12:47:14 -0700772void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700773 Mutex::Autolock _l(mStateLock);
774
Romain Guy11d63f42017-07-20 12:47:14 -0700775 char value[PROPERTY_VALUE_MAX];
776
777 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800778 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700779 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800780 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100781
782 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700783 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700784}
785
Mathias Agopiana67e4182012-06-19 17:26:12 -0700786void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800787 // Start boot animation service by setting a property mailbox
788 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700789 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800790 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700791 if (mStartPropertySetThread->join() != NO_ERROR) {
792 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800793 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700794}
795
Mathias Agopian875d8e12013-06-07 15:35:48 -0700796size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800797 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700798}
799
Mathias Agopian875d8e12013-06-07 15:35:48 -0700800size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800801 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700802}
803
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800804// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800805
Jamie Gennis582270d2011-08-17 18:19:00 -0700806bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800807 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800808 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800809 return authenticateSurfaceTextureLocked(bufferProducer);
810}
811
812bool SurfaceFlinger::authenticateSurfaceTextureLocked(
813 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800814 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800815 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800816}
817
Brian Anderson6b376712017-04-04 10:51:39 -0700818status_t SurfaceFlinger::getSupportedFrameTimestamps(
819 std::vector<FrameEvent>* outSupported) const {
820 *outSupported = {
821 FrameEvent::REQUESTED_PRESENT,
822 FrameEvent::ACQUIRE,
823 FrameEvent::LATCH,
824 FrameEvent::FIRST_REFRESH_START,
825 FrameEvent::LAST_REFRESH_START,
826 FrameEvent::GPU_COMPOSITION_DONE,
827 FrameEvent::DEQUEUE_READY,
828 FrameEvent::RELEASE,
829 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700830 ConditionalLock _l(mStateLock,
831 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700832 if (!getHwComposer().hasCapability(
833 HWC2::Capability::PresentFenceIsNotReliable)) {
834 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
835 }
836 return NO_ERROR;
837}
838
Dan Stoza7f7da322014-05-02 15:26:25 -0700839status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
840 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800841 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700842 return BAD_VALUE;
843 }
844
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500845 if (!display.get())
846 return NAME_NOT_FOUND;
847
Jesse Hall692c7232012-11-08 15:41:56 -0800848 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700849 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800850 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700851 type = i;
852 break;
853 }
854 }
855
856 if (type < 0) {
857 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700858 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700859
Mathias Agopian8b736f12012-08-13 17:54:26 -0700860 // TODO: Not sure if display density should handled by SF any longer
861 class Density {
862 static int getDensityFromProperty(char const* propName) {
863 char property[PROPERTY_VALUE_MAX];
864 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800865 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700866 density = atoi(property);
867 }
868 return density;
869 }
870 public:
871 static int getEmuDensity() {
872 return getDensityFromProperty("qemu.sf.lcd_density"); }
873 static int getBuildDensity() {
874 return getDensityFromProperty("ro.sf.lcd_density"); }
875 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700876
Dan Stoza7f7da322014-05-02 15:26:25 -0700877 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700878
Steven Thomas6d8110b2017-08-31 18:24:21 -0700879 ConditionalLock _l(mStateLock,
880 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800881 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700882 DisplayInfo info = DisplayInfo();
883
Dan Stoza9e56aa02015-11-02 13:00:03 -0800884 float xdpi = hwConfig->getDpiX();
885 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700886
887 if (type == DisplayDevice::DISPLAY_PRIMARY) {
888 // The density of the device is provided by a build property
889 float density = Density::getBuildDensity() / 160.0f;
890 if (density == 0) {
891 // the build doesn't provide a density -- this is wrong!
892 // use xdpi instead
893 ALOGE("ro.sf.lcd_density must be defined as a build property");
894 density = xdpi / 160.0f;
895 }
896 if (Density::getEmuDensity()) {
897 // if "qemu.sf.lcd_density" is specified, it overrides everything
898 xdpi = ydpi = density = Density::getEmuDensity();
899 density /= 160.0f;
900 }
901 info.density = density;
902
903 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700904 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800905 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700906 } else {
907 // TODO: where should this value come from?
908 static const int TV_DENSITY = 213;
909 info.density = TV_DENSITY / 160.0f;
910 info.orientation = 0;
911 }
912
Dan Stoza9e56aa02015-11-02 13:00:03 -0800913 info.w = hwConfig->getWidth();
914 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700915 info.xdpi = xdpi;
916 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800917 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900918 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800919
Andy McFadden91b2ca82014-06-13 14:04:23 -0700920 // This is how far in advance a buffer must be queued for
921 // presentation at a given time. If you want a buffer to appear
922 // on the screen at time N, you must submit the buffer before
923 // (N - presentationDeadline).
924 //
925 // Normally it's one full refresh period (to give SF a chance to
926 // latch the buffer), but this can be reduced by configuring a
927 // DispSync offset. Any additional delays introduced by the hardware
928 // composer or panel must be accounted for here.
929 //
930 // We add an additional 1ms to allow for processing time and
931 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800932 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800933 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700934
935 // All non-virtual displays are currently considered secure.
936 info.secure = true;
937
Iris Chang7501ed62018-04-30 14:45:42 +0800938 if (type == DisplayDevice::DISPLAY_PRIMARY &&
939 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
940 std::swap(info.w, info.h);
941 }
942
Michael Wright28f24d02016-07-12 13:30:53 -0700943 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700944 }
945
Dan Stoza7f7da322014-05-02 15:26:25 -0700946 return NO_ERROR;
947}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700948
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800949status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700950 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800951 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700952 return BAD_VALUE;
953 }
954
955 // FIXME for now we always return stats for the primary display
956 memset(stats, 0, sizeof(*stats));
957 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
958 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
959 return NO_ERROR;
960}
961
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700962int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800963 if (display == nullptr) {
964 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800965 return BAD_VALUE;
966 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700967
968 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -0800969 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700970 return device->getActiveConfig();
971 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700972
Dan Stoza24a42e92015-03-09 10:04:11 -0700973 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700974}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700975
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700976void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
977 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
978 this);
979 int32_t type = hw->getDisplayType();
980 int currentMode = hw->getActiveConfig();
981
982 if (mode == currentMode) {
983 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
984 return;
985 }
986
987 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
988 ALOGW("Trying to set config for virtual display");
989 return;
990 }
991
992 hw->setActiveConfig(mode);
993 getHwComposer().setActiveConfig(type, mode);
994}
995
996status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
997 class MessageSetActiveConfig: public MessageBase {
998 SurfaceFlinger& mFlinger;
999 sp<IBinder> mDisplay;
1000 int mMode;
1001 public:
1002 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
1003 int mode) :
1004 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1005 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -07001006 Vector<DisplayInfo> configs;
1007 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -07001008 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -07001009 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -07001010 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -07001011 return true;
Michael Lentine7306c672014-07-30 13:00:37 -07001012 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001013 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08001014 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001015 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07001016 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001017 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
1018 ALOGW("Attempt to set active config = %d for virtual display",
1019 mMode);
1020 } else {
1021 mFlinger.setActiveConfigInternal(hw, mMode);
1022 }
1023 return true;
1024 }
1025 };
1026 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
1027 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -07001028 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001029}
Michael Wright28f24d02016-07-12 13:30:53 -07001030status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001031 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001032 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
1033 return BAD_VALUE;
1034 }
1035
1036 if (!display.get()) {
1037 return NAME_NOT_FOUND;
1038 }
1039
1040 int32_t type = NAME_NOT_FOUND;
1041 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
1042 if (display == mBuiltinDisplays[i]) {
1043 type = i;
1044 break;
1045 }
1046 }
1047
1048 if (type < 0) {
1049 return type;
1050 }
1051
Peiyong Lina52f0292018-03-14 17:26:31 -07001052 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001053 {
1054 ConditionalLock _l(mStateLock,
1055 std::this_thread::get_id() != mMainThreadId);
1056 modes = getHwComposer().getColorModes(type);
1057 }
Michael Wright28f24d02016-07-12 13:30:53 -07001058 outColorModes->clear();
1059 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1060
1061 return NO_ERROR;
1062}
1063
Peiyong Lina52f0292018-03-14 17:26:31 -07001064ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001065 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -07001066 if (device != nullptr) {
1067 return device->getActiveColorMode();
1068 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001069 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001070}
1071
1072void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001073 ColorMode mode, Dataspace dataSpace,
1074 RenderIntent renderIntent) {
Michael Wright28f24d02016-07-12 13:30:53 -07001075 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -07001076 ColorMode currentMode = hw->getActiveColorMode();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001077 Dataspace currentDataSpace = hw->getCompositionDataSpace();
Peiyong Lin38e9a562018-04-10 16:24:20 -07001078 RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001079
Peiyong Lin38e9a562018-04-10 16:24:20 -07001080 if (mode == currentMode && dataSpace == currentDataSpace &&
1081 renderIntent == currentRenderIntent) {
1082 return;
1083 }
1084
1085 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1086 ALOGW("Trying to set config for virtual display");
1087 return;
1088 }
1089
1090 hw->setActiveColorMode(mode);
1091 hw->setCompositionDataSpace(dataSpace);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001092 hw->setActiveRenderIntent(renderIntent);
1093 getHwComposer().setActiveColorMode(type, mode, renderIntent);
1094
1095 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1096 decodeColorMode(mode).c_str(), mode,
1097 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1098 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001099}
1100
1101
1102status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001103 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001104 class MessageSetActiveColorMode: public MessageBase {
1105 SurfaceFlinger& mFlinger;
1106 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001107 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001108 public:
1109 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001110 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001111 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1112 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001113 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001114 mFlinger.getDisplayColorModes(mDisplay, &modes);
1115 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001116 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001117 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1118 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001119 return true;
1120 }
1121 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1122 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001123 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1124 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001125 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001126 ALOGW("Attempt to set active color mode %s %d for virtual display",
1127 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001128 } else {
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001129 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN,
1130 RenderIntent::COLORIMETRIC);
Michael Wright28f24d02016-07-12 13:30:53 -07001131 }
1132 return true;
1133 }
1134 };
1135 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1136 postMessageSync(msg);
1137 return NO_ERROR;
1138}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001139
Svetoslavd85084b2014-03-20 10:28:31 -07001140status_t SurfaceFlinger::clearAnimationFrameStats() {
1141 Mutex::Autolock _l(mStateLock);
1142 mAnimFrameTracker.clearStats();
1143 return NO_ERROR;
1144}
1145
1146status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1147 Mutex::Autolock _l(mStateLock);
1148 mAnimFrameTracker.getStats(outStats);
1149 return NO_ERROR;
1150}
1151
Dan Stozac4f471e2016-03-24 09:31:08 -07001152status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1153 HdrCapabilities* outCapabilities) const {
1154 Mutex::Autolock _l(mStateLock);
1155
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001156 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001157 if (displayDevice == nullptr) {
1158 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1159 return BAD_VALUE;
1160 }
1161
Peiyong Linfb069302018-04-25 14:34:31 -07001162 // At this point the DisplayDeivce should already be set up,
1163 // meaning the luminance information is already queried from
1164 // hardware composer and stored properly.
1165 const HdrCapabilities& capabilities = displayDevice->getHdrCapabilities();
1166 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1167 capabilities.getDesiredMaxLuminance(),
1168 capabilities.getDesiredMaxAverageLuminance(),
1169 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001170
1171 return NO_ERROR;
1172}
1173
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001174status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001175 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1176 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001177
Chia-I Wu90f669f2017-10-05 14:24:41 -07001178 if (mInjectVSyncs == enable) {
1179 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001180 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001181
1182 if (enable) {
1183 ALOGV("VSync Injections enabled");
1184 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001185 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001186 mInjectorEventThread = std::make_unique<
1187 impl::EventThread>(mVSyncInjector.get(),
1188 [this]() { resyncWithRateLimit(); },
1189 impl::EventThread::InterceptVSyncsCallback(),
1190 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001191 }
Lloyd Pique9123ae52018-01-22 17:14:00 -08001192 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001193 } else {
1194 ALOGV("VSync Injections disabled");
Lloyd Pique9123ae52018-01-22 17:14:00 -08001195 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001196 }
1197
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001198 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001199 });
1200 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001201 return NO_ERROR;
1202}
1203
1204status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001205 Mutex::Autolock _l(mStateLock);
1206
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001207 if (!mInjectVSyncs) {
1208 ALOGE("VSync Injections not enabled");
1209 return BAD_VALUE;
1210 }
1211 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1212 ALOGV("Injecting VSync inside SurfaceFlinger");
1213 mVSyncInjector->onInjectSyncEvent(when);
1214 }
1215 return NO_ERROR;
1216}
1217
Lloyd Pique755e3192018-01-31 16:46:15 -08001218status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1219 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001220 IPCThreadState* ipc = IPCThreadState::self();
1221 const int pid = ipc->getCallingPid();
1222 const int uid = ipc->getCallingUid();
1223 if ((uid != AID_SHELL) &&
1224 !PermissionCache::checkPermission(sDump, pid, uid)) {
1225 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1226 return PERMISSION_DENIED;
1227 }
1228
1229 // Try to acquire a lock for 1s, fail gracefully
1230 const status_t err = mStateLock.timedLock(s2ns(1));
1231 const bool locked = (err == NO_ERROR);
1232 if (!locked) {
1233 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1234 return TIMED_OUT;
1235 }
1236
1237 outLayers->clear();
1238 mCurrentState.traverseInZOrder([&](Layer* layer) {
1239 outLayers->push_back(layer->getLayerDebugInfo());
1240 });
1241
1242 mStateLock.unlock();
1243 return NO_ERROR;
1244}
1245
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001246// ----------------------------------------------------------------------------
1247
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001248sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1249 ISurfaceComposer::VsyncSource vsyncSource) {
1250 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1251 return mSFEventThread->createEventConnection();
1252 } else {
1253 return mEventThread->createEventConnection();
1254 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001255}
1256
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001257// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001258
1259void SurfaceFlinger::waitForEvent() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001260 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001261}
1262
1263void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001264 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001265}
1266
1267void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001268 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001269}
1270
1271void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001272 mRefreshPending = true;
Lloyd Pique9123ae52018-01-22 17:14:00 -08001273 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001274}
1275
1276status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001277 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001278 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001279}
1280
1281status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001282 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001283 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001284 if (res == NO_ERROR) {
1285 msg->wait();
1286 }
1287 return res;
1288}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001289
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001290void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001291 do {
1292 waitForEvent();
1293 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001294}
1295
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001296void SurfaceFlinger::enableHardwareVsync() {
1297 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001298 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001299 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001300 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1301 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001302 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001303 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001304}
1305
Jesse Hall948fe0c2013-10-14 12:56:09 -07001306void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001307 Mutex::Autolock _l(mHWVsyncLock);
1308
Jesse Hall948fe0c2013-10-14 12:56:09 -07001309 if (makeAvailable) {
1310 mHWVsyncAvailable = true;
1311 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001312 // Hardware vsync is not currently available, so abort the resync
1313 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001314 return;
1315 }
1316
David Sodman105b7dc2017-11-04 20:28:14 -07001317 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001318 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001319
1320 mPrimaryDispSync.reset();
1321 mPrimaryDispSync.setPeriod(period);
1322
1323 if (!mPrimaryHWVsyncEnabled) {
1324 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001325 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1326 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001327 mPrimaryHWVsyncEnabled = true;
1328 }
1329}
1330
Jesse Hall948fe0c2013-10-14 12:56:09 -07001331void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001332 Mutex::Autolock _l(mHWVsyncLock);
1333 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001334 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1335 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001336 mPrimaryDispSync.endResync();
1337 mPrimaryHWVsyncEnabled = false;
1338 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001339 if (makeUnavailable) {
1340 mHWVsyncAvailable = false;
1341 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001342}
1343
Tim Murray4a4e4a22016-04-19 16:29:23 +00001344void SurfaceFlinger::resyncWithRateLimit() {
1345 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001346
1347 // No explicit locking is needed here since EventThread holds a lock while calling this method
1348 static nsecs_t sLastResyncAttempted = 0;
1349 const nsecs_t now = systemTime();
1350 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001351 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001352 }
Dan Stoza57164302017-05-08 14:03:54 -07001353 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001354}
1355
Steven Thomasb02664d2017-07-26 18:48:28 -07001356void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1357 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001358 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001359 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001360 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001361 return;
1362 }
1363
1364 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001365 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001366 return;
1367 }
1368
Jamie Gennisd1700752013-10-14 12:22:52 -07001369 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001370
Jamie Gennisd1700752013-10-14 12:22:52 -07001371 { // Scope for the lock
1372 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001373 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001374 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001375 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001376 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001377
1378 if (needsHwVsync) {
1379 enableHardwareVsync();
1380 } else {
1381 disableHardwareVsync(false);
1382 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001383}
1384
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001385void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001386 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1387 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001388}
1389
Lloyd Pique715a2c12017-12-14 17:18:08 -08001390void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1391 HWC2::Connection connection) {
1392 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1393 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001394
Lloyd Piqueba04e622017-12-14 17:11:26 -08001395 // Ignore events that do not have the right sequenceId.
1396 if (sequenceId != getBE().mComposerSequenceId) {
1397 return;
1398 }
1399
Steven Thomasb02664d2017-07-26 18:48:28 -07001400 // Only lock if we're not on the main thread. This function is normally
1401 // called on a hwbinder thread, but for the primary display it's called on
1402 // the main thread with the state lock already held, so don't attempt to
1403 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001404 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001405
Lloyd Pique715a2c12017-12-14 17:18:08 -08001406 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001407
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001408 if (std::this_thread::get_id() == mMainThreadId) {
1409 // Process all pending hot plug events immediately if we are on the main thread.
1410 processDisplayHotplugEventsLocked();
1411 }
1412
Lloyd Piqueba04e622017-12-14 17:11:26 -08001413 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001414}
1415
Steven Thomasb02664d2017-07-26 18:48:28 -07001416void SurfaceFlinger::onRefreshReceived(int sequenceId,
1417 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001418 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001419 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001420 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001421 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001422 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001423}
1424
Dan Stoza9e56aa02015-11-02 13:00:03 -08001425void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001426 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001427 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001428 getHwComposer().setVsyncEnabled(disp,
1429 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001430}
1431
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001432// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001433void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001434 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001435 // Clear the drawing state so that the logic inside of
1436 // handleTransactionLocked will fire. It will determine the delta between
1437 // mCurrentState and mDrawingState and re-apply all changes when we make the
1438 // transition.
1439 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001440 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001441 mDisplays.clear();
1442}
1443
Steven Thomas050b2c82017-03-06 11:45:16 -08001444void SurfaceFlinger::updateVrFlinger() {
1445 if (!mVrFlinger)
1446 return;
1447 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001448 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001449 return;
1450 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001451
David Sodman105b7dc2017-11-04 20:28:14 -07001452 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001453 ALOGE("Vr flinger is only supported for remote hardware composer"
1454 " service connections. Ignoring request to transition to vr"
1455 " flinger.");
1456 mVrFlingerRequestsDisplay = false;
1457 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001458 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001459
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001460 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001461
Steven Thomasb02664d2017-07-26 18:48:28 -07001462 int currentDisplayPowerMode = getDisplayDeviceLocked(
1463 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001464
Steven Thomasb02664d2017-07-26 18:48:28 -07001465 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001466 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001467 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001468
Steven Thomasb02664d2017-07-26 18:48:28 -07001469 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001470 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001471 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1472 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001473 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001474
David Sodman105b7dc2017-11-04 20:28:14 -07001475 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1476 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001477
1478 if (vrFlingerRequestsDisplay) {
1479 mVrFlinger->GrantDisplayOwnership();
1480 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001481 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001482 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001483
1484 mVisibleRegionsDirty = true;
1485 invalidateHwcGeometry();
1486
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001487 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001488 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1489 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1490 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001491
Steven Thomasb02664d2017-07-26 18:48:28 -07001492 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001493 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001494 const nsecs_t period = activeConfig->getVsyncPeriod();
1495 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001496
Steven Thomasb02664d2017-07-26 18:48:28 -07001497 // Use phase of 0 since phase is not known.
1498 // Use latency of 0, which will snap to the ideal latency.
1499 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001500
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001501 android_atomic_or(1, &mRepaintEverything);
1502 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001503}
1504
Mathias Agopian4fec8732012-06-29 14:12:52 -07001505void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001506 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001507 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001508 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001509 bool frameMissed = !mHadClientComposition &&
1510 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001511 (mPreviousPresentFence->getSignalTime() ==
1512 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001513 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001514 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001515 mTimeStats.incrementMissedFrames();
1516 if (mPropagateBackpressure) {
1517 signalLayerUpdate();
1518 break;
1519 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001520 }
Dan Stoza50182882016-07-08 12:02:20 -07001521
Steven Thomas050b2c82017-03-06 11:45:16 -08001522 // Now that we're going to make it to the handleMessageTransaction()
1523 // call below it's safe to call updateVrFlinger(), which will
1524 // potentially trigger a display handoff.
1525 updateVrFlinger();
1526
Dan Stoza6b9454d2014-11-07 16:00:59 -08001527 bool refreshNeeded = handleMessageTransaction();
1528 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001529 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001530 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001531 // Signal a refresh if a transaction modified the window state,
1532 // a new buffer was latched, or if HWC has requested a full
1533 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001534 signalRefresh();
1535 }
1536 break;
1537 }
1538 case MessageQueue::REFRESH: {
1539 handleMessageRefresh();
1540 break;
1541 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001542 }
1543}
1544
Dan Stoza6b9454d2014-11-07 16:00:59 -08001545bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001546 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001547 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001548 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001549 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001550 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001551 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001552}
1553
Dan Stoza6b9454d2014-11-07 16:00:59 -08001554bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001555 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001556 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001557}
1558
1559void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001560 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001561
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001562 mRefreshPending = false;
1563
Pablo Ceballos40845df2016-01-25 17:41:15 -08001564 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001565
Brian Andersond6927fb2016-07-23 23:37:30 -07001566 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001567 rebuildLayerStacks();
1568 setUpHWComposer();
1569 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001570 doTracing("handleRefresh");
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001571 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001572 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001573 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001574
David Sodman105b7dc2017-11-04 20:28:14 -07001575 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001576
1577 mHadClientComposition = false;
1578 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1579 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1580 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001581 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001582 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001583 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001584
Dan Stoza9e56aa02015-11-02 13:00:03 -08001585 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001586}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001587
Mathias Agopiancd60f992012-08-16 16:28:27 -07001588void SurfaceFlinger::doDebugFlashRegions()
1589{
1590 // is debugging enabled
1591 if (CC_LIKELY(!mDebugRegion))
1592 return;
1593
1594 const bool repaintEverything = mRepaintEverything;
1595 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1596 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001597 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001598 // transform the dirty region into this screen's coordinate space
1599 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1600 if (!dirtyRegion.isEmpty()) {
1601 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001602 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001603
1604 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001605 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001606 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001607 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1608
Mathias Agopianda27af92012-09-13 18:17:13 -07001609 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001610 }
1611 }
1612 }
1613
1614 postFramebuffer();
1615
1616 if (mDebugRegion > 1) {
1617 usleep(mDebugRegion * 1000);
1618 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001619
Dan Stoza9e56aa02015-11-02 13:00:03 -08001620 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001621 auto& displayDevice = mDisplays[displayId];
1622 if (!displayDevice->isDisplayOn()) {
1623 continue;
1624 }
1625
David Sodman105b7dc2017-11-04 20:28:14 -07001626 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1627 ALOGE_IF(result != NO_ERROR,
1628 "prepareFrame for display %zd failed:"
1629 " %d (%s)",
1630 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001631 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001632}
1633
Adrian Roos1e1a1282017-11-01 19:05:31 +01001634void SurfaceFlinger::doTracing(const char* where) {
1635 ATRACE_CALL();
1636 ATRACE_NAME(where);
1637 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001638 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001639 }
1640}
1641
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001642void SurfaceFlinger::logLayerStats() {
1643 ATRACE_CALL();
1644 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1645 int32_t hwcId = -1;
1646 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1647 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1648 if (displayDevice->isPrimary()) {
1649 hwcId = displayDevice->getHwcDisplayId();
1650 break;
1651 }
1652 }
1653 if (hwcId < 0) {
1654 ALOGE("LayerStats: Hmmm, no primary display?");
1655 return;
1656 }
1657 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1658 }
1659}
1660
Brian Andersond6927fb2016-07-23 23:37:30 -07001661void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001662{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001663 ATRACE_CALL();
1664 ALOGV("preComposition");
1665
Mathias Agopiancd60f992012-08-16 16:28:27 -07001666 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001667 mDrawingState.traverseInZOrder([&](Layer* layer) {
1668 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001669 needExtraInvalidate = true;
1670 }
Robert Carr2047fae2016-11-28 14:09:09 -08001671 });
1672
Mathias Agopiancd60f992012-08-16 16:28:27 -07001673 if (needExtraInvalidate) {
1674 signalLayerUpdate();
1675 }
1676}
1677
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001678void SurfaceFlinger::updateCompositorTiming(
1679 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1680 std::shared_ptr<FenceTime>& presentFenceTime) {
1681 // Update queue of past composite+present times and determine the
1682 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001683 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001684 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001685 while (!getBE().mCompositePresentTimes.empty()) {
1686 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001687 // Cached values should have been updated before calling this method,
1688 // which helps avoid duplicate syscalls.
1689 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1690 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1691 break;
1692 }
1693 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001694 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001695 }
1696
1697 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001698 while (getBE().mCompositePresentTimes.size() > 16) {
1699 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001700 }
1701
Brian Andersond0010582017-03-07 13:20:31 -08001702 setCompositorTimingSnapped(
1703 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1704}
1705
1706void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1707 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001708 // Integer division and modulo round toward 0 not -inf, so we need to
1709 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001710 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001711 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1712 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1713
Brian Andersond0010582017-03-07 13:20:31 -08001714 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1715 if (idealLatency <= 0) {
1716 idealLatency = vsyncInterval;
1717 }
1718
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001719 // Snap the latency to a value that removes scheduling jitter from the
1720 // composition and present times, which often have >1ms of jitter.
1721 // Reducing jitter is important if an app attempts to extrapolate
1722 // something (such as user input) to an accurate diasplay time.
1723 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1724 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001725 nsecs_t bias = vsyncInterval / 2;
1726 int64_t extraVsyncs =
1727 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1728 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1729 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001730
David Sodman99974d22017-11-28 12:04:33 -08001731 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1732 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1733 getBE().mCompositorTiming.interval = vsyncInterval;
1734 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001735}
1736
1737void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001738{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001739 ATRACE_CALL();
1740 ALOGV("postComposition");
1741
Brian Anderson3546a3f2016-07-14 11:51:14 -07001742 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001743 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001744 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001745 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001746 }
1747
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001748 // |mStateLock| not needed as we are on the main thread
1749 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001750
David Sodman73beded2017-11-15 11:56:06 -08001751 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001752 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001753 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001754 glCompositionDoneFenceTime =
1755 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001756 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001757 } else {
1758 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1759 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001760
David Sodman73beded2017-11-15 11:56:06 -08001761 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001762 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001763 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001764 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001765
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001766 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1767 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1768
1769 // We use the refreshStartTime which might be sampled a little later than
1770 // when we started doing work for this frame, but that should be okay
1771 // since updateCompositorTiming has snapping logic.
1772 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001773 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001774 CompositorTiming compositorTiming;
1775 {
David Sodman99974d22017-11-28 12:04:33 -08001776 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1777 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001778 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001779
Robert Carr2047fae2016-11-28 14:09:09 -08001780 mDrawingState.traverseInZOrder([&](Layer* layer) {
1781 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001782 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001783 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001784 recordBufferingStats(layer->getName().string(),
1785 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001786 }
Robert Carr2047fae2016-11-28 14:09:09 -08001787 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001788
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001789 if (presentFenceTime->isValid()) {
1790 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001791 enableHardwareVsync();
1792 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001793 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001794 }
1795 }
1796
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001797 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001798 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001799 enableHardwareVsync();
1800 }
1801 }
1802
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001803 if (mAnimCompositionPending) {
1804 mAnimCompositionPending = false;
1805
Brian Anderson4e606e32017-03-16 15:34:57 -07001806 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001807 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001808 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001809 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001810 // The HWC doesn't support present fences, so use the refresh
1811 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001812 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001813 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001814 mAnimFrameTracker.setActualPresentTime(presentTime);
1815 }
1816 mAnimFrameTracker.advanceFrame();
1817 }
Dan Stozab90cf072015-03-05 11:05:59 -08001818
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001819 mTimeStats.incrementTotalFrames();
1820 if (mHadClientComposition) {
1821 mTimeStats.incrementClientCompositionFrames();
1822 }
1823
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001824 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1825 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001826 return;
1827 }
1828
1829 nsecs_t currentTime = systemTime();
1830 if (mHasPoweredOff) {
1831 mHasPoweredOff = false;
1832 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001833 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001834 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001835 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1836 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001837 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001838 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001839 }
David Sodman4a36e932017-11-07 14:29:47 -08001840 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001841 }
David Sodman4a36e932017-11-07 14:29:47 -08001842 getBE().mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001843}
1844
1845void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001846 ATRACE_CALL();
1847 ALOGV("rebuildLayerStacks");
1848
Mathias Agopiancd60f992012-08-16 16:28:27 -07001849 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001850 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001851 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001852 mVisibleRegionsDirty = false;
1853 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001854
Jeff Sharkey76488112017-02-27 14:15:18 -07001855 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1856 Region opaqueRegion;
1857 Region dirtyRegion;
1858 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001859 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001860 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1861 const Transform& tr(displayDevice->getTransform());
1862 const Rect bounds(displayDevice->getBounds());
1863 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001864 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001865
Jeff Sharkey76488112017-02-27 14:15:18 -07001866 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001867 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001868 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1869 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001870 Region drawRegion(tr.transform(
1871 layer->visibleNonTransparentRegion));
1872 drawRegion.andSelf(bounds);
1873 if (!drawRegion.isEmpty()) {
1874 layersSortedByZ.add(layer);
1875 } else {
1876 // Clear out the HWC layer if this layer was
1877 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001878 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001879 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001880 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001881 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001882 // WM changes displayDevice->layerStack upon sleep/awake.
1883 // Here we make sure we delete the HWC layers even if
1884 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001885 hwcLayerDestroyed = layer->destroyHwcLayer(
1886 displayDevice->getHwcDisplayId());
1887 }
1888
1889 // If a layer is not going to get a release fence because
1890 // it is invisible, but it is also going to release its
1891 // old buffer, add it to the list of layers needing
1892 // fences.
1893 if (hwcLayerDestroyed) {
1894 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1895 mLayersWithQueuedFrames.cend(), layer);
1896 if (found != mLayersWithQueuedFrames.cend()) {
1897 layersNeedingFences.add(layer);
1898 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001899 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001900 });
1901 }
1902 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001903 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001904 displayDevice->undefinedRegion.set(bounds);
1905 displayDevice->undefinedRegion.subtractSelf(
1906 tr.transform(opaqueRegion));
1907 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001908 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001909 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001910}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001911
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001912// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001913// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001914// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001915// - Dataspace::DISPLAY_P3
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001916// The returned HDR data space is one of
1917// - Dataspace::UNKNOWN
1918// - Dataspace::BT2020_HLG
1919// - Dataspace::BT2020_PQ
1920Dataspace SurfaceFlinger::getBestDataspace(
1921 const sp<const DisplayDevice>& displayDevice, Dataspace* outHdrDataSpace) const {
1922 Dataspace bestDataSpace = Dataspace::SRGB;
1923 *outHdrDataSpace = Dataspace::UNKNOWN;
1924
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001925 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu1b6bafc2018-05-22 12:03:00 -07001926 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001927 case Dataspace::V0_SCRGB:
1928 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001929 case Dataspace::DISPLAY_P3:
Chia-I Wu0607fbe2018-05-18 10:59:36 -07001930 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001931 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001932 case Dataspace::BT2020_PQ:
1933 case Dataspace::BT2020_ITU_PQ:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001934 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001935 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001936 case Dataspace::BT2020_HLG:
1937 case Dataspace::BT2020_ITU_HLG:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001938 // When there's mixed PQ content and HLG content, we set the HDR
1939 // data space to be BT2020_PQ and convert HLG to PQ.
1940 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1941 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001942 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001943 break;
1944 default:
1945 break;
1946 }
Romain Guy54f154a2017-10-24 21:40:32 +01001947 }
1948
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001949 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001950}
1951
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001952// Pick the ColorMode / Dataspace for the display device.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001953void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001954 ColorMode* outMode, Dataspace* outDataSpace,
1955 RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001956 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1957 *outMode = ColorMode::NATIVE;
1958 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001959 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001960 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001961 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001962
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001963 Dataspace hdrDataSpace;
1964 Dataspace bestDataSpace = getBestDataspace(displayDevice, &hdrDataSpace);
1965
Peiyong Lin3c6b7ef2018-06-05 10:58:41 -07001966 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001967 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lin3c6b7ef2018-06-05 10:58:41 -07001968 !displayDevice->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001969 if (isHdr) {
1970 bestDataSpace = hdrDataSpace;
1971 }
1972
Chia-I Wu0d711262018-05-21 15:19:35 -07001973 RenderIntent intent;
1974 switch (mDisplayColorSetting) {
1975 case DisplayColorSetting::MANAGED:
1976 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001977 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001978 break;
1979 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001980 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001981 break;
1982 default: // vendor display color setting
1983 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1984 break;
1985 }
Chia-I Wu0607fbe2018-05-18 10:59:36 -07001986
Chia-I Wu0607fbe2018-05-18 10:59:36 -07001987 displayDevice->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001988}
1989
Mathias Agopiancd60f992012-08-16 16:28:27 -07001990void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001991 ATRACE_CALL();
1992 ALOGV("setUpHWComposer");
1993
Jesse Hall028dc8f2013-08-20 16:35:32 -07001994 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07001995 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07001996 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1997 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1998
1999 // If nothing has changed (!dirty), don't recompose.
2000 // If something changed, but we don't currently have any visible layers,
2001 // and didn't when we last did a composition, then skip it this time.
2002 // The second rule does two things:
2003 // - When all layers are removed from a display, we'll emit one black
2004 // frame, then nothing more until we get new layers.
2005 // - When a display is created with a private layer stack, we won't
2006 // emit any black frames until a layer is added to the layer stack.
2007 bool mustRecompose = dirty && !(empty && wasEmpty);
2008
2009 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2010 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
2011 mustRecompose ? "doing" : "skipping",
2012 dirty ? "+" : "-",
2013 empty ? "+" : "-",
2014 wasEmpty ? "+" : "-");
2015
Dan Stoza71433162014-02-04 16:22:36 -08002016 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07002017
2018 if (mustRecompose) {
2019 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
2020 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07002021 }
2022
Dan Stoza9e56aa02015-11-02 13:00:03 -08002023 // build the h/w work list
2024 if (CC_UNLIKELY(mGeometryInvalid)) {
2025 mGeometryInvalid = false;
2026 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2027 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
2028 const auto hwcId = displayDevice->getHwcDisplayId();
2029 if (hwcId >= 0) {
2030 const Vector<sp<Layer>>& currentLayers(
2031 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08002032 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002033 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08002034 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07002035 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002036 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002037 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07002038 }
2039 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07002040
Robert Carrae060832016-11-28 10:51:00 -08002041 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002042 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002043 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07002044 }
2045 }
2046 }
2047 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002048 }
Riley Andrews03414a12014-07-01 14:22:59 -07002049
Dan Stoza9e56aa02015-11-02 13:00:03 -08002050 // Set the per-frame data
2051 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2052 auto& displayDevice = mDisplays[displayId];
2053 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002054
Dan Stoza9e56aa02015-11-02 13:00:03 -08002055 if (hwcId < 0) {
2056 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07002057 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07002058 if (mDrawingState.colorMatrixChanged) {
2059 displayDevice->setColorTransform(mDrawingState.colorMatrix);
2060 status_t result = getBE().mHwc->setColorTransform(hwcId, mDrawingState.colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002061 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2062 "display %zd: %d", displayId, result);
2063 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002064 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu07376a92018-06-05 15:46:58 -07002065 if (layer->isHdrY410()) {
2066 layer->forceClientComposition(hwcId);
2067 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2068 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002069 !displayDevice->hasHDR10Support()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002070 layer->forceClientComposition(hwcId);
Chia-I Wu07376a92018-06-05 15:46:58 -07002071 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2072 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Peiyong Linf59a7192018-04-25 11:19:31 -07002073 !displayDevice->hasHLGSupport()) {
2074 layer->forceClientComposition(hwcId);
2075 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002076
chaviwc9232ed2017-11-14 15:31:15 -08002077 if (layer->getForceClientComposition(hwcId)) {
2078 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2079 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2080 continue;
2081 }
2082
Dan Stoza9e56aa02015-11-02 13:00:03 -08002083 layer->setPerFrameData(displayDevice);
2084 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002085
2086 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002087 ColorMode colorMode;
2088 Dataspace dataSpace;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002089 RenderIntent renderIntent;
2090 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
2091 setActiveColorModeInternal(displayDevice, colorMode, dataSpace, renderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002092 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002093 }
2094
Chia-I Wu28f320b2018-05-03 11:02:56 -07002095 mDrawingState.colorMatrixChanged = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002096
Dan Stoza9e56aa02015-11-02 13:00:03 -08002097 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002098 auto& displayDevice = mDisplays[displayId];
2099 if (!displayDevice->isDisplayOn()) {
2100 continue;
2101 }
2102
David Sodman105b7dc2017-11-04 20:28:14 -07002103 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002104 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2105 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002106 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002107}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002108
Mathias Agopiancd60f992012-08-16 16:28:27 -07002109void SurfaceFlinger::doComposition() {
2110 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002111 ALOGV("doComposition");
2112
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002113 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002114 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002115 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002116 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002117 // transform the dirty region into this screen's coordinate space
2118 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002119
2120 // repaint the framebuffer (if needed)
2121 doDisplayComposition(hw, dirtyRegion);
2122
Mathias Agopiancd60f992012-08-16 16:28:27 -07002123 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002124 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002125 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002126 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002127 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002128}
2129
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002130void SurfaceFlinger::postFramebuffer()
2131{
Mathias Agopian841cde52012-03-01 15:44:37 -08002132 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002133 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002134
Mathias Agopiana44b0412011-10-16 18:46:35 -07002135 const nsecs_t now = systemTime();
2136 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002137
Dan Stoza9e56aa02015-11-02 13:00:03 -08002138 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2139 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002140 if (!displayDevice->isDisplayOn()) {
2141 continue;
2142 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002143 const auto hwcId = displayDevice->getHwcDisplayId();
2144 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002145 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002146 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002147 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002148 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002149 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002150 // The layer buffer from the previous frame (if any) is released
2151 // by HWC only when the release fence from this frame (if any) is
2152 // signaled. Always get the release fence from HWC first.
2153 auto hwcLayer = layer->getHwcLayer(hwcId);
David Sodman105b7dc2017-11-04 20:28:14 -07002154 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002155
2156 // If the layer was client composited in the previous frame, we
2157 // need to merge with the previous client target acquire fence.
2158 // Since we do not track that, always merge with the current
2159 // client target acquire fence when it is available, even though
2160 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002161 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002162 releaseFence = Fence::merge("LayerRelease", releaseFence,
2163 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002164 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002165
Dan Stoza9e56aa02015-11-02 13:00:03 -08002166 layer->onLayerDisplayed(releaseFence);
2167 }
Chia-I Wu83806892017-11-16 10:50:20 -08002168
2169 // We've got a list of layers needing fences, that are disjoint with
2170 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2171 // supply them with the present fence.
2172 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002173 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002174 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2175 layer->onLayerDisplayed(presentFence);
2176 }
2177 }
2178
Dan Stoza9e56aa02015-11-02 13:00:03 -08002179 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002180 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002181 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002182 }
2183
Mathias Agopiana44b0412011-10-16 18:46:35 -07002184 mLastSwapBufferTime = systemTime() - now;
2185 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002186
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002187 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002188 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2189 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2190 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2191 logFrameStats();
2192 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002193 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002194}
2195
Mathias Agopian87baae12012-07-31 12:38:26 -07002196void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002197{
Mathias Agopian841cde52012-03-01 15:44:37 -08002198 ATRACE_CALL();
2199
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002200 // here we keep a copy of the drawing state (that is the state that's
2201 // going to be overwritten by handleTransactionLocked()) outside of
2202 // mStateLock so that the side-effects of the State assignment
2203 // don't happen with mStateLock held (which can cause deadlocks).
2204 State drawingState(mDrawingState);
2205
Mathias Agopianca4d3602011-05-19 15:38:14 -07002206 Mutex::Autolock _l(mStateLock);
2207 const nsecs_t now = systemTime();
2208 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002209
Mathias Agopianca4d3602011-05-19 15:38:14 -07002210 // Here we're guaranteed that some transaction flags are set
2211 // so we can call handleTransactionLocked() unconditionally.
2212 // We call getTransactionFlags(), which will also clear the flags,
2213 // with mStateLock held to guarantee that mCurrentState won't change
2214 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002215
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002216 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002217 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002218 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002219
Mathias Agopianca4d3602011-05-19 15:38:14 -07002220 mLastTransactionTime = systemTime() - now;
2221 mDebugInTransaction = 0;
2222 invalidateHwcGeometry();
2223 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002224}
2225
Lloyd Pique715a2c12017-12-14 17:18:08 -08002226DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique09594832018-01-22 17:48:03 -08002227 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002228 // Figure out whether the event is for the primary display or an
2229 // external display by matching the Hwc display id against one for a
2230 // connected display. If we did not find a match, we then check what
2231 // displays are not already connected to determine the type. If we don't
2232 // have a connected primary display, we assume the new display is meant to
2233 // be the primary display, and then if we don't have an external display,
2234 // we assume it is that.
2235 const auto primaryDisplayId =
2236 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2237 const auto externalDisplayId =
2238 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2239 if (primaryDisplayId && primaryDisplayId == display) {
2240 return DisplayDevice::DISPLAY_PRIMARY;
2241 } else if (externalDisplayId && externalDisplayId == display) {
2242 return DisplayDevice::DISPLAY_EXTERNAL;
2243 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2244 return DisplayDevice::DISPLAY_PRIMARY;
2245 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2246 return DisplayDevice::DISPLAY_EXTERNAL;
2247 }
2248
2249 return DisplayDevice::DISPLAY_ID_INVALID;
2250}
2251
Lloyd Piqueba04e622017-12-14 17:11:26 -08002252void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2253 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002254 auto displayType = determineDisplayType(event.display, event.connection);
2255 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2256 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2257 continue;
2258 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002259
2260 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2261 ALOGE("External displays are not supported by the vr hardware composer.");
2262 continue;
2263 }
2264
Lloyd Pique715a2c12017-12-14 17:18:08 -08002265 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002266
2267 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002268 if (!mBuiltinDisplays[displayType].get()) {
2269 ALOGV("Creating built in display %d", displayType);
2270 mBuiltinDisplays[displayType] = new BBinder();
2271 // All non-virtual displays are currently considered secure.
2272 DisplayDeviceState info(displayType, true);
2273 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2274 "Built-in Screen" : "External Screen";
2275 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4d234852018-01-22 17:21:36 -08002276 mInterceptor->saveDisplayCreation(info);
Steven Thomas3bed0522018-03-20 15:40:48 -07002277 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002278 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002279 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002280
Lloyd Piquefcd86612017-12-14 17:15:36 -08002281 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2282 if (idx >= 0) {
2283 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4d234852018-01-22 17:21:36 -08002284 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002285 mCurrentState.displays.removeItemsAt(idx);
2286 }
2287 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002288 }
2289
2290 processDisplayChangesLocked();
2291 }
2292
2293 mPendingHotplugEvents.clear();
2294}
2295
Lloyd Pique09594832018-01-22 17:48:03 -08002296sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2297 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2298 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002299 bool hasWideColorGamut = false;
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002300 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002301
Lloyd Pique09594832018-01-22 17:48:03 -08002302 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002303 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique09594832018-01-22 17:48:03 -08002304 for (ColorMode colorMode : modes) {
2305 switch (colorMode) {
2306 case ColorMode::DISPLAY_P3:
2307 case ColorMode::ADOBE_RGB:
2308 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002309 hasWideColorGamut = true;
Lloyd Pique09594832018-01-22 17:48:03 -08002310 break;
2311 default:
2312 break;
2313 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002314
2315 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2316 colorMode);
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002317 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique09594832018-01-22 17:48:03 -08002318 }
2319 }
2320
Peiyong Lin62665892018-04-16 11:07:44 -07002321 HdrCapabilities hdrCapabilities;
2322 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
Lloyd Pique09594832018-01-22 17:48:03 -08002323
2324 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2325 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2326
2327 /*
2328 * Create our display's surface
2329 */
2330 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2331 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2332 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2333 renderSurface->setNativeWindow(nativeWindow.get());
2334 const int displayWidth = renderSurface->queryWidth();
2335 const int displayHeight = renderSurface->queryHeight();
2336
2337 // Make sure that composition can never be stalled by a virtual display
2338 // consumer that isn't processing buffers fast enough. We have to do this
2339 // in two places:
2340 // * Here, in case the display is composed entirely by HWC.
2341 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2342 // window's swap interval in eglMakeCurrent, so they'll override the
2343 // interval we set here.
2344 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2345 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2346 }
2347
2348 // virtual displays are always considered enabled
2349 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2350 : HWC_POWER_MODE_OFF;
2351
2352 sp<DisplayDevice> hw =
2353 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2354 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin2c327ac2018-04-19 22:06:34 -07002355 hasWideColorGamut, hdrCapabilities,
2356 getHwComposer().getSupportedPerFrameMetadata(hwcId),
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002357 hwcColorModes, initialPowerMode);
Lloyd Pique09594832018-01-22 17:48:03 -08002358
2359 if (maxFrameBufferAcquiredBuffers >= 3) {
2360 nativeWindowSurface->preallocateBuffers();
2361 }
2362
2363 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002364 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2365 if (hasWideColorGamut) {
Lloyd Pique09594832018-01-22 17:48:03 -08002366 defaultColorMode = ColorMode::SRGB;
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002367 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique09594832018-01-22 17:48:03 -08002368 }
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002369 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace,
2370 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002371 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
2372 hw->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
2373 }
Lloyd Pique09594832018-01-22 17:48:03 -08002374 hw->setLayerStack(state.layerStack);
2375 hw->setProjection(state.orientation, state.viewport, state.frame);
2376 hw->setDisplayName(state.displayName);
2377
2378 return hw;
2379}
2380
Lloyd Pique347200f2017-12-14 17:00:15 -08002381void SurfaceFlinger::processDisplayChangesLocked() {
2382 // here we take advantage of Vector's copy-on-write semantics to
2383 // improve performance by skipping the transaction entirely when
2384 // know that the lists are identical
2385 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2386 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2387 if (!curr.isIdenticalTo(draw)) {
2388 mVisibleRegionsDirty = true;
2389 const size_t cc = curr.size();
2390 size_t dc = draw.size();
2391
2392 // find the displays that were removed
2393 // (ie: in drawing state but not in current state)
2394 // also handle displays that changed
2395 // (ie: displays that are in both lists)
2396 for (size_t i = 0; i < dc;) {
2397 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2398 if (j < 0) {
2399 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002400 // Call makeCurrent() on the primary display so we can
2401 // be sure that nothing associated with this display
2402 // is current.
2403 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2404 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2405 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2406 if (hw != nullptr) hw->disconnect(getHwComposer());
2407 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2408 mEventThread->onHotplugReceived(draw[i].type, false);
2409 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002410 } else {
2411 // this display is in both lists. see if something changed.
2412 const DisplayDeviceState& state(curr[j]);
2413 const wp<IBinder>& display(curr.keyAt(j));
2414 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2415 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2416 if (state_binder != draw_binder) {
2417 // changing the surface is like destroying and
2418 // recreating the DisplayDevice, so we just remove it
2419 // from the drawing state, so that it get re-added
2420 // below.
2421 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2422 if (hw != nullptr) hw->disconnect(getHwComposer());
2423 mDisplays.removeItem(display);
2424 mDrawingState.displays.removeItemsAt(i);
2425 dc--;
2426 // at this point we must loop to the next item
2427 continue;
2428 }
2429
2430 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2431 if (disp != nullptr) {
2432 if (state.layerStack != draw[i].layerStack) {
2433 disp->setLayerStack(state.layerStack);
2434 }
2435 if ((state.orientation != draw[i].orientation) ||
2436 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2437 disp->setProjection(state.orientation, state.viewport, state.frame);
2438 }
2439 if (state.width != draw[i].width || state.height != draw[i].height) {
2440 disp->setDisplaySize(state.width, state.height);
2441 }
2442 }
2443 }
2444 ++i;
2445 }
2446
2447 // find displays that were added
2448 // (ie: in current state but not in drawing state)
2449 for (size_t i = 0; i < cc; i++) {
2450 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2451 const DisplayDeviceState& state(curr[i]);
2452
2453 sp<DisplaySurface> dispSurface;
2454 sp<IGraphicBufferProducer> producer;
2455 sp<IGraphicBufferProducer> bqProducer;
2456 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002457 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002458
2459 int32_t hwcId = -1;
2460 if (state.isVirtualDisplay()) {
2461 // Virtual displays without a surface are dormant:
2462 // they have external state (layer stack, projection,
2463 // etc.) but no internal state (i.e. a DisplayDevice).
2464 if (state.surface != nullptr) {
2465 // Allow VR composer to use virtual displays.
2466 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2467 int width = 0;
2468 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2469 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2470 int height = 0;
2471 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2472 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2473 int intFormat = 0;
2474 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2475 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002476 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002477
2478 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2479 }
2480
2481 // TODO: Plumb requested format back up to consumer
2482
2483 sp<VirtualDisplaySurface> vds =
2484 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2485 bqProducer, bqConsumer,
2486 state.displayName);
2487
2488 dispSurface = vds;
2489 producer = vds;
2490 }
2491 } else {
2492 ALOGE_IF(state.surface != nullptr,
2493 "adding a supported display, but rendering "
2494 "surface is provided (%p), ignoring it",
2495 state.surface.get());
2496
2497 hwcId = state.type;
2498 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2499 producer = bqProducer;
2500 }
2501
2502 const wp<IBinder>& display(curr.keyAt(i));
2503 if (dispSurface != nullptr) {
Lloyd Pique09594832018-01-22 17:48:03 -08002504 mDisplays.add(display,
2505 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2506 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002507 if (!state.isVirtualDisplay()) {
2508 mEventThread->onHotplugReceived(state.type, true);
2509 }
2510 }
2511 }
2512 }
2513 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002514
2515 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002516}
2517
Mathias Agopian87baae12012-07-31 12:38:26 -07002518void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002519{
Dan Stoza7dde5992015-05-22 09:51:44 -07002520 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002521 mCurrentState.traverseInZOrder([](Layer* layer) {
2522 layer->notifyAvailableFrames();
2523 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002524
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002525 /*
2526 * Traversal of the children
2527 * (perform the transaction for each of them if needed)
2528 */
2529
Mathias Agopian3559b072012-08-15 13:46:03 -07002530 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002531 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002532 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002533 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002534
2535 const uint32_t flags = layer->doTransaction(0);
2536 if (flags & Layer::eVisibleRegion)
2537 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002538 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002539 }
2540
2541 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002542 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002543 */
2544
Mathias Agopiane57f2922012-08-09 16:29:12 -07002545 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002546 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002547 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002548 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002549
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002550 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002551 // The transform hint might have changed for some layers
2552 // (either because a display has changed, or because a layer
2553 // as changed).
2554 //
2555 // Walk through all the layers in currentLayers,
2556 // and update their transform hint.
2557 //
2558 // If a layer is visible only on a single display, then that
2559 // display is used to calculate the hint, otherwise we use the
2560 // default display.
2561 //
2562 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2563 // the hint is set before we acquire a buffer from the surface texture.
2564 //
2565 // NOTE: layer transactions have taken place already, so we use their
2566 // drawing state. However, SurfaceFlinger's own transaction has not
2567 // happened yet, so we must use the current state layer list
2568 // (soon to become the drawing state list).
2569 //
2570 sp<const DisplayDevice> disp;
2571 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002572 bool first = true;
2573 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002574 // NOTE: we rely on the fact that layers are sorted by
2575 // layerStack first (so we don't have to traverse the list
2576 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002577 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002578 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002579 currentlayerStack = layerStack;
2580 // figure out if this layerstack is mirrored
2581 // (more than one display) if so, pick the default display,
2582 // if not, pick the only display it's on.
2583 disp.clear();
2584 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2585 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002586 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002587 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002588 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002589 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002590 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002591 break;
2592 }
2593 }
2594 }
2595 }
Chet Haase91d25932013-04-11 15:24:55 -07002596
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002597 if (disp == nullptr) {
2598 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2599 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002600
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002601 // could be null when this layer is using a layerStack
2602 // that is not visible on any display. Also can occur at
2603 // screen off/on times.
2604 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002605 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002606
2607 // disp can be null if there is no display available at all to get
2608 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002609 if (disp != nullptr) {
2610 layer->updateTransformHint(disp);
2611 }
Robert Carr2047fae2016-11-28 14:09:09 -08002612
2613 first = false;
2614 });
Mathias Agopian84300952012-11-21 16:02:13 -08002615 }
2616
2617
Mathias Agopian3559b072012-08-15 13:46:03 -07002618 /*
2619 * Perform our own transaction if needed
2620 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002621
2622 if (mLayersAdded) {
2623 mLayersAdded = false;
2624 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002625 mVisibleRegionsDirty = true;
2626 }
2627
2628 // some layers might have been removed, so
2629 // we need to update the regions they're exposing.
2630 if (mLayersRemoved) {
2631 mLayersRemoved = false;
2632 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002633 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002634 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002635 // this layer is not visible anymore
2636 // TODO: we could traverse the tree from front to back and
2637 // compute the actual visible region
2638 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002639 Region visibleReg;
2640 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002641 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002642 }
Robert Carr2047fae2016-11-28 14:09:09 -08002643 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002644 }
2645
2646 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002647
2648 updateCursorAsync();
2649}
2650
2651void SurfaceFlinger::updateCursorAsync()
2652{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002653 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2654 auto& displayDevice = mDisplays[displayId];
2655 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002656 continue;
2657 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002658
2659 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2660 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002661 }
2662 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002663}
2664
2665void SurfaceFlinger::commitTransaction()
2666{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002667 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002668 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002669 for (const auto& l : mLayersPendingRemoval) {
2670 recordBufferingStats(l->getName().string(),
2671 l->getOccupancyHistory(true));
2672 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002673 }
2674 mLayersPendingRemoval.clear();
2675 }
2676
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002677 // If this transaction is part of a window animation then the next frame
2678 // we composite should be considered an animation as well.
2679 mAnimCompositionPending = mAnimTransactionPending;
2680
Mathias Agopian4fec8732012-06-29 14:12:52 -07002681 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002682 // clear the "changed" flags in current state
2683 mCurrentState.colorMatrixChanged = false;
2684
Robert Carr1f0a16a2016-10-24 16:27:39 -07002685 mDrawingState.traverseInZOrder([](Layer* layer) {
2686 layer->commitChildList();
2687 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002688 mTransactionPending = false;
2689 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002690 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002691}
2692
Chia-I Wuab0c3192017-08-01 11:29:00 -07002693void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002694 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002695{
Mathias Agopian841cde52012-03-01 15:44:37 -08002696 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002697 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002698
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002699 Region aboveOpaqueLayers;
2700 Region aboveCoveredLayers;
2701 Region dirty;
2702
Mathias Agopian87baae12012-07-31 12:38:26 -07002703 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002704
Robert Carr2047fae2016-11-28 14:09:09 -08002705 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002706 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002707 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002708
Jesse Hall01e29052013-02-19 16:13:35 -08002709 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002710 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002711 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002712
Mathias Agopianab028732010-03-16 16:41:46 -07002713 /*
2714 * opaqueRegion: area of a surface that is fully opaque.
2715 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002716 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002717
2718 /*
2719 * visibleRegion: area of a surface that is visible on screen
2720 * and not fully transparent. This is essentially the layer's
2721 * footprint minus the opaque regions above it.
2722 * Areas covered by a translucent surface are considered visible.
2723 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002724 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002725
2726 /*
2727 * coveredRegion: area of a surface that is covered by all
2728 * visible regions above it (which includes the translucent areas).
2729 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002730 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002731
Jesse Halla8026d22012-09-25 13:25:04 -07002732 /*
2733 * transparentRegion: area of a surface that is hinted to be completely
2734 * transparent. This is only used to tell when the layer has no visible
2735 * non-transparent regions and can be removed from the layer list. It
2736 * does not affect the visibleRegion of this layer or any layers
2737 * beneath it. The hint may not be correct if apps don't respect the
2738 * SurfaceView restrictions (which, sadly, some don't).
2739 */
2740 Region transparentRegion;
2741
Mathias Agopianab028732010-03-16 16:41:46 -07002742
2743 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002744 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002745 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002746 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002747 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002748 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002749 if (!visibleRegion.isEmpty()) {
2750 // Remove the transparent area from the visible region
2751 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002752 if (tr.preserveRects()) {
2753 // transform the transparent region
2754 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002755 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002756 // transformation too complex, can't do the
2757 // transparent region optimization.
2758 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002759 }
Mathias Agopianab028732010-03-16 16:41:46 -07002760 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002761
Mathias Agopianab028732010-03-16 16:41:46 -07002762 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002763 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002764 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002765 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2766 // the opaque region is the layer's footprint
2767 opaqueRegion = visibleRegion;
2768 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002769 }
2770 }
2771
Robert Carre5f4f692018-01-12 13:12:28 -08002772 if (visibleRegion.isEmpty()) {
2773 layer->clearVisibilityRegions();
2774 return;
2775 }
2776
Mathias Agopianab028732010-03-16 16:41:46 -07002777 // Clip the covered region to the visible region
2778 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2779
2780 // Update aboveCoveredLayers for next (lower) layer
2781 aboveCoveredLayers.orSelf(visibleRegion);
2782
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002783 // subtract the opaque region covered by the layers above us
2784 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002785
2786 // compute this layer's dirty region
2787 if (layer->contentDirty) {
2788 // we need to invalidate the whole region
2789 dirty = visibleRegion;
2790 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002791 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002792 layer->contentDirty = false;
2793 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002794 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002795 * the exposed region consists of two components:
2796 * 1) what's VISIBLE now and was COVERED before
2797 * 2) what's EXPOSED now less what was EXPOSED before
2798 *
2799 * note that (1) is conservative, we start with the whole
2800 * visible region but only keep what used to be covered by
2801 * something -- which mean it may have been exposed.
2802 *
2803 * (2) handles areas that were not covered by anything but got
2804 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002805 */
Mathias Agopianab028732010-03-16 16:41:46 -07002806 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002807 const Region oldVisibleRegion = layer->visibleRegion;
2808 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002809 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2810 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002811 }
2812 dirty.subtractSelf(aboveOpaqueLayers);
2813
2814 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002815 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002816
Mathias Agopianab028732010-03-16 16:41:46 -07002817 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002818 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002819
Jesse Halla8026d22012-09-25 13:25:04 -07002820 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002821 layer->setVisibleRegion(visibleRegion);
2822 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002823 layer->setVisibleNonTransparentRegion(
2824 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002825 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002826
Mathias Agopian87baae12012-07-31 12:38:26 -07002827 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002828}
2829
Chia-I Wuab0c3192017-08-01 11:29:00 -07002830void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002831 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002832 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002833 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002834 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002835 }
2836 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002837}
2838
Dan Stoza6b9454d2014-11-07 16:00:59 -08002839bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002840{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002841 ALOGV("handlePageFlip");
2842
Brian Andersond6927fb2016-07-23 23:37:30 -07002843 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002844
Mathias Agopian4fec8732012-06-29 14:12:52 -07002845 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002846 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002847 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002848
2849 // Store the set of layers that need updates. This set must not change as
2850 // buffers are being latched, as this could result in a deadlock.
2851 // Example: Two producers share the same command stream and:
2852 // 1.) Layer 0 is latched
2853 // 2.) Layer 0 gets a new frame
2854 // 2.) Layer 1 gets a new frame
2855 // 3.) Layer 1 is latched.
2856 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2857 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002858 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002859 if (layer->hasQueuedFrame()) {
2860 frameQueued = true;
2861 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002862 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002863 } else {
2864 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002865 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002866 } else {
2867 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002868 }
Robert Carr2047fae2016-11-28 14:09:09 -08002869 });
2870
Dan Stoza9e56aa02015-11-02 13:00:03 -08002871 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002872 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002873 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002874 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002875 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002876 newDataLatched = true;
2877 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002878 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002879
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002880 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002881
2882 // If we will need to wake up at some time in the future to deal with a
2883 // queued frame that shouldn't be displayed during this vsync period, wake
2884 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002885 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002886 signalLayerUpdate();
2887 }
2888
2889 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002890 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002891}
2892
Mathias Agopianad456f92011-01-13 17:53:01 -08002893void SurfaceFlinger::invalidateHwcGeometry()
2894{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002895 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002896}
2897
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002898
Fabien Sanglard830b8472016-11-30 16:35:58 -08002899void SurfaceFlinger::doDisplayComposition(
2900 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002901 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002902{
Dan Stoza71433162014-02-04 16:22:36 -08002903 // We only need to actually compose the display if:
2904 // 1) It is being handled by hardware composer, which may need this to
2905 // keep its virtual display state machine in sync, or
2906 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002907 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002908 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002909 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002910 return;
2911 }
2912
Dan Stoza9e56aa02015-11-02 13:00:03 -08002913 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002914 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002915
2916 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002917 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002918}
2919
Chia-I Wub02087d2017-11-09 10:19:54 -08002920bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002921{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002922 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002923
Chia-I Wub02087d2017-11-09 10:19:54 -08002924 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002925 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002926 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002927 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002928 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002929
Chia-I Wu8e50e692018-05-04 10:12:37 -07002930 bool applyColorMatrix = false;
Chia-I Wu6d844112018-06-27 07:17:41 +08002931 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002932
Dan Stoza9e56aa02015-11-02 13:00:03 -08002933 if (hasClientComposition) {
2934 ALOGV("hasClientComposition");
2935
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002936 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002937 if (displayDevice->hasWideColorGamut()) {
2938 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002939 }
2940 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002941 getBE().mRenderEngine->setDisplayMaxLuminance(
2942 displayDevice->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002943
Chia-I Wu8e50e692018-05-04 10:12:37 -07002944 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
2945 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2946 HWC2::Capability::SkipClientColorTransform);
2947
Chia-I Wu6d844112018-06-27 07:17:41 +08002948 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002949 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2950 if (applyColorMatrix) {
Chia-I Wu6d844112018-06-27 07:17:41 +08002951 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002952 }
2953
Chia-I Wu6d844112018-06-27 07:17:41 +08002954 // The current enhanced saturation matrix is designed to enhance Display P3,
2955 // thus we only apply this matrix when the render intent is not colorimetric
2956 // and the output color space is Display P3.
2957 needsEnhancedColorMatrix =
Chia-I Wu0d711262018-05-21 15:19:35 -07002958 (displayDevice->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
Chia-I Wu6d844112018-06-27 07:17:41 +08002959 outputDataspace == Dataspace::DISPLAY_P3);
2960 if (needsEnhancedColorMatrix) {
2961 colorMatrix *= mEnhancedSaturationMatrix;
2962 }
2963
2964 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002965
Chia-I Wu7f402902017-11-09 12:51:10 -08002966 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002967 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002968 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08002969 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002970
2971 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08002972 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002973 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2974 }
2975 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002976 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002977
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002978 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002979 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002980 // when using overlays, we assume a fully transparent framebuffer
2981 // NOTE: we could reduce how much we need to clear, for instance
2982 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002983 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002984 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002985 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002986 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002987 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002988 // we're left with the letterbox region
2989 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002990 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002991
2992 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002993 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002994
Mathias Agopianb9494d52012-04-18 02:28:45 -07002995 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002996 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002997 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002998 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002999 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003000 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003001
Dan Stoza9e56aa02015-11-02 13:00:03 -08003002 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07003003 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07003004 // scissor on the main display. It should never be needed
3005 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08003006 const Rect& bounds(displayDevice->getBounds());
3007 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003008 if (scissor != bounds) {
3009 // scissor doesn't match the screen's dimensions, so we
3010 // need to clear everything outside of it and enable
3011 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003012
Mathias Agopianf45c5102012-10-24 16:29:17 -07003013 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08003014 const uint32_t height = displayDevice->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08003015 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07003016 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003017 }
3018 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003019 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003020
Mathias Agopian85d751c2012-08-29 16:59:24 -07003021 /*
3022 * and then, render the layers targeted at the framebuffer
3023 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003024
Dan Stoza9e56aa02015-11-02 13:00:03 -08003025 ALOGV("Rendering client layers");
3026 const Transform& displayTransform = displayDevice->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003027 bool firstLayer = true;
3028 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3029 const Region clip(bounds.intersect(
3030 displayTransform.transform(layer->visibleRegion)));
3031 ALOGV("Layer: %s", layer->getName().string());
3032 ALOGV(" Composition type: %s",
3033 to_string(layer->getCompositionType(hwcId)).c_str());
3034 if (!clip.isEmpty()) {
3035 switch (layer->getCompositionType(hwcId)) {
3036 case HWC2::Composition::Cursor:
3037 case HWC2::Composition::Device:
3038 case HWC2::Composition::Sideband:
3039 case HWC2::Composition::SolidColor: {
3040 const Layer::State& state(layer->getDrawingState());
3041 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
3042 layer->isOpaque(state) && (state.color.a == 1.0f)
3043 && hasClientComposition) {
3044 // never clear the very first layer since we're
3045 // guaranteed the FB is already cleared
3046 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003047 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003048 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003049 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003050 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003051 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003052 break;
3053 }
3054 default:
3055 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003056 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003057 } else {
3058 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003059 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003060 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003061 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003062
Chia-I Wu6d844112018-06-27 07:17:41 +08003063 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003064 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003065 }
3066
Mathias Agopianf45c5102012-10-24 16:29:17 -07003067 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003068 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003069 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003070}
3071
Fabien Sanglard830b8472016-11-30 16:35:58 -08003072void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3073 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003074 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003075 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003076}
3077
Dan Stoza7d89d062015-04-30 13:29:25 -07003078status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003079 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003080 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003081 const sp<Layer>& lbc,
3082 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003083{
Dan Stoza7d89d062015-04-30 13:29:25 -07003084 // add this layer to the current state list
3085 {
3086 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003087 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003088 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3089 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003090 return NO_MEMORY;
3091 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003092 if (parent == nullptr) {
3093 mCurrentState.layersSortedByZ.add(lbc);
3094 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003095 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003096 ALOGE("addClientLayer called with a removed parent");
3097 return NAME_NOT_FOUND;
3098 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003099 parent->addChild(lbc);
3100 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003101
Yiwei Zhang243b3782018-05-15 17:40:04 -07003102 if (gbc != nullptr) {
3103 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3104 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3105 mMaxGraphicBufferProducerListSize,
3106 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3107 mGraphicBufferProducerList.size(),
3108 mMaxGraphicBufferProducerListSize, mNumLayers);
3109 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003110 mLayersAdded = true;
3111 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003112 }
3113
Mathias Agopian96f08192010-06-02 23:28:45 -07003114 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003115 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003116
Dan Stoza7d89d062015-04-30 13:29:25 -07003117 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003118}
3119
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003120status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003121 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003122 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3123}
Robert Carr7f9b8992017-03-10 11:08:39 -08003124
chaviwca27f252018-02-06 16:46:39 -08003125status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3126 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003127 if (layer->isPendingRemoval()) {
3128 return NO_ERROR;
3129 }
3130
Robert Carr1f0a16a2016-10-24 16:27:39 -07003131 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003132 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003133 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003134 if (topLevelOnly) {
3135 return NO_ERROR;
3136 }
3137
Chia-I Wu98f1c102017-05-30 14:54:08 -07003138 sp<Layer> ancestor = p;
3139 while (ancestor->getParent() != nullptr) {
3140 ancestor = ancestor->getParent();
3141 }
3142 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3143 ALOGE("removeLayer called with a layer whose parent has been removed");
3144 return NAME_NOT_FOUND;
3145 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003146
3147 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003148 } else {
3149 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003150 }
3151
Robert Carr136e2f62017-02-08 17:54:29 -08003152 // As a matter of normal operation, the LayerCleaner will produce a second
3153 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3154 // so we will succeed in promoting it, but it's already been removed
3155 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3156 // otherwise something has gone wrong and we are leaking the layer.
3157 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003158 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3159 layer->getName().string(),
3160 (p != nullptr) ? p->getName().string() : "no-parent");
3161 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003162 } else if (index < 0) {
3163 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003164 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003165
Chia-I Wuc6657022017-08-15 11:18:17 -07003166 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003167 mLayersPendingRemoval.add(layer);
3168 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003169 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003170 setTransactionFlags(eTransactionNeeded);
3171 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003172}
3173
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003174uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003175 return android_atomic_release_load(&mTransactionFlags);
3176}
3177
Mathias Agopian3f844832013-08-07 21:24:32 -07003178uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003179 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3180}
3181
Mathias Agopian3f844832013-08-07 21:24:32 -07003182uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza2713c302018-03-28 17:07:36 -07003183 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3184}
3185
3186uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3187 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003188 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza2713c302018-03-28 17:07:36 -07003189 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003190 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003191 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003192 }
3193 return old;
3194}
3195
chaviwca27f252018-02-06 16:46:39 -08003196bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3197 for (const ComposerState& state : states) {
3198 // Here we need to check that the interface we're given is indeed
3199 // one of our own. A malicious client could give us a nullptr
3200 // IInterface, or one of its own or even one of our own but a
3201 // different type. All these situations would cause us to crash.
3202 if (state.client == nullptr) {
3203 return true;
3204 }
3205
3206 sp<IBinder> binder = IInterface::asBinder(state.client);
3207 if (binder == nullptr) {
3208 return true;
3209 }
3210
3211 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3212 return true;
3213 }
3214 }
3215 return false;
3216}
3217
Mathias Agopian8b33f032012-07-24 20:43:54 -07003218void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003219 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003220 const Vector<DisplayState>& displays,
3221 uint32_t flags)
3222{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003223 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003224 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003225 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003226
chaviwca27f252018-02-06 16:46:39 -08003227 if (containsAnyInvalidClientState(states)) {
3228 return;
3229 }
3230
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003231 if (flags & eAnimation) {
3232 // For window updates that are part of an animation we must wait for
3233 // previous animation "frames" to be handled.
3234 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003235 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003236 if (CC_UNLIKELY(err != NO_ERROR)) {
3237 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003238 // caller after a few seconds.
3239 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3240 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003241 mAnimTransactionPending = false;
3242 break;
3243 }
3244 }
3245 }
3246
chaviwca27f252018-02-06 16:46:39 -08003247 for (const DisplayState& display : displays) {
3248 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003249 }
3250
chaviwca27f252018-02-06 16:46:39 -08003251 for (const ComposerState& state : states) {
3252 transactionFlags |= setClientStateLocked(state);
3253 }
3254
3255 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3256 // as destroyed should only occur after setting all other states. This is to allow for a
3257 // child re-parent to happen before marking its original parent as destroyed (which would
3258 // then mark the child as destroyed).
3259 for (const ComposerState& state : states) {
3260 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003261 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003262
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003263 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3264 // anyway. This can be used as a flush mechanism for previous async transactions.
3265 // Empty animation transaction can be used to simulate back-pressure, so also force a
3266 // transaction for empty animation transactions.
3267 if (transactionFlags == 0 &&
3268 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003269 transactionFlags = eTransactionNeeded;
3270 }
3271
Mathias Agopian386aa982011-11-07 21:58:03 -08003272 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003273 if (mInterceptor->isEnabled()) {
3274 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003275 }
Irvel468051e2016-06-13 16:44:44 -07003276
Mathias Agopian386aa982011-11-07 21:58:03 -08003277 // this triggers the transaction
Dan Stoza2713c302018-03-28 17:07:36 -07003278 const auto start = (flags & eEarlyWakeup)
3279 ? VSyncModulator::TransactionStart::EARLY
3280 : VSyncModulator::TransactionStart::NORMAL;
3281 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003282
3283 // if this is a synchronous transaction, wait for it to take effect
3284 // before returning.
3285 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003286 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003287 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003288 if (flags & eAnimation) {
3289 mAnimTransactionPending = true;
3290 }
3291 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003292 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3293 if (CC_UNLIKELY(err != NO_ERROR)) {
3294 // just in case something goes wrong in SF, return to the
3295 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003296 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3297 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003298 break;
3299 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003300 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003301 }
3302}
3303
Mathias Agopiane57f2922012-08-09 16:29:12 -07003304uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3305{
Jesse Hall9a143922012-10-04 16:29:19 -07003306 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3307 if (dpyIdx < 0)
3308 return 0;
3309
Mathias Agopiane57f2922012-08-09 16:29:12 -07003310 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003311 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003312 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003313 const uint32_t what = s.what;
3314 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003315 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003316 disp.surface = s.surface;
3317 flags |= eDisplayTransactionNeeded;
3318 }
3319 }
3320 if (what & DisplayState::eLayerStackChanged) {
3321 if (disp.layerStack != s.layerStack) {
3322 disp.layerStack = s.layerStack;
3323 flags |= eDisplayTransactionNeeded;
3324 }
3325 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003326 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003327 if (disp.orientation != s.orientation) {
3328 disp.orientation = s.orientation;
3329 flags |= eDisplayTransactionNeeded;
3330 }
3331 if (disp.frame != s.frame) {
3332 disp.frame = s.frame;
3333 flags |= eDisplayTransactionNeeded;
3334 }
3335 if (disp.viewport != s.viewport) {
3336 disp.viewport = s.viewport;
3337 flags |= eDisplayTransactionNeeded;
3338 }
3339 }
Michael Lentine47e45402014-07-18 15:34:25 -07003340 if (what & DisplayState::eDisplaySizeChanged) {
3341 if (disp.width != s.width) {
3342 disp.width = s.width;
3343 flags |= eDisplayTransactionNeeded;
3344 }
3345 if (disp.height != s.height) {
3346 disp.height = s.height;
3347 flags |= eDisplayTransactionNeeded;
3348 }
3349 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003350 }
3351 return flags;
3352}
3353
Robert Carrd4ae7f32018-06-07 16:10:57 -07003354bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3355 IPCThreadState* ipc = IPCThreadState::self();
3356 const int pid = ipc->getCallingPid();
3357 const int uid = ipc->getCallingUid();
3358
3359 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3360 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3361 return false;
3362 }
3363 return true;
3364}
3365
chaviwca27f252018-02-06 16:46:39 -08003366uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3367 const layer_state_t& s = composerState.state;
3368 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3369
Mathias Agopian13127d82013-03-05 17:47:11 -08003370 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003371 if (layer == nullptr) {
3372 return 0;
3373 }
3374
3375 if (layer->isPendingRemoval()) {
3376 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3377 return 0;
3378 }
3379
3380 uint32_t flags = 0;
3381
3382 const uint32_t what = s.what;
3383 bool geometryAppliesWithResize =
3384 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003385
3386 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3387 // pending state will also be deferred.
3388 if (what & layer_state_t::eDeferTransaction) {
3389 layer->pushPendingState();
3390 }
3391
chaviw8b3871a2017-11-01 17:41:01 -07003392 if (what & layer_state_t::ePositionChanged) {
3393 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3394 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003395 }
chaviw8b3871a2017-11-01 17:41:01 -07003396 }
3397 if (what & layer_state_t::eLayerChanged) {
3398 // NOTE: index needs to be calculated before we update the state
3399 const auto& p = layer->getParent();
3400 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003401 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003402 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003403 mCurrentState.layersSortedByZ.removeAt(idx);
3404 mCurrentState.layersSortedByZ.add(layer);
3405 // we need traversal (state changed)
3406 // AND transaction (list changed)
3407 flags |= eTransactionNeeded|eTraversalNeeded;
3408 }
chaviw8b3871a2017-11-01 17:41:01 -07003409 } else {
3410 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003411 flags |= eTransactionNeeded|eTraversalNeeded;
3412 }
3413 }
chaviw8b3871a2017-11-01 17:41:01 -07003414 }
3415 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003416 // NOTE: index needs to be calculated before we update the state
3417 const auto& p = layer->getParent();
3418 if (p == nullptr) {
3419 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3420 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3421 mCurrentState.layersSortedByZ.removeAt(idx);
3422 mCurrentState.layersSortedByZ.add(layer);
3423 // we need traversal (state changed)
3424 // AND transaction (list changed)
3425 flags |= eTransactionNeeded|eTraversalNeeded;
3426 }
3427 } else {
3428 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3429 flags |= eTransactionNeeded|eTraversalNeeded;
3430 }
chaviw8b3871a2017-11-01 17:41:01 -07003431 }
3432 }
3433 if (what & layer_state_t::eSizeChanged) {
3434 if (layer->setSize(s.w, s.h)) {
3435 flags |= eTraversalNeeded;
3436 }
3437 }
3438 if (what & layer_state_t::eAlphaChanged) {
3439 if (layer->setAlpha(s.alpha))
3440 flags |= eTraversalNeeded;
3441 }
3442 if (what & layer_state_t::eColorChanged) {
3443 if (layer->setColor(s.color))
3444 flags |= eTraversalNeeded;
3445 }
3446 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003447 // TODO: b/109894387
3448 //
3449 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3450 // rotation. To see the problem observe that if we have a square parent, and a child
3451 // of the same size, then we rotate the child 45 degrees around it's center, the child
3452 // must now be cropped to a non rectangular 8 sided region.
3453 //
3454 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3455 // private API, and the WindowManager only uses rotation in one case, which is on a top
3456 // level layer in which cropping is not an issue.
3457 //
3458 // However given that abuse of rotation matrices could lead to surfaces extending outside
3459 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3460 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3461 // transformations.
3462 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003463 flags |= eTraversalNeeded;
3464 }
3465 if (what & layer_state_t::eTransparentRegionChanged) {
3466 if (layer->setTransparentRegionHint(s.transparentRegion))
3467 flags |= eTraversalNeeded;
3468 }
3469 if (what & layer_state_t::eFlagsChanged) {
3470 if (layer->setFlags(s.flags, s.mask))
3471 flags |= eTraversalNeeded;
3472 }
3473 if (what & layer_state_t::eCropChanged) {
3474 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3475 flags |= eTraversalNeeded;
3476 }
3477 if (what & layer_state_t::eFinalCropChanged) {
3478 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3479 flags |= eTraversalNeeded;
3480 }
3481 if (what & layer_state_t::eLayerStackChanged) {
3482 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3483 // We only allow setting layer stacks for top level layers,
3484 // everything else inherits layer stack from its parent.
3485 if (layer->hasParent()) {
3486 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3487 layer->getName().string());
3488 } else if (idx < 0) {
3489 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3490 "that also does not appear in the top level layer list. Something"
3491 " has gone wrong.", layer->getName().string());
3492 } else if (layer->setLayerStack(s.layerStack)) {
3493 mCurrentState.layersSortedByZ.removeAt(idx);
3494 mCurrentState.layersSortedByZ.add(layer);
3495 // we need traversal (state changed)
3496 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003497 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003498 }
3499 }
3500 if (what & layer_state_t::eDeferTransaction) {
3501 if (s.barrierHandle != nullptr) {
3502 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3503 } else if (s.barrierGbp != nullptr) {
3504 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3505 if (authenticateSurfaceTextureLocked(gbp)) {
3506 const auto& otherLayer =
3507 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3508 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3509 } else {
3510 ALOGE("Attempt to defer transaction to to an"
3511 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003512 }
3513 }
chaviw8b3871a2017-11-01 17:41:01 -07003514 // We don't trigger a traversal here because if no other state is
3515 // changed, we don't want this to cause any more work
3516 }
3517 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003518 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003519 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003520 if (!hadParent) {
3521 mCurrentState.layersSortedByZ.remove(layer);
3522 }
chaviw8b3871a2017-11-01 17:41:01 -07003523 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003524 }
chaviw8b3871a2017-11-01 17:41:01 -07003525 }
3526 if (what & layer_state_t::eReparentChildren) {
3527 if (layer->reparentChildren(s.reparentHandle)) {
3528 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003529 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003530 }
chaviw8b3871a2017-11-01 17:41:01 -07003531 if (what & layer_state_t::eDetachChildren) {
3532 layer->detachChildren();
3533 }
3534 if (what & layer_state_t::eOverrideScalingModeChanged) {
3535 layer->setOverrideScalingMode(s.overrideScalingMode);
3536 // We don't trigger a traversal here because if no other state is
3537 // changed, we don't want this to cause any more work
3538 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003539 return flags;
3540}
3541
chaviwca27f252018-02-06 16:46:39 -08003542void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3543 const layer_state_t& state = composerState.state;
3544 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3545
3546 sp<Layer> layer(client->getLayerUser(state.surface));
3547 if (layer == nullptr) {
3548 return;
3549 }
3550
3551 if (layer->isPendingRemoval()) {
3552 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3553 return;
3554 }
3555
3556 if (state.what & layer_state_t::eDestroySurface) {
3557 removeLayerLocked(mStateLock, layer);
3558 }
3559}
3560
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003561status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003562 const String8& name,
3563 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003564 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliuccd34842018-03-14 12:26:23 -07003565 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003566 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003567{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003568 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003569 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003570 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003571 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003572 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003573
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003574 status_t result = NO_ERROR;
3575
3576 sp<Layer> layer;
3577
Cody Northropbc755282017-03-31 12:00:08 -06003578 String8 uniqueName = getUniqueLayerName(name);
3579
Mathias Agopian3165cc22012-08-08 19:42:09 -07003580 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3581 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003582 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003583 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003584 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003585
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003586 break;
chaviw13fdc492017-06-27 12:40:18 -07003587 case ISurfaceComposerClient::eFXSurfaceColor:
3588 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003589 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003590 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003591 break;
3592 default:
3593 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003594 break;
3595 }
3596
Dan Stoza7d89d062015-04-30 13:29:25 -07003597 if (result != NO_ERROR) {
3598 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003599 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003600
Chia-I Wuab0c3192017-08-01 11:29:00 -07003601 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3602 // TODO b/64227542
3603 if (windowType == 441731) {
3604 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3605 layer->setPrimaryDisplayOnly();
3606 }
3607
Albert Chaulk479c60c2017-01-27 14:21:34 -05003608 layer->setInfo(windowType, ownerUid);
3609
Robert Carr1f0a16a2016-10-24 16:27:39 -07003610 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003611 if (result != NO_ERROR) {
3612 return result;
3613 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003614 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003615
3616 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003617 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003618}
3619
Cody Northropbc755282017-03-31 12:00:08 -06003620String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3621{
3622 bool matchFound = true;
3623 uint32_t dupeCounter = 0;
3624
3625 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3626 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3627
3628 // Loop over layers until we're sure there is no matching name
3629 while (matchFound) {
3630 matchFound = false;
3631 mDrawingState.traverseInZOrder([&](Layer* layer) {
3632 if (layer->getName() == uniqueName) {
3633 matchFound = true;
3634 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3635 }
3636 });
3637 }
3638
3639 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3640
3641 return uniqueName;
3642}
3643
David Sodman0c69cad2017-08-21 12:12:51 -07003644status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003645 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3646 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003647{
3648 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003649 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003650 case PIXEL_FORMAT_TRANSPARENT:
3651 case PIXEL_FORMAT_TRANSLUCENT:
3652 format = PIXEL_FORMAT_RGBA_8888;
3653 break;
3654 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003655 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003656 break;
3657 }
3658
David Sodman0c69cad2017-08-21 12:12:51 -07003659 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3660 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003661 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003662 *handle = layer->getHandle();
3663 *gbp = layer->getProducer();
3664 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003665 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003666
David Sodman0c69cad2017-08-21 12:12:51 -07003667 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003668 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003669}
3670
chaviw13fdc492017-06-27 12:40:18 -07003671status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003672 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003673 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003674{
chaviw13fdc492017-06-27 12:40:18 -07003675 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003676 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003677 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003678}
3679
Mathias Agopianac9fa422013-02-11 16:40:36 -08003680status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003681{
Robert Carr9524cb32017-02-13 11:32:32 -08003682 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003683 status_t err = NO_ERROR;
3684 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003685 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003686 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003687 err = removeLayer(l);
3688 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3689 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003690 }
3691 return err;
3692}
3693
Mathias Agopian13127d82013-03-05 17:47:11 -08003694status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003695{
Mathias Agopian67106042013-03-14 19:18:13 -07003696 // called by ~LayerCleaner() when all references to the IBinder (handle)
3697 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003698 sp<Layer> l = layer.promote();
3699 if (l == nullptr) {
3700 // The layer has already been removed, carry on
3701 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003702 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003703 // If we have a parent, then we can continue to live as long as it does.
3704 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003705}
3706
Mathias Agopianb60314a2012-04-10 22:09:54 -07003707// ---------------------------------------------------------------------------
3708
Andy McFadden13a082e2012-08-24 10:16:42 -07003709void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003710 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003711 Vector<ComposerState> state;
3712 Vector<DisplayState> displays;
3713 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003714 d.what = DisplayState::eDisplayProjectionChanged |
3715 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003716 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003717 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003718 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003719 d.frame.makeInvalid();
3720 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003721 d.width = 0;
3722 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003723 displays.add(d);
3724 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003725 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3726 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003727
David Sodman105b7dc2017-11-04 20:28:14 -07003728 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003729 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003730 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003731
Brian Andersond0010582017-03-07 13:20:31 -08003732 // Use phase of 0 since phase is not known.
3733 // Use latency of 0, which will snap to the ideal latency.
3734 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003735}
3736
3737void SurfaceFlinger::initializeDisplays() {
3738 class MessageScreenInitialized : public MessageBase {
3739 SurfaceFlinger* flinger;
3740 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003741 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003742 virtual bool handler() {
3743 flinger->onInitializeDisplays();
3744 return true;
3745 }
3746 };
3747 sp<MessageBase> msg = new MessageScreenInitialized(this);
3748 postMessageAsync(msg); // we may be called from main thread, use async message
3749}
3750
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003751void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003752 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003753 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3754 this);
3755 int32_t type = hw->getDisplayType();
3756 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003757
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003758 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003759 return;
3760 }
3761
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003762 hw->setPowerMode(mode);
3763 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3764 ALOGW("Trying to set power mode for virtual display");
3765 return;
3766 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003767
Lloyd Pique4d234852018-01-22 17:21:36 -08003768 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003769 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003770 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3771 if (idx < 0) {
3772 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3773 return;
3774 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003775 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003776 }
3777
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003778 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003779 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003780 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003781 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3782 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003783 // FIXME: eventthread only knows about the main display right now
3784 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003785 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003786 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003787
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003788 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003789 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003790 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003791
3792 struct sched_param param = {0};
3793 param.sched_priority = 1;
3794 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3795 ALOGW("Couldn't set SCHED_FIFO on display on");
3796 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003797 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003798 // Turn off the display
3799 struct sched_param param = {0};
3800 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3801 ALOGW("Couldn't set SCHED_OTHER on display off");
3802 }
3803
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003804 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3805 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003806 disableHardwareVsync(true); // also cancels any in-progress resync
3807
Mathias Agopiancde87a32012-09-13 14:09:01 -07003808 // FIXME: eventthread only knows about the main display right now
3809 mEventThread->onScreenReleased();
3810 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003811
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003812 getHwComposer().setPowerMode(type, mode);
3813 mVisibleRegionsDirty = true;
3814 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003815 } else if (mode == HWC_POWER_MODE_DOZE ||
3816 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003817 // Update display while dozing
3818 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003819 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3820 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003821 // FIXME: eventthread only knows about the main display right now
3822 mEventThread->onScreenAcquired();
3823 resyncToHardwareVsync(true);
3824 }
3825 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3826 // Leave display going to doze
3827 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3828 disableHardwareVsync(true); // also cancels any in-progress resync
3829 // FIXME: eventthread only knows about the main display right now
3830 mEventThread->onScreenReleased();
3831 }
3832 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003833 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003834 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003835 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003836 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003837 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003838}
3839
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003840void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3841 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003842 SurfaceFlinger& mFlinger;
3843 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003844 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003845 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003846 MessageSetPowerMode(SurfaceFlinger& flinger,
3847 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3848 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003849 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003850 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003851 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003852 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003853 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003854 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003855 ALOGW("Attempt to set power mode = %d for virtual display",
3856 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003857 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003858 mFlinger.setPowerModeInternal(
3859 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003860 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003861 return true;
3862 }
3863 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003864 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003865 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003866}
3867
3868// ---------------------------------------------------------------------------
3869
Lloyd Pique755e3192018-01-31 16:46:15 -08003870status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3871 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003872 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003873
Mathias Agopianbd115332013-04-18 16:41:04 -07003874 IPCThreadState* ipc = IPCThreadState::self();
3875 const int pid = ipc->getCallingPid();
3876 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003877
Mathias Agopianbd115332013-04-18 16:41:04 -07003878 if ((uid != AID_SHELL) &&
3879 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003880 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003881 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003882 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003883 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003884 // (this would indicate SF is stuck, but we want to be able to
3885 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003886 status_t err = mStateLock.timedLock(s2ns(1));
3887 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003888 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003889 result.appendFormat(
3890 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3891 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003892 }
3893
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003894 bool dumpAll = true;
3895 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003896 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003897
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003898 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003899 if ((index < numArgs) &&
3900 (args[index] == String16("--list"))) {
3901 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003902 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003903 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003904 }
3905
3906 if ((index < numArgs) &&
3907 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003908 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003909 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003910 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003911 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003912
3913 if ((index < numArgs) &&
3914 (args[index] == String16("--latency-clear"))) {
3915 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003916 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003917 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003918 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003919
3920 if ((index < numArgs) &&
3921 (args[index] == String16("--dispsync"))) {
3922 index++;
3923 mPrimaryDispSync.dump(result);
3924 dumpAll = false;
3925 }
Dan Stozab90cf072015-03-05 11:05:59 -08003926
3927 if ((index < numArgs) &&
3928 (args[index] == String16("--static-screen"))) {
3929 index++;
3930 dumpStaticScreenStats(result);
3931 dumpAll = false;
3932 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003933
3934 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003935 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003936 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003937 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003938 dumpAll = false;
3939 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003940
3941 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3942 index++;
3943 dumpWideColorInfo(result);
3944 dumpAll = false;
3945 }
Yiwei Zhang068e31b2018-02-21 13:02:45 -08003946
3947 if ((index < numArgs) &&
3948 (args[index] == String16("--enable-layer-stats"))) {
3949 index++;
3950 mLayerStats.enable();
3951 dumpAll = false;
3952 }
3953
3954 if ((index < numArgs) &&
3955 (args[index] == String16("--disable-layer-stats"))) {
3956 index++;
3957 mLayerStats.disable();
3958 dumpAll = false;
3959 }
3960
3961 if ((index < numArgs) &&
3962 (args[index] == String16("--clear-layer-stats"))) {
3963 index++;
3964 mLayerStats.clear();
3965 dumpAll = false;
3966 }
3967
3968 if ((index < numArgs) &&
3969 (args[index] == String16("--dump-layer-stats"))) {
3970 index++;
3971 mLayerStats.dump(result);
3972 dumpAll = false;
3973 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07003974
3975 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3976 index++;
3977 mTimeStats.parseArgs(asProto, args, index, result);
3978 dumpAll = false;
3979 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003980 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003981
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003982 if (dumpAll) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07003983 if (asProto) {
3984 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3985 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3986 } else {
3987 dumpAllLocked(args, index, result);
3988 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003989 }
3990
Mathias Agopian9795c422009-08-26 16:36:26 -07003991 if (locked) {
3992 mStateLock.unlock();
3993 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003994 }
3995 write(fd, result.string(), result.size());
3996 return NO_ERROR;
3997}
3998
Dan Stozac7014012014-02-14 15:03:43 -08003999void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4000 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004001{
Robert Carr2047fae2016-11-28 14:09:09 -08004002 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004003 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004004 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004005}
4006
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004007void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004008 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004009{
4010 String8 name;
4011 if (index < args.size()) {
4012 name = String8(args[index]);
4013 index++;
4014 }
4015
David Sodman105b7dc2017-11-04 20:28:14 -07004016 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004017 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08004018 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004019
4020 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004021 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004022 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004023 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004024 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004025 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004026 }
Robert Carr2047fae2016-11-28 14:09:09 -08004027 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004028 }
4029}
4030
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004031void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004032 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004033{
4034 String8 name;
4035 if (index < args.size()) {
4036 name = String8(args[index]);
4037 index++;
4038 }
4039
Robert Carr2047fae2016-11-28 14:09:09 -08004040 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004041 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004042 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004043 }
Robert Carr2047fae2016-11-28 14:09:09 -08004044 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004045
Svetoslavd85084b2014-03-20 10:28:31 -07004046 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004047}
4048
Jamie Gennis6547ff42013-07-16 20:12:42 -07004049// This should only be called from the main thread. Otherwise it would need
4050// the lock and should use mCurrentState rather than mDrawingState.
4051void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004052 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004053 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004054 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004055
4056 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4057}
4058
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004059void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004060{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004061 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004062
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004063 if (isLayerTripleBufferingDisabled())
4064 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004065
4066 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004067 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004068 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004069 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004070 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4071 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004072 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004073}
4074
Dan Stozab90cf072015-03-05 11:05:59 -08004075void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4076{
4077 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004078 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4079 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004080 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004081 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004082 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4083 b + 1, bucketTimeSec, percent);
4084 }
David Sodman4a36e932017-11-07 14:29:47 -08004085 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004086 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004087 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004088 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004089 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004090}
4091
Dan Stozae77c7662016-05-13 11:37:28 -07004092void SurfaceFlinger::recordBufferingStats(const char* layerName,
4093 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004094 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4095 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004096 for (const auto& segment : history) {
4097 if (!segment.usedThirdBuffer) {
4098 stats.twoBufferTime += segment.totalTime;
4099 }
4100 if (segment.occupancyAverage < 1.0f) {
4101 stats.doubleBufferedTime += segment.totalTime;
4102 } else if (segment.occupancyAverage < 2.0f) {
4103 stats.tripleBufferedTime += segment.totalTime;
4104 }
4105 ++stats.numSegments;
4106 stats.totalTime += segment.totalTime;
4107 }
4108}
4109
Brian Andersond6927fb2016-07-23 23:37:30 -07004110void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4111 result.appendFormat("Layer frame timestamps:\n");
4112
4113 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4114 const size_t count = currentLayers.size();
4115 for (size_t i=0 ; i<count ; i++) {
4116 currentLayers[i]->dumpFrameEvents(result);
4117 }
4118}
4119
Dan Stozae77c7662016-05-13 11:37:28 -07004120void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4121 result.append("Buffering stats:\n");
4122 result.append(" [Layer name] <Active time> <Two buffer> "
4123 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004124 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004125 typedef std::tuple<std::string, float, float, float> BufferTuple;
4126 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004127 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004128 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004129 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004130 if (stats.numSegments == 0) {
4131 continue;
4132 }
4133 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4134 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4135 stats.totalTime;
4136 float doubleBufferRatio = static_cast<float>(
4137 stats.doubleBufferedTime) / stats.totalTime;
4138 float tripleBufferRatio = static_cast<float>(
4139 stats.tripleBufferedTime) / stats.totalTime;
4140 sorted.insert({activeTime, {name, twoBufferRatio,
4141 doubleBufferRatio, tripleBufferRatio}});
4142 }
4143 for (const auto& sortedPair : sorted) {
4144 float activeTime = sortedPair.first;
4145 const BufferTuple& values = sortedPair.second;
4146 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4147 std::get<0>(values).c_str(), activeTime,
4148 std::get<1>(values), std::get<2>(values),
4149 std::get<3>(values));
4150 }
4151 result.append("\n");
4152}
4153
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004154void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4155 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004156 result.appendFormat("DisplayColorSetting: %s\n",
4157 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004158
4159 // TODO: print out if wide-color mode is active or not
4160
4161 for (size_t d = 0; d < mDisplays.size(); d++) {
4162 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4163 int32_t hwcId = displayDevice->getHwcDisplayId();
4164 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4165 continue;
4166 }
4167
4168 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004169 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004170 for (auto&& mode : modes) {
4171 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4172 }
4173
Peiyong Lina52f0292018-03-14 17:26:31 -07004174 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004175 result.appendFormat(" Current color mode: %s (%d)\n",
4176 decodeColorMode(currentMode).c_str(), currentMode);
4177 }
4178 result.append("\n");
4179}
4180
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004181LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004182 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004183 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4184 const State& state = useDrawing ? mDrawingState : mCurrentState;
4185 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004186 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004187 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004188 });
4189
4190 return layersProto;
4191}
4192
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004193LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4194 LayersProto layersProto;
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004195 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004196
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004197 SizeProto* resolution = layersProto.mutable_resolution();
4198 resolution->set_w(displayDevice->getWidth());
4199 resolution->set_h(displayDevice->getHeight());
4200
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004201 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4202 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4203 layersProto.set_global_transform(
4204 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4205
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004206 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004207 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004208 LayerProto* layerProto = layersProto.add_layers();
4209 layer->writeToProto(layerProto, hwcId);
4210 }
4211 });
4212
4213 return layersProto;
4214}
4215
Mathias Agopian74d211a2013-04-22 16:55:35 +02004216void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4217 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004218{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004219 bool colorize = false;
4220 if (index < args.size()
4221 && (args[index] == String16("--color"))) {
4222 colorize = true;
4223 index++;
4224 }
4225
4226 Colorizer colorizer(colorize);
4227
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004228 // figure out if we're stuck somewhere
4229 const nsecs_t now = systemTime();
4230 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4231 const nsecs_t inTransaction(mDebugInTransaction);
4232 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4233 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4234
4235 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004236 * Dump library configuration.
4237 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004238
4239 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004240 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004241 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004242 appendSfConfigString(result);
4243 appendUiConfigString(result);
4244 appendGuiConfigString(result);
4245 result.append("\n");
4246
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004247 result.append("\nWide-Color information:\n");
4248 dumpWideColorInfo(result);
4249
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004250 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004251 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004252 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004253 result.append(SyncFeatures::getInstance().toString());
4254 result.append("\n");
4255
David Sodman105b7dc2017-11-04 20:28:14 -07004256 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004257
Andy McFadden41d67d72014-04-25 16:58:34 -07004258 colorizer.bold(result);
4259 result.append("DispSync configuration: ");
4260 colorizer.reset(result);
Jorim Jaggie203e042018-06-19 15:57:08 +02004261 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4262 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
4263 result.appendFormat(
4264 "app phase %" PRId64 " ns, "
4265 "sf phase %" PRId64 " ns, "
4266 "early app phase %" PRId64 " ns, "
4267 "early sf phase %" PRId64 " ns, "
4268 "early app gl phase %" PRId64 " ns, "
4269 "early sf gl phase %" PRId64 " ns, "
4270 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4271 vsyncPhaseOffsetNs,
4272 sfVsyncPhaseOffsetNs,
4273 appEarlyOffset,
4274 sfEarlyOffset,
4275 appEarlyGlOffset,
4276 sfEarlyOffset,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004277 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004278 result.append("\n");
4279
Dan Stozab90cf072015-03-05 11:05:59 -08004280 // Dump static screen stats
4281 result.append("\n");
4282 dumpStaticScreenStats(result);
4283 result.append("\n");
4284
Dan Stozae77c7662016-05-13 11:37:28 -07004285 dumpBufferingStats(result);
4286
Andy McFadden4803b742012-09-24 19:07:20 -07004287 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004288 * Dump the visible layer list
4289 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004290 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004291 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004292 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4293 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004294 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004295
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004296 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004297 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004298 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004299 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004300
4301 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004302 * Dump Display state
4303 */
4304
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004305 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004306 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004307 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004308 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4309 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004310 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004311 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004312 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004313
4314 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004315 * Dump SurfaceFlinger global state
4316 */
4317
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004318 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004319 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004320 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004321
Mathias Agopian888c8222012-08-04 21:10:38 -07004322 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004323 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004324
David Sodmanbc815282017-11-05 18:57:52 -08004325 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004326
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004327 if (hw) {
4328 hw->undefinedRegion.dump(result, "undefinedRegion");
4329 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4330 hw->getOrientation(), hw->isDisplayOn());
4331 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004332 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004333 " last eglSwapBuffers() time: %f us\n"
4334 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004335 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004336 " refresh-rate : %f fps\n"
4337 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004338 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004339 " gpu_to_cpu_unsupported : %d\n"
4340 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004341 mLastSwapBufferTime/1000.0,
4342 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004343 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004344 1e9 / activeConfig->getVsyncPeriod(),
4345 activeConfig->getDpiX(),
4346 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004347 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004348
Mathias Agopian74d211a2013-04-22 16:55:35 +02004349 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004350 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004351
Mathias Agopian74d211a2013-04-22 16:55:35 +02004352 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004353 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004354
4355 /*
4356 * VSYNC state
4357 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004358 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004359 result.append("\n");
4360
4361 /*
4362 * HWC layer minidump
4363 */
4364 for (size_t d = 0; d < mDisplays.size(); d++) {
4365 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4366 int32_t hwcId = displayDevice->getHwcDisplayId();
4367 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4368 continue;
4369 }
4370
4371 result.appendFormat("Display %d HWC layers:\n", hwcId);
4372 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004373 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004374 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004375 });
Dan Stozae22aec72016-08-01 13:20:59 -07004376 result.append("\n");
4377 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004378
4379 /*
4380 * Dump HWComposer state
4381 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004382 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004383 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004384 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004385 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004386 result.appendFormat(" h/w composer %s\n",
4387 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004388 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004389
4390 /*
4391 * Dump gralloc state
4392 */
4393 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4394 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004395
4396 /*
4397 * Dump VrFlinger state if in use.
4398 */
4399 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4400 result.append("VrFlinger state:\n");
4401 result.append(mVrFlinger->Dump().c_str());
4402 result.append("\n");
4403 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004404}
4405
Mathias Agopian13127d82013-03-05 17:47:11 -08004406const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004407SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004408 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004409 wp<IBinder> dpy;
4410 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4411 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4412 dpy = mDisplays.keyAt(i);
4413 break;
4414 }
4415 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004416 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004417 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4418 // Just use the primary display so we have something to return
4419 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4420 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004421 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004422}
4423
Keun young Park63f165f2012-08-31 10:53:36 -07004424bool SurfaceFlinger::startDdmConnection()
4425{
4426 void* libddmconnection_dso =
4427 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4428 if (!libddmconnection_dso) {
4429 return false;
4430 }
4431 void (*DdmConnection_start)(const char* name);
4432 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004433 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004434 if (!DdmConnection_start) {
4435 dlclose(libddmconnection_dso);
4436 return false;
4437 }
4438 (*DdmConnection_start)(getServiceName());
4439 return true;
4440}
4441
Chia-I Wu28f320b2018-05-03 11:02:56 -07004442void SurfaceFlinger::updateColorMatrixLocked() {
4443 mat4 colorMatrix;
4444 if (mGlobalSaturationFactor != 1.0f) {
4445 // Rec.709 luma coefficients
4446 float3 luminance{0.213f, 0.715f, 0.072f};
4447 luminance *= 1.0f - mGlobalSaturationFactor;
4448 mat4 saturationMatrix = mat4(
4449 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4450 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4451 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4452 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4453 );
4454 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4455 } else {
4456 colorMatrix = mClientColorMatrix * mDaltonizer();
4457 }
4458
4459 if (mCurrentState.colorMatrix != colorMatrix) {
4460 mCurrentState.colorMatrix = colorMatrix;
4461 mCurrentState.colorMatrixChanged = true;
4462 setTransactionFlags(eTransactionNeeded);
4463 }
4464}
4465
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004466status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004467 switch (code) {
4468 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004469 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004470 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004471 case CLEAR_ANIMATION_FRAME_STATS:
4472 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004473 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004474 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004475 case ENABLE_VSYNC_INJECTIONS:
4476 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004477 {
4478 // codes that require permission check
Robert Carrd4ae7f32018-06-07 16:10:57 -07004479 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4480 IPCThreadState* ipc = IPCThreadState::self();
4481 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4482 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004483 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004484 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004485 break;
4486 }
Robert Carr1db73f62016-12-21 12:58:51 -08004487 /*
4488 * Calling setTransactionState is safe, because you need to have been
4489 * granted a reference to Client* and Handle* to do anything with it.
4490 *
4491 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4492 */
4493 case SET_TRANSACTION_STATE:
4494 case CREATE_SCOPED_CONNECTION:
4495 {
4496 return OK;
4497 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004498 case CAPTURE_SCREEN:
4499 {
4500 // codes that require permission check
4501 IPCThreadState* ipc = IPCThreadState::self();
4502 const int pid = ipc->getCallingPid();
4503 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004504 if ((uid != AID_GRAPHICS) &&
4505 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004506 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004507 return PERMISSION_DENIED;
4508 }
4509 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004510 }
chaviwa76b2712017-09-20 12:02:26 -07004511 case CAPTURE_LAYERS: {
4512 IPCThreadState* ipc = IPCThreadState::self();
4513 const int pid = ipc->getCallingPid();
4514 const int uid = ipc->getCallingUid();
4515 if ((uid != AID_GRAPHICS) &&
4516 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4517 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4518 return PERMISSION_DENIED;
4519 }
4520 break;
4521 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004522 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004523 return OK;
4524}
4525
4526status_t SurfaceFlinger::onTransact(
4527 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4528{
4529 status_t credentialCheck = CheckTransactCodeCredentials(code);
4530 if (credentialCheck != OK) {
4531 return credentialCheck;
4532 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004533
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004534 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4535 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004536 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004537 IPCThreadState* ipc = IPCThreadState::self();
4538 const int uid = ipc->getCallingUid();
4539 if (CC_UNLIKELY(uid != AID_SYSTEM
4540 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004541 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004542 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004543 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004544 return PERMISSION_DENIED;
4545 }
4546 int n;
4547 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004548 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004549 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004550 return NO_ERROR;
4551 case 1002: // SHOW_UPDATES
4552 n = data.readInt32();
4553 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004554 invalidateHwcGeometry();
4555 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004556 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004557 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004558 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004559 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004560 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004561 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004562 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004563 setTransactionFlags(
4564 eTransactionNeeded|
4565 eDisplayTransactionNeeded|
4566 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004567 return NO_ERROR;
4568 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004569 case 1006:{ // send empty update
4570 signalRefresh();
4571 return NO_ERROR;
4572 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004573 case 1008: // toggle use of hw composer
4574 n = data.readInt32();
4575 mDebugDisableHWC = n ? 1 : 0;
4576 invalidateHwcGeometry();
4577 repaintEverything();
4578 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004579 case 1009: // toggle use of transform hint
4580 n = data.readInt32();
4581 mDebugDisableTransformHint = n ? 1 : 0;
4582 invalidateHwcGeometry();
4583 repaintEverything();
4584 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004585 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004586 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004587 reply->writeInt32(0);
4588 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004589 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004590 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004591 return NO_ERROR;
4592 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004593 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004594 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004595 return NO_ERROR;
4596 }
4597 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004598 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004599 // daltonize
4600 n = data.readInt32();
4601 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004602 case 1:
4603 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4604 break;
4605 case 2:
4606 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4607 break;
4608 case 3:
4609 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4610 break;
4611 default:
4612 mDaltonizer.setType(ColorBlindnessType::None);
4613 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004614 }
4615 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004616 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004617 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004618 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004619 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004620
4621 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004622 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004623 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004624 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004625 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004626 // apply a color matrix
4627 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004628 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004629 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004630 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004631 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004632 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004633 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004634 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004635 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004636 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004637 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004638
4639 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4640 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004641 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004642 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4643 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4644 }
4645
Chia-I Wu28f320b2018-05-03 11:02:56 -07004646 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004647 return NO_ERROR;
4648 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004649 // This is an experimental interface
4650 // Needs to be shifted to proper binder interface when we productize
4651 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004652 n = data.readInt32();
4653 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004654 return NO_ERROR;
4655 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004656 case 1017: {
4657 n = data.readInt32();
4658 mForceFullDamage = static_cast<bool>(n);
4659 return NO_ERROR;
4660 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004661 case 1018: { // Modify Choreographer's phase offset
4662 n = data.readInt32();
4663 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4664 return NO_ERROR;
4665 }
4666 case 1019: { // Modify SurfaceFlinger's phase offset
4667 n = data.readInt32();
4668 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4669 return NO_ERROR;
4670 }
Irvel468051e2016-06-13 16:44:44 -07004671 case 1020: { // Layer updates interceptor
4672 n = data.readInt32();
4673 if (n) {
4674 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004675 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004676 }
4677 else{
4678 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004679 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004680 }
4681 return NO_ERROR;
4682 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004683 case 1021: { // Disable HWC virtual displays
4684 n = data.readInt32();
4685 mUseHwcVirtualDisplays = !n;
4686 return NO_ERROR;
4687 }
Romain Guy0147a172017-06-01 13:53:56 -07004688 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004689 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004690 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004691
Chia-I Wu28f320b2018-05-03 11:02:56 -07004692 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004693 return NO_ERROR;
4694 }
Romain Guy54f154a2017-10-24 21:40:32 +01004695 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004696 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004697 invalidateHwcGeometry();
4698 repaintEverything();
4699 return NO_ERROR;
4700 }
4701 case 1024: { // Is wide color gamut rendering/color management supported?
4702 reply->writeBool(hasWideColorDisplay);
4703 return NO_ERROR;
4704 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004705 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004706 n = data.readInt32();
4707 if (n) {
4708 ALOGV("LayerTracing enabled");
4709 mTracing.enable();
4710 doTracing("tracing.enable");
4711 reply->writeInt32(NO_ERROR);
4712 } else {
4713 ALOGV("LayerTracing disabled");
4714 status_t err = mTracing.disable();
4715 reply->writeInt32(err);
4716 }
4717 return NO_ERROR;
4718 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004719 case 1026: { // Get layer tracing status
4720 reply->writeBool(mTracing.isEnabled());
4721 return NO_ERROR;
4722 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004723 // Is a DisplayColorSetting supported?
4724 case 1027: {
Chia-I Wu0d711262018-05-21 15:19:35 -07004725 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
4726 if (!hw) {
4727 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004728 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004729
4730 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4731 switch (setting) {
4732 case DisplayColorSetting::MANAGED:
4733 reply->writeBool(hasWideColorDisplay);
4734 break;
4735 case DisplayColorSetting::UNMANAGED:
4736 reply->writeBool(true);
4737 break;
4738 case DisplayColorSetting::ENHANCED:
4739 reply->writeBool(hw->hasRenderIntent(RenderIntent::ENHANCE));
4740 break;
4741 default: // vendor display color setting
4742 reply->writeBool(hw->hasRenderIntent(static_cast<RenderIntent>(setting)));
4743 break;
4744 }
4745 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004746 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004747 }
4748 }
4749 return err;
4750}
4751
Steven Thomas6d8110b2017-08-31 18:24:21 -07004752void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004753 android_atomic_or(1, &mRepaintEverything);
4754 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004755}
4756
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004757// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4758class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004759public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004760 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4761 ~WindowDisconnector() {
4762 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004763 }
4764
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004765private:
4766 ANativeWindow* mWindow;
4767 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004768};
4769
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004770status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4771 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4772 int32_t minLayerZ, int32_t maxLayerZ,
4773 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004774 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004775 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004776
chaviwa76b2712017-09-20 12:02:26 -07004777 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4778
4779 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004780 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4781
chaviwa76b2712017-09-20 12:02:26 -07004782 DisplayRenderArea renderArea(device, sourceCrop, reqHeight, reqWidth, rotation);
4783
4784 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4785 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004786 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004787}
4788
4789status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004790 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004791 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004792 ATRACE_CALL();
4793
4794 class LayerRenderArea : public RenderArea {
4795 public:
Robert Carr578038f2018-03-09 12:25:24 -08004796 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4797 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004798 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004799 mLayer(layer),
4800 mCrop(crop),
4801 mFlinger(flinger),
4802 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004803 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004804 Rect getBounds() const override {
4805 const Layer::State& layerState(mLayer->getDrawingState());
4806 return Rect(layerState.active.w, layerState.active.h);
4807 }
4808 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4809 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4810 bool isSecure() const override { return false; }
4811 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004812 Rect getSourceCrop() const override {
4813 if (mCrop.isEmpty()) {
4814 return getBounds();
4815 } else {
4816 return mCrop;
4817 }
4818 }
Robert Carr578038f2018-03-09 12:25:24 -08004819 class ReparentForDrawing {
4820 public:
4821 const sp<Layer>& oldParent;
4822 const sp<Layer>& newParent;
4823
4824 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4825 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004826 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004827 }
Robert Carr15eae092018-03-23 13:43:53 -07004828 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004829 };
4830
4831 void render(std::function<void()> drawLayers) override {
4832 if (!mChildrenOnly) {
4833 mTransform = mLayer->getTransform().inverse();
4834 drawLayers();
4835 } else {
4836 Rect bounds = getBounds();
4837 screenshotParentLayer =
4838 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4839 bounds.getWidth(), bounds.getHeight(), 0);
4840
4841 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4842 drawLayers();
4843 }
4844 }
chaviwa76b2712017-09-20 12:02:26 -07004845
chaviwa76b2712017-09-20 12:02:26 -07004846 private:
chaviw7206d492017-11-10 16:16:12 -08004847 const sp<Layer> mLayer;
4848 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004849
4850 // In the "childrenOnly" case we reparent the children to a screenshot
4851 // layer which has no properties set and which does not draw.
4852 sp<ContainerLayer> screenshotParentLayer;
4853 Transform mTransform;
4854
4855 SurfaceFlinger* mFlinger;
4856 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004857 };
4858
4859 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4860 auto parent = layerHandle->owner.promote();
4861
chaviw7206d492017-11-10 16:16:12 -08004862 if (parent == nullptr || parent->isPendingRemoval()) {
4863 ALOGE("captureLayers called with a removed parent");
4864 return NAME_NOT_FOUND;
4865 }
4866
Robert Carr578038f2018-03-09 12:25:24 -08004867 const int uid = IPCThreadState::self()->getCallingUid();
4868 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4869 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4870 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4871 return PERMISSION_DENIED;
4872 }
4873
chaviw7206d492017-11-10 16:16:12 -08004874 Rect crop(sourceCrop);
4875 if (sourceCrop.width() <= 0) {
4876 crop.left = 0;
4877 crop.right = parent->getCurrentState().active.w;
4878 }
4879
4880 if (sourceCrop.height() <= 0) {
4881 crop.top = 0;
4882 crop.bottom = parent->getCurrentState().active.h;
4883 }
4884
4885 int32_t reqWidth = crop.width() * frameScale;
4886 int32_t reqHeight = crop.height() * frameScale;
4887
Robert Carr578038f2018-03-09 12:25:24 -08004888 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004889
Robert Carr578038f2018-03-09 12:25:24 -08004890 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004891 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4892 if (!layer->isVisible()) {
4893 return;
Robert Carr578038f2018-03-09 12:25:24 -08004894 } else if (childrenOnly && layer == parent.get()) {
4895 return;
chaviwa76b2712017-09-20 12:02:26 -07004896 }
4897 visitor(layer);
4898 });
4899 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004900 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004901}
4902
4903status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4904 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004905 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004906 bool useIdentityTransform) {
4907 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004908
Iris Chang7501ed62018-04-30 14:45:42 +08004909 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004910
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004911 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4912 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4913 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4914 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004915
4916 // This mutex protects syncFd and captureResult for communication of the return values from the
4917 // main thread back to this Binder thread
4918 std::mutex captureMutex;
4919 std::condition_variable captureCondition;
4920 std::unique_lock<std::mutex> captureLock(captureMutex);
4921 int syncFd = -1;
4922 std::optional<status_t> captureResult;
4923
Robert Carr03480e22018-01-04 16:02:06 -08004924 const int uid = IPCThreadState::self()->getCallingUid();
4925 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4926
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004927 sp<LambdaMessage> message = new LambdaMessage([&]() {
4928 // If there is a refresh pending, bug out early and tell the binder thread to try again
4929 // after the refresh.
4930 if (mRefreshPending) {
4931 ATRACE_NAME("Skipping screenshot for now");
4932 std::unique_lock<std::mutex> captureLock(captureMutex);
4933 captureResult = std::make_optional<status_t>(EAGAIN);
4934 captureCondition.notify_one();
4935 return;
4936 }
4937
4938 status_t result = NO_ERROR;
4939 int fd = -1;
4940 {
4941 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08004942 renderArea.render([&]() {
4943 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4944 useIdentityTransform, forSystem, &fd);
4945 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004946 }
4947
4948 {
4949 std::unique_lock<std::mutex> captureLock(captureMutex);
4950 syncFd = fd;
4951 captureResult = std::make_optional<status_t>(result);
4952 captureCondition.notify_one();
4953 }
4954 });
4955
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004956 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004957 if (result == NO_ERROR) {
4958 captureCondition.wait(captureLock, [&]() { return captureResult; });
4959 while (*captureResult == EAGAIN) {
4960 captureResult.reset();
4961 result = postMessageAsync(message);
4962 if (result != NO_ERROR) {
4963 return result;
4964 }
4965 captureCondition.wait(captureLock, [&]() { return captureResult; });
4966 }
4967 result = *captureResult;
4968 }
4969
4970 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004971 sync_wait(syncFd, -1);
4972 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004973 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004974
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004975 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004976}
4977
chaviwa76b2712017-09-20 12:02:26 -07004978void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4979 TraverseLayersFunction traverseLayers, bool yswap,
4980 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004981 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004982
Lloyd Pique144e1162017-12-20 16:44:52 -08004983 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004984
4985 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004986 const auto raWidth = renderArea.getWidth();
4987 const auto raHeight = renderArea.getHeight();
4988
4989 const auto reqWidth = renderArea.getReqWidth();
4990 const auto reqHeight = renderArea.getReqHeight();
4991 Rect sourceCrop = renderArea.getSourceCrop();
4992
Iris Chang7501ed62018-04-30 14:45:42 +08004993 bool filtering = false;
4994 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
4995 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
4996 static_cast<int32_t>(reqHeight) != raWidth;
4997 } else {
4998 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
4999 static_cast<int32_t>(reqHeight) != raHeight;
5000 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005001
Dan Stozac1879002014-05-22 15:59:05 -07005002 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005003 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005004 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005005 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005006 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5007 Transform tr;
5008 uint32_t flags = 0x00;
5009 switch (mPrimaryDisplayOrientation) {
5010 case DisplayState::eOrientation90:
5011 flags = Transform::ROT_90;
5012 break;
5013 case DisplayState::eOrientation180:
5014 flags = Transform::ROT_180;
5015 break;
5016 case DisplayState::eOrientation270:
5017 flags = Transform::ROT_270;
5018 break;
5019 }
5020 tr.set(flags, raWidth, raHeight);
5021 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005022 }
5023
5024 // ensure that sourceCrop is inside screen
5025 if (sourceCrop.left < 0) {
5026 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5027 }
chaviwa76b2712017-09-20 12:02:26 -07005028 if (sourceCrop.right > raWidth) {
5029 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005030 }
5031 if (sourceCrop.top < 0) {
5032 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5033 }
chaviwa76b2712017-09-20 12:02:26 -07005034 if (sourceCrop.bottom > raHeight) {
5035 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005036 }
5037
Chia-I Wu36574d92018-05-16 10:54:36 -07005038 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5039 engine.setOutputDataSpace(Dataspace::SRGB);
5040 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005041
Mathias Agopian180f10d2013-04-10 22:55:41 -07005042 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005043 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005044
Iris Chang7501ed62018-04-30 14:45:42 +08005045 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5046 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5047 // convert hw orientation into flag presentation
5048 // here inverse transform needed
5049 uint8_t hw_rot_90 = 0x00;
5050 uint8_t hw_flip_hv = 0x00;
5051 switch (mPrimaryDisplayOrientation) {
5052 case DisplayState::eOrientation90:
5053 hw_rot_90 = Transform::ROT_90;
5054 hw_flip_hv = Transform::ROT_180;
5055 break;
5056 case DisplayState::eOrientation180:
5057 hw_flip_hv = Transform::ROT_180;
5058 break;
5059 case DisplayState::eOrientation270:
5060 hw_rot_90 = Transform::ROT_90;
5061 break;
5062 }
5063
5064 // transform flags operation
5065 // 1) flip H V if both have ROT_90 flag
5066 // 2) XOR these flags
5067 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5068 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5069 if (rotation_rot_90 & hw_rot_90) {
5070 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5071 }
5072 rotation = static_cast<Transform::orientation_flags>
5073 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5074 }
5075
Mathias Agopian180f10d2013-04-10 22:55:41 -07005076 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005077 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005078 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005079 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005080
chaviw50da5042018-04-09 13:49:37 -07005081 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005082 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005083 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005084
chaviwa76b2712017-09-20 12:02:26 -07005085 traverseLayers([&](Layer* layer) {
5086 if (filtering) layer->setFiltering(true);
5087 layer->draw(renderArea, useIdentityTransform);
5088 if (filtering) layer->setFiltering(false);
5089 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005090}
5091
chaviwa76b2712017-09-20 12:02:26 -07005092status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5093 TraverseLayersFunction traverseLayers,
5094 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005095 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005096 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005097 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005098 ATRACE_CALL();
5099
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005100 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005101
5102 traverseLayers([&](Layer* layer) {
5103 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5104 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005105
Robert Carr03480e22018-01-04 16:02:06 -08005106 // We allow the system server to take screenshots of secure layers for
5107 // use in situations like the Screen-rotation animation and place
5108 // the impetus on WindowManager to not persist them.
5109 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005110 ALOGW("FB is protected: PERMISSION_DENIED");
5111 return PERMISSION_DENIED;
5112 }
5113
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005114 // this binds the given EGLImage as a framebuffer for the
5115 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005116 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005117 if (bufferBond.getStatus() != NO_ERROR) {
5118 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005119 return INVALID_OPERATION;
5120 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005121
Dan Stozaabcda352017-06-01 14:37:39 -07005122 // this will in fact render into our dequeued buffer
5123 // via an FBO, which means we didn't have to create
5124 // an EGLSurface and therefore we're not
5125 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005126 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005127
Dan Stozaabcda352017-06-01 14:37:39 -07005128 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005129 getRenderEngine().finish();
5130 *outSyncFd = -1;
5131
chaviwa76b2712017-09-20 12:02:26 -07005132 const auto reqWidth = renderArea.getReqWidth();
5133 const auto reqHeight = renderArea.getReqHeight();
5134
Dan Stozaabcda352017-06-01 14:37:39 -07005135 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5136 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005137 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005138 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005139 } else {
5140 base::unique_fd syncFd = getRenderEngine().flush();
5141 if (syncFd < 0) {
5142 getRenderEngine().finish();
5143 }
5144 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005145 }
5146
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005147 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005148}
5149
Mathias Agopiand5556842013-09-19 17:08:37 -07005150void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005151 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005152 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005153 for (size_t y = 0; y < h; y++) {
5154 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5155 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005156 if (p[x] != 0xFF000000) return;
5157 }
5158 }
chaviwa76b2712017-09-20 12:02:26 -07005159 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005160
Robert Carr2047fae2016-11-28 14:09:09 -08005161 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005162 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005163 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005164 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5165 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5166 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5167 static_cast<float>(state.color.a));
5168 i++;
5169 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005170 }
5171}
5172
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005173// ---------------------------------------------------------------------------
5174
Dan Stoza412903f2017-04-27 13:42:17 -07005175void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5176 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005177}
5178
Dan Stoza412903f2017-04-27 13:42:17 -07005179void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5180 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005181}
5182
chaviwa76b2712017-09-20 12:02:26 -07005183void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5184 int32_t maxLayerZ,
5185 const LayerVector::Visitor& visitor) {
5186 // We loop through the first level of layers without traversing,
5187 // as we need to interpret min/max layer Z in the top level Z space.
5188 for (const auto& layer : mDrawingState.layersSortedByZ) {
5189 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5190 continue;
5191 }
5192 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005193 // relative layers are traversed in Layer::traverseInZOrder
5194 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005195 continue;
5196 }
5197 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005198 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5199 return;
5200 }
chaviwa76b2712017-09-20 12:02:26 -07005201 if (!layer->isVisible()) {
5202 return;
5203 }
5204 visitor(layer);
5205 });
5206 }
5207}
5208
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005209}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005210
5211
5212#if defined(__gl_h_)
5213#error "don't include gl/gl.h in this file"
5214#endif
5215
5216#if defined(__gl2_h_)
5217#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005218#endif