blob: ba5154d8e72f59132997459d7d31fd14900d930e [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 Wud49d6692018-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"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070082#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070083#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070084#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070085#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080086
Mathias Agopianff2ed702013-09-01 21:36:12 -070087#include "Effects/Daltonizer.h"
88
Mathias Agopian875d8e12013-06-07 15:35:48 -070089#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070090#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070091
Jiyong Park4b20c2e2017-01-14 19:45:11 +090092#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080093#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
94#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090095#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090096
chaviw1d044282017-09-27 12:19:28 -070097#include <layerproto/LayerProtoParser.h>
98
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080099#define DISPLAY_COUNT 1
100
Mathias Agopianfee2b462013-07-03 12:34:01 -0700101/*
102 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
103 * black pixels.
104 */
105#define DEBUG_SCREENSHOTS false
106
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800107namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700108
Jaesoo Lee43518572017-01-23 19:03:16 +0900109using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900110using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700111using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700112using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700113using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700114using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900115
Steven Thomasb02664d2017-07-26 18:48:28 -0700116namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700117
118#pragma clang diagnostic push
119#pragma clang diagnostic error "-Wswitch-enum"
120
121bool isWideColorMode(const ColorMode colorMode) {
122 switch (colorMode) {
123 case ColorMode::DISPLAY_P3:
124 case ColorMode::ADOBE_RGB:
125 case ColorMode::DCI_P3:
126 case ColorMode::BT2020:
127 case ColorMode::BT2100_PQ:
128 case ColorMode::BT2100_HLG:
129 return true;
130 case ColorMode::NATIVE:
131 case ColorMode::STANDARD_BT601_625:
132 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
133 case ColorMode::STANDARD_BT601_525:
134 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
135 case ColorMode::STANDARD_BT709:
136 case ColorMode::SRGB:
137 return false;
138 }
139 return false;
140}
141
142#pragma clang diagnostic pop
143
Steven Thomasb02664d2017-07-26 18:48:28 -0700144class ConditionalLock {
145public:
146 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
147 if (lock) {
148 mMutex.lock();
149 }
150 }
151 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
152private:
153 Mutex& mMutex;
154 bool mLocked;
155};
Peiyong Linfca547f2018-07-09 13:03:33 -0700156
Steven Thomasb02664d2017-07-26 18:48:28 -0700157} // namespace anonymous
158
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800159// ---------------------------------------------------------------------------
160
Mathias Agopian99b49842011-06-27 16:05:52 -0700161const String16 sHardwareTest("android.permission.HARDWARE_TEST");
162const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
163const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
164const String16 sDump("android.permission.DUMP");
165
166// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800167int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
168int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700169int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700170bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800171uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800172bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800173bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800174int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800175// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600176bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700177
Kalle Raitaa099a242017-01-11 11:17:29 -0800178
179std::string getHwcServiceName() {
180 char value[PROPERTY_VALUE_MAX] = {};
181 property_get("debug.sf.hwc_service_name", value, "default");
182 ALOGI("Using HWComposer service: '%s'", value);
183 return std::string(value);
184}
185
186bool useTrebleTestingOverride() {
187 char value[PROPERTY_VALUE_MAX] = {};
188 property_get("debug.sf.treble_testing_override", value, "false");
189 ALOGI("Treble testing override: '%s'", value);
190 return std::string(value) == "true";
191}
192
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800193std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
194 switch(displayColorSetting) {
195 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700196 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800197 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700198 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800199 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700200 return std::string("Enhanced");
201 default:
202 return std::string("Unknown ") +
203 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800204 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800205}
206
Lloyd Pique99d3da52018-01-22 17:48:03 -0800207NativeWindowSurface::~NativeWindowSurface() = default;
208
209namespace impl {
210
211class NativeWindowSurface final : public android::NativeWindowSurface {
212public:
213 static std::unique_ptr<android::NativeWindowSurface> create(
214 const sp<IGraphicBufferProducer>& producer) {
215 return std::make_unique<NativeWindowSurface>(producer);
216 }
217
218 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
219 : surface(new Surface(producer, false)) {}
220
221 ~NativeWindowSurface() override = default;
222
223private:
224 sp<ANativeWindow> getNativeWindow() const override { return surface; }
225
226 void preallocateBuffers() override { surface->allocateBuffers(); }
227
228 sp<Surface> surface;
229};
230
231} // namespace impl
232
David Sodmanbc815282017-11-05 18:57:52 -0800233SurfaceFlingerBE::SurfaceFlingerBE()
234 : mHwcServiceName(getHwcServiceName()),
235 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800236 mFrameBuckets(),
237 mTotalTime(0),
238 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800239 mComposerSequenceId(0) {
240}
241
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800242SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800243 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800244 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700245 mTransactionPending(false),
246 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700247 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700248 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700249 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800250 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700251 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800252 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800253 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800254 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800255 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800256 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700257 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700258 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700259 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700260 mDebugInSwapBuffers(0),
261 mLastSwapBufferTime(0),
262 mDebugInTransaction(0),
263 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700264 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000265 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700266 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700267 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800268 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800269 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700270 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800271 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800272 mCreateBufferQueue(&BufferQueue::createBufferQueue),
273 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800274
275SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800276 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800277
278 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
279 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
280
281 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
282 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
283
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800284 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
285 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800286
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700287 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
288 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
289
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700290 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
291 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
292
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800293 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
294 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
295
Steven Thomas050b2c82017-03-06 11:45:16 -0800296 // Vr flinger is only enabled on Daydream ready devices.
297 useVrFlinger = getBool< ISurfaceFlingerConfigs,
298 &ISurfaceFlingerConfigs::useVrFlinger>(false);
299
Fabien Sanglard1971b632017-03-10 14:50:03 -0800300 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
301 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
302
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600303 hasWideColorDisplay =
304 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
305
Iris Chang7501ed62018-04-30 14:45:42 +0800306 V1_1::DisplayOrientation primaryDisplayOrientation =
307 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
308 V1_1::DisplayOrientation::ORIENTATION_0);
309
310 switch (primaryDisplayOrientation) {
311 case V1_1::DisplayOrientation::ORIENTATION_90:
312 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
313 break;
314 case V1_1::DisplayOrientation::ORIENTATION_180:
315 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
316 break;
317 case V1_1::DisplayOrientation::ORIENTATION_270:
318 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
319 break;
320 default:
321 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
322 break;
323 }
324 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
325
David Sodman99974d22017-11-28 12:04:33 -0800326 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700327
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800328 // debugging stuff...
329 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700330
Mathias Agopianb4b17302013-03-20 18:36:41 -0700331 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700332 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700333
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800334 property_get("debug.sf.showupdates", value, "0");
335 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700336
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700337 property_get("debug.sf.ddms", value, "0");
338 mDebugDDMS = atoi(value);
339 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700340 if (!startDdmConnection()) {
341 // start failed, and DDMS debugging not enabled
342 mDebugDDMS = 0;
343 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700344 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700345 ALOGI_IF(mDebugRegion, "showupdates enabled");
346 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700347
348 property_get("debug.sf.disable_backpressure", value, "0");
349 mPropagateBackpressure = !atoi(value);
350 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700351
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800352 property_get("debug.sf.enable_hwc_vds", value, "0");
353 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800354 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800355
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800356 property_get("ro.sf.disable_triple_buffer", value, "1");
357 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800358 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700359
Yiwei Zhang243b3782018-05-15 17:40:04 -0700360 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700361 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
362 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
363
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200364 property_get("debug.sf.early_phase_offset_ns", value, "-1");
365 const int earlySfOffsetNs = atoi(value);
366
367 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
368 const int earlyGlSfOffsetNs = atoi(value);
369
370 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
371 const int earlyAppOffsetNs = atoi(value);
372
373 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
374 const int earlyGlAppOffsetNs = atoi(value);
375
376 const VSyncModulator::Offsets earlyOffsets =
377 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
378 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
379 const VSyncModulator::Offsets earlyGlOffsets =
380 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
381 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
382 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
383 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700384
Romain Guy11d63f42017-07-20 12:47:14 -0700385 // We should be reading 'persist.sys.sf.color_saturation' here
386 // but since /data may be encrypted, we need to wait until after vold
387 // comes online to attempt to read the property. The property is
388 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800389
390 if (useTrebleTestingOverride()) {
391 // Without the override SurfaceFlinger cannot connect to HIDL
392 // services that are not listed in the manifests. Considered
393 // deriving the setting from the set service name, but it
394 // would be brittle if the name that's not 'default' is used
395 // for production purposes later on.
396 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
397 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800398}
399
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800400void SurfaceFlinger::onFirstRef()
401{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800402 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800403}
404
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800405SurfaceFlinger::~SurfaceFlinger()
406{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800407}
408
Dan Stozac7014012014-02-14 15:03:43 -0800409void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800410{
411 // the window manager died on us. prepare its eulogy.
412
Andy McFadden13a082e2012-08-24 10:16:42 -0700413 // restore initial conditions (default device unblank, etc)
414 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800415
416 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700417 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800418}
419
Robert Carr1db73f62016-12-21 12:58:51 -0800420static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700421 status_t err = client->initCheck();
422 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800423 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800424 }
Robert Carr1db73f62016-12-21 12:58:51 -0800425 return nullptr;
426}
427
428sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
429 return initClient(new Client(this));
430}
431
432sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
433 const sp<IGraphicBufferProducer>& gbp) {
434 if (authenticateSurfaceTexture(gbp) == false) {
435 return nullptr;
436 }
437 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
438 if (layer == nullptr) {
439 return nullptr;
440 }
441
442 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800443}
444
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700445sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
446 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700447{
448 class DisplayToken : public BBinder {
449 sp<SurfaceFlinger> flinger;
450 virtual ~DisplayToken() {
451 // no more references, this display must be terminated
452 Mutex::Autolock _l(flinger->mStateLock);
453 flinger->mCurrentState.displays.removeItem(this);
454 flinger->setTransactionFlags(eDisplayTransactionNeeded);
455 }
456 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700457 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700458 : flinger(flinger) {
459 }
460 };
461
462 sp<BBinder> token = new DisplayToken(this);
463
464 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700465 DisplayDeviceState info;
466 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700467 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700468 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700469 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800470 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700471 return token;
472}
473
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700474void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700475 Mutex::Autolock _l(mStateLock);
476
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700477 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700478 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700479 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700480 return;
481 }
482
483 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700484 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700485 ALOGE("destroyDisplay called for non-virtual display");
486 return;
487 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700488 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700489 mCurrentState.displays.removeItemsAt(idx);
490 setTransactionFlags(eDisplayTransactionNeeded);
491}
492
Mathias Agopiane57f2922012-08-09 16:29:12 -0700493sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700494 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700495 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800496 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700497 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700498 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700499}
500
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800501void SurfaceFlinger::bootFinished()
502{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700503 if (mStartPropertySetThread->join() != NO_ERROR) {
504 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800505 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800506 const nsecs_t now = systemTime();
507 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000508 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700509
510 // wait patiently for the window manager death
511 const String16 name("window");
512 sp<IBinder> window(defaultServiceManager()->getService(name));
513 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700514 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700515 }
516
Steven Thomas050b2c82017-03-06 11:45:16 -0800517 if (mVrFlinger) {
518 mVrFlinger->OnBootFinished();
519 }
520
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700521 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700522 // formerly we would just kill the process, but we now ask it to exit so it
523 // can choose where to stop the animation.
524 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700525
526 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
527 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
528 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700529
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800530 postMessageAsync(new LambdaMessage([this] {
531 readPersistentProperties();
532 mBootStage = BootStage::FINISHED;
533 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800534}
535
Dan Stoza436ccf32018-06-21 12:10:12 -0700536uint32_t SurfaceFlinger::getNewTexture() {
537 {
538 std::lock_guard lock(mTexturePoolMutex);
539 if (!mTexturePool.empty()) {
540 uint32_t name = mTexturePool.back();
541 mTexturePool.pop_back();
542 ATRACE_INT("TexturePoolSize", mTexturePool.size());
543 return name;
544 }
545
546 // The pool was too small, so increase it for the future
547 ++mTexturePoolSize;
548 }
549
550 // The pool was empty, so we need to get a new texture name directly using a
551 // blocking call to the main thread
552 uint32_t name = 0;
553 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
554 return name;
555}
556
Mathias Agopian3f844832013-08-07 21:24:32 -0700557void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700558 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700559}
560
Lloyd Piquee83f9312018-02-01 12:53:17 -0800561class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700562public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700563 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000564 const char* name) :
565 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700566 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700567 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000568 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
569 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700570 mDispSync(dispSync),
571 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700572 mVsyncMutex(),
573 mPhaseOffset(phaseOffset),
574 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700575
Lloyd Piquee83f9312018-02-01 12:53:17 -0800576 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700577
Lloyd Piquee83f9312018-02-01 12:53:17 -0800578 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700579 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700580 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000581 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700582 static_cast<DispSync::Callback*>(this));
583 if (err != NO_ERROR) {
584 ALOGE("error registering vsync callback: %s (%d)",
585 strerror(-err), err);
586 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700587 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700588 } else {
589 status_t err = mDispSync->removeEventListener(
590 static_cast<DispSync::Callback*>(this));
591 if (err != NO_ERROR) {
592 ALOGE("error unregistering vsync callback: %s (%d)",
593 strerror(-err), err);
594 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700595 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700596 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700597 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700598 }
599
Lloyd Piquee83f9312018-02-01 12:53:17 -0800600 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700601 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700602 mCallback = callback;
603 }
604
Lloyd Piquee83f9312018-02-01 12:53:17 -0800605 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700606 Mutex::Autolock lock(mVsyncMutex);
607
608 // Normalize phaseOffset to [0, period)
609 auto period = mDispSync->getPeriod();
610 phaseOffset %= period;
611 if (phaseOffset < 0) {
612 // If we're here, then phaseOffset is in (-period, 0). After this
613 // operation, it will be in (0, period)
614 phaseOffset += period;
615 }
616 mPhaseOffset = phaseOffset;
617
618 // If we're not enabled, we don't need to mess with the listeners
619 if (!mEnabled) {
620 return;
621 }
622
Dan Stoza84d619e2018-03-28 17:07:36 -0700623 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
624 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700625 if (err != NO_ERROR) {
Dan Stoza84d619e2018-03-28 17:07:36 -0700626 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700627 strerror(-err), err);
628 }
629 }
630
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700631private:
632 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800633 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700634 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700635 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700636 callback = mCallback;
637
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700638 if (mTraceVsync) {
639 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700640 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700641 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700642 }
643
Peiyong Lin566a3b42018-01-09 18:22:43 -0800644 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700645 callback->onVSyncEvent(when);
646 }
647 }
648
Tim Murray4a4e4a22016-04-19 16:29:23 +0000649 const char* const mName;
650
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700651 int mValue;
652
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700653 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700654 const String8 mVsyncOnLabel;
655 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700656
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700657 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700658
659 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800660 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700661
662 Mutex mVsyncMutex; // Protects the following
663 nsecs_t mPhaseOffset;
664 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700665};
666
Lloyd Piquee83f9312018-02-01 12:53:17 -0800667class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700668public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800669 InjectVSyncSource() = default;
670 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700671
Lloyd Piquee83f9312018-02-01 12:53:17 -0800672 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700673 std::lock_guard<std::mutex> lock(mCallbackMutex);
674 mCallback = callback;
675 }
676
Lloyd Piquee83f9312018-02-01 12:53:17 -0800677 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700678 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700679 if (mCallback) {
680 mCallback->onVSyncEvent(when);
681 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700682 }
683
Lloyd Piquee83f9312018-02-01 12:53:17 -0800684 void setVSyncEnabled(bool) override {}
685 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700686
687private:
688 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800689 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700690};
691
Wei Wangf9b05ee2017-07-19 20:59:39 -0700692// Do not call property_set on main thread which will be blocked by init
693// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700694void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700695 ALOGI( "SurfaceFlinger's main thread ready to run. "
696 "Initializing graphics H/W...");
697
Thierry Strudel2924d012017-08-14 15:19:37 -0700698 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900699
Steven Thomasb02664d2017-07-26 18:48:28 -0700700 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800701
Steven Thomasb02664d2017-07-26 18:48:28 -0700702 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800703 mEventThreadSource =
704 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
705 true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800706 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700707 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800708 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800709 "appEventThread");
710 mSfEventThreadSource =
711 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
712 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800713
Lloyd Pique24b0a482018-03-09 18:52:26 -0800714 mSFEventThread =
715 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700716 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800717 [this](nsecs_t timestamp) {
718 mInterceptor->saveVSyncEvent(timestamp);
719 },
720 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800721 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200722 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800723
Steven Thomasb02664d2017-07-26 18:48:28 -0700724 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800725 getBE().mRenderEngine =
726 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
727 hasWideColorDisplay
728 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
729 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800730 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700731
732 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
733 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800734 getBE().mHwc.reset(
735 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700736 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800737 // Process any initial hotplug and resulting display changes.
738 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700739 const auto display = getDefaultDisplayDeviceLocked();
740 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
741 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
742 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800743
Lloyd Piquefcd86612017-12-14 17:15:36 -0800744 // make the default display GLContext current so that we can create textures
745 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700746 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800747
Steven Thomas050b2c82017-03-06 11:45:16 -0800748 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700749 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700750 // This callback is called from the vr flinger dispatch thread. We
751 // need to call signalTransaction(), which requires holding
752 // mStateLock when we're not on the main thread. Acquiring
753 // mStateLock from the vr flinger dispatch thread might trigger a
754 // deadlock in surface flinger (see b/66916578), so post a message
755 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700756 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700757 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
758 mVrFlingerRequestsDisplay = requestDisplay;
759 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700760 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800761 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700762 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
763 getHwComposer()
764 .getHwcDisplayId(display->getId())
765 .value_or(0),
766 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800767 if (!mVrFlinger) {
768 ALOGE("Failed to start vrflinger");
769 }
770 }
771
Lloyd Pique379adc12018-01-22 17:31:47 -0800772 mEventControlThread = std::make_unique<impl::EventControlThread>(
773 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700774
Mathias Agopian92a979a2012-08-02 18:32:23 -0700775 // initialize our drawing state
776 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700777
Andy McFadden13a082e2012-08-24 10:16:42 -0700778 // set initial conditions (e.g. unblank default device)
779 initializeDisplays();
780
David Sodmanbc815282017-11-05 18:57:52 -0800781 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700782
Wei Wangf9b05ee2017-07-19 20:59:39 -0700783 // Inform native graphics APIs whether the present timestamp is supported:
784 if (getHwComposer().hasCapability(
785 HWC2::Capability::PresentFenceIsNotReliable)) {
786 mStartPropertySetThread = new StartPropertySetThread(false);
787 } else {
788 mStartPropertySetThread = new StartPropertySetThread(true);
789 }
790
791 if (mStartPropertySetThread->Start() != NO_ERROR) {
792 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800793 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800794
Chia-I Wud49d6692018-06-27 07:17:41 +0800795 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
796 // is used to saturate legacy sRGB content. However, to make sure the same color under
797 // Display P3 will be saturated to the same color, we intentionally break the API spec
798 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
799 // such saturation matrix on Display P3 is understood fully, the API should always return
800 // identify matrix.
801 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
802 Dataspace::SRGB_LINEAR);
803
804 // we will apply this on Display P3.
805 if (mEnhancedSaturationMatrix != mat4()) {
806 ColorSpace srgb(ColorSpace::sRGB());
807 ColorSpace displayP3(ColorSpace::DisplayP3());
808 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
809 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
810 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
811 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800812
Dan Stoza9e56aa02015-11-02 13:00:03 -0800813 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700814}
815
Romain Guy11d63f42017-07-20 12:47:14 -0700816void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700817 Mutex::Autolock _l(mStateLock);
818
Romain Guy11d63f42017-07-20 12:47:14 -0700819 char value[PROPERTY_VALUE_MAX];
820
821 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800822 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700823 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800824 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100825
826 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700827 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700828}
829
Mathias Agopiana67e4182012-06-19 17:26:12 -0700830void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800831 // Start boot animation service by setting a property mailbox
832 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700833 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800834 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700835 if (mStartPropertySetThread->join() != NO_ERROR) {
836 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800837 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700838}
839
Mathias Agopian875d8e12013-06-07 15:35:48 -0700840size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800841 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700842}
843
Mathias Agopian875d8e12013-06-07 15:35:48 -0700844size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800845 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700846}
847
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800848// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800849
Jamie Gennis582270d2011-08-17 18:19:00 -0700850bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800851 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800852 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800853 return authenticateSurfaceTextureLocked(bufferProducer);
854}
855
856bool SurfaceFlinger::authenticateSurfaceTextureLocked(
857 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800858 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800859 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800860}
861
Brian Anderson6b376712017-04-04 10:51:39 -0700862status_t SurfaceFlinger::getSupportedFrameTimestamps(
863 std::vector<FrameEvent>* outSupported) const {
864 *outSupported = {
865 FrameEvent::REQUESTED_PRESENT,
866 FrameEvent::ACQUIRE,
867 FrameEvent::LATCH,
868 FrameEvent::FIRST_REFRESH_START,
869 FrameEvent::LAST_REFRESH_START,
870 FrameEvent::GPU_COMPOSITION_DONE,
871 FrameEvent::DEQUEUE_READY,
872 FrameEvent::RELEASE,
873 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700874 ConditionalLock _l(mStateLock,
875 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700876 if (!getHwComposer().hasCapability(
877 HWC2::Capability::PresentFenceIsNotReliable)) {
878 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
879 }
880 return NO_ERROR;
881}
882
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700883status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
884 Vector<DisplayInfo>* configs) {
885 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700886 return BAD_VALUE;
887 }
888
Jesse Hall692c7232012-11-08 15:41:56 -0800889 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700890 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
891 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700892 type = i;
893 break;
894 }
895 }
896
897 if (type < 0) {
898 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700899 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700900
Mathias Agopian8b736f12012-08-13 17:54:26 -0700901 // TODO: Not sure if display density should handled by SF any longer
902 class Density {
903 static int getDensityFromProperty(char const* propName) {
904 char property[PROPERTY_VALUE_MAX];
905 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800906 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700907 density = atoi(property);
908 }
909 return density;
910 }
911 public:
912 static int getEmuDensity() {
913 return getDensityFromProperty("qemu.sf.lcd_density"); }
914 static int getBuildDensity() {
915 return getDensityFromProperty("ro.sf.lcd_density"); }
916 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700917
Dan Stoza7f7da322014-05-02 15:26:25 -0700918 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700919
Steven Thomas6d8110b2017-08-31 18:24:21 -0700920 ConditionalLock _l(mStateLock,
921 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800922 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700923 DisplayInfo info = DisplayInfo();
924
Dan Stoza9e56aa02015-11-02 13:00:03 -0800925 float xdpi = hwConfig->getDpiX();
926 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700927
928 if (type == DisplayDevice::DISPLAY_PRIMARY) {
929 // The density of the device is provided by a build property
930 float density = Density::getBuildDensity() / 160.0f;
931 if (density == 0) {
932 // the build doesn't provide a density -- this is wrong!
933 // use xdpi instead
934 ALOGE("ro.sf.lcd_density must be defined as a build property");
935 density = xdpi / 160.0f;
936 }
937 if (Density::getEmuDensity()) {
938 // if "qemu.sf.lcd_density" is specified, it overrides everything
939 xdpi = ydpi = density = Density::getEmuDensity();
940 density /= 160.0f;
941 }
942 info.density = density;
943
944 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700945 const auto display = getDefaultDisplayDeviceLocked();
946 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700947 } else {
948 // TODO: where should this value come from?
949 static const int TV_DENSITY = 213;
950 info.density = TV_DENSITY / 160.0f;
951 info.orientation = 0;
952 }
953
Dan Stoza9e56aa02015-11-02 13:00:03 -0800954 info.w = hwConfig->getWidth();
955 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700956 info.xdpi = xdpi;
957 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800958 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900959 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800960
Andy McFadden91b2ca82014-06-13 14:04:23 -0700961 // This is how far in advance a buffer must be queued for
962 // presentation at a given time. If you want a buffer to appear
963 // on the screen at time N, you must submit the buffer before
964 // (N - presentationDeadline).
965 //
966 // Normally it's one full refresh period (to give SF a chance to
967 // latch the buffer), but this can be reduced by configuring a
968 // DispSync offset. Any additional delays introduced by the hardware
969 // composer or panel must be accounted for here.
970 //
971 // We add an additional 1ms to allow for processing time and
972 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800973 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800974 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700975
976 // All non-virtual displays are currently considered secure.
977 info.secure = true;
978
Iris Chang7501ed62018-04-30 14:45:42 +0800979 if (type == DisplayDevice::DISPLAY_PRIMARY &&
980 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
981 std::swap(info.w, info.h);
982 }
983
Michael Wright28f24d02016-07-12 13:30:53 -0700984 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700985 }
986
Dan Stoza7f7da322014-05-02 15:26:25 -0700987 return NO_ERROR;
988}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700989
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700990status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
991 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700992 return BAD_VALUE;
993 }
994
995 // FIXME for now we always return stats for the primary display
996 memset(stats, 0, sizeof(*stats));
997 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
998 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
999 return NO_ERROR;
1000}
1001
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001002int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
1003 const auto display = getDisplayDevice(displayToken);
1004 if (!display) {
1005 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +08001006 return BAD_VALUE;
1007 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001008
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001009 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -07001010}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001011
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001012void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
1013 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001014 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001015 return;
1016 }
1017
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001018 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001019 ALOGW("Trying to set config for virtual display");
1020 return;
1021 }
1022
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001023 display->setActiveConfig(mode);
1024 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001025}
1026
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001027status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001028 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001029 Vector<DisplayInfo> configs;
1030 getDisplayConfigs(displayToken, &configs);
1031 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
1032 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
1033 configs.size());
1034 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001035 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001036 const auto display = getDisplayDevice(displayToken);
1037 if (!display) {
1038 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
1039 displayToken.get());
1040 } else if (display->isVirtual()) {
1041 ALOGW("Attempt to set active config %d for virtual display", mode);
1042 } else {
1043 setActiveConfigInternal(display, mode);
1044 }
1045 }));
1046
Mathias Agopian888c8222012-08-04 21:10:38 -07001047 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001048}
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001049status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1050 Vector<ColorMode>* outColorModes) {
1051 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001052 return BAD_VALUE;
1053 }
1054
Michael Wright28f24d02016-07-12 13:30:53 -07001055 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001056 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
1057 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -07001058 type = i;
1059 break;
1060 }
1061 }
1062
1063 if (type < 0) {
1064 return type;
1065 }
1066
Peiyong Lina52f0292018-03-14 17:26:31 -07001067 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001068 {
1069 ConditionalLock _l(mStateLock,
1070 std::this_thread::get_id() != mMainThreadId);
1071 modes = getHwComposer().getColorModes(type);
1072 }
Michael Wright28f24d02016-07-12 13:30:53 -07001073 outColorModes->clear();
1074 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1075
1076 return NO_ERROR;
1077}
1078
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001079ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1080 if (const auto display = getDisplayDevice(displayToken)) {
1081 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001082 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001083 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001084}
1085
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001086void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1087 Dataspace dataSpace, RenderIntent renderIntent) {
1088 ColorMode currentMode = display->getActiveColorMode();
1089 Dataspace currentDataSpace = display->getCompositionDataSpace();
1090 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001091
Peiyong Lin38e9a562018-04-10 16:24:20 -07001092 if (mode == currentMode && dataSpace == currentDataSpace &&
1093 renderIntent == currentRenderIntent) {
1094 return;
1095 }
1096
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001097 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001098 ALOGW("Trying to set config for virtual display");
1099 return;
1100 }
1101
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001102 display->setActiveColorMode(mode);
1103 display->setCompositionDataSpace(dataSpace);
1104 display->setActiveRenderIntent(renderIntent);
1105 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001106
1107 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001108 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1109 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001110}
1111
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001112status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001113 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001114 Vector<ColorMode> modes;
1115 getDisplayColorModes(displayToken, &modes);
1116 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1117 if (mode < ColorMode::NATIVE || !exists) {
1118 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1119 decodeColorMode(mode).c_str(), mode, displayToken.get());
1120 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001121 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001122 const auto display = getDisplayDevice(displayToken);
1123 if (!display) {
1124 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1125 decodeColorMode(mode).c_str(), mode, displayToken.get());
1126 } else if (display->isVirtual()) {
1127 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1128 decodeColorMode(mode).c_str(), mode);
1129 } else {
1130 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1131 RenderIntent::COLORIMETRIC);
1132 }
1133 }));
1134
Michael Wright28f24d02016-07-12 13:30:53 -07001135 return NO_ERROR;
1136}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001137
Svetoslavd85084b2014-03-20 10:28:31 -07001138status_t SurfaceFlinger::clearAnimationFrameStats() {
1139 Mutex::Autolock _l(mStateLock);
1140 mAnimFrameTracker.clearStats();
1141 return NO_ERROR;
1142}
1143
1144status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1145 Mutex::Autolock _l(mStateLock);
1146 mAnimFrameTracker.getStats(outStats);
1147 return NO_ERROR;
1148}
1149
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001150status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1151 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001152 Mutex::Autolock _l(mStateLock);
1153
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001154 const auto display = getDisplayDeviceLocked(displayToken);
1155 if (!display) {
1156 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001157 return BAD_VALUE;
1158 }
1159
Peiyong Linfb069302018-04-25 14:34:31 -07001160 // At this point the DisplayDeivce should already be set up,
1161 // meaning the luminance information is already queried from
1162 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001163 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001164 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1165 capabilities.getDesiredMaxLuminance(),
1166 capabilities.getDesiredMaxAverageLuminance(),
1167 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001168
1169 return NO_ERROR;
1170}
1171
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001172status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001173 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001174 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001175
Chia-I Wu90f669f2017-10-05 14:24:41 -07001176 if (mInjectVSyncs == enable) {
1177 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001178 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001179
1180 if (enable) {
1181 ALOGV("VSync Injections enabled");
1182 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001183 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001184 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001185 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001186 impl::EventThread::InterceptVSyncsCallback(),
1187 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001188 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001189 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001190 } else {
1191 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001192 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001193 }
1194
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001195 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001196 }));
1197
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001198 return NO_ERROR;
1199}
1200
1201status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001202 Mutex::Autolock _l(mStateLock);
1203
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001204 if (!mInjectVSyncs) {
1205 ALOGE("VSync Injections not enabled");
1206 return BAD_VALUE;
1207 }
1208 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1209 ALOGV("Injecting VSync inside SurfaceFlinger");
1210 mVSyncInjector->onInjectSyncEvent(when);
1211 }
1212 return NO_ERROR;
1213}
1214
Lloyd Pique755e3192018-01-31 16:46:15 -08001215status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1216 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001217 IPCThreadState* ipc = IPCThreadState::self();
1218 const int pid = ipc->getCallingPid();
1219 const int uid = ipc->getCallingUid();
1220 if ((uid != AID_SHELL) &&
1221 !PermissionCache::checkPermission(sDump, pid, uid)) {
1222 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1223 return PERMISSION_DENIED;
1224 }
1225
1226 // Try to acquire a lock for 1s, fail gracefully
1227 const status_t err = mStateLock.timedLock(s2ns(1));
1228 const bool locked = (err == NO_ERROR);
1229 if (!locked) {
1230 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1231 return TIMED_OUT;
1232 }
1233
1234 outLayers->clear();
1235 mCurrentState.traverseInZOrder([&](Layer* layer) {
1236 outLayers->push_back(layer->getLayerDebugInfo());
1237 });
1238
1239 mStateLock.unlock();
1240 return NO_ERROR;
1241}
1242
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001243// ----------------------------------------------------------------------------
1244
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001245sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1246 ISurfaceComposer::VsyncSource vsyncSource) {
1247 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1248 return mSFEventThread->createEventConnection();
1249 } else {
1250 return mEventThread->createEventConnection();
1251 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001252}
1253
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001254// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001255
1256void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001257 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001258}
1259
1260void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001261 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001262}
1263
1264void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001265 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001266}
1267
1268void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001269 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001270 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001271}
1272
1273status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001274 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001275 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001276}
1277
1278status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001279 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001280 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001281 if (res == NO_ERROR) {
1282 msg->wait();
1283 }
1284 return res;
1285}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001286
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001287void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001288 do {
1289 waitForEvent();
1290 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001291}
1292
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001293void SurfaceFlinger::enableHardwareVsync() {
1294 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001295 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001296 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001297 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001298 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001299 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001300}
1301
Jesse Hall948fe0c2013-10-14 12:56:09 -07001302void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001303 Mutex::Autolock _l(mHWVsyncLock);
1304
Jesse Hall948fe0c2013-10-14 12:56:09 -07001305 if (makeAvailable) {
1306 mHWVsyncAvailable = true;
1307 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001308 // Hardware vsync is not currently available, so abort the resync
1309 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001310 return;
1311 }
1312
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001313 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1314 if (!getHwComposer().isConnected(displayId)) {
1315 return;
1316 }
1317
1318 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001319 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001320
1321 mPrimaryDispSync.reset();
1322 mPrimaryDispSync.setPeriod(period);
1323
1324 if (!mPrimaryHWVsyncEnabled) {
1325 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001326 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 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001335 mPrimaryDispSync.endResync();
1336 mPrimaryHWVsyncEnabled = false;
1337 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001338 if (makeUnavailable) {
1339 mHWVsyncAvailable = false;
1340 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001341}
1342
Tim Murray4a4e4a22016-04-19 16:29:23 +00001343void SurfaceFlinger::resyncWithRateLimit() {
1344 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001345
1346 // No explicit locking is needed here since EventThread holds a lock while calling this method
1347 static nsecs_t sLastResyncAttempted = 0;
1348 const nsecs_t now = systemTime();
1349 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001350 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001351 }
Dan Stoza57164302017-05-08 14:03:54 -07001352 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001353}
1354
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001355void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1356 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001357 ATRACE_NAME("SF onVsync");
1358
Steven Thomas3cfac282017-02-06 12:29:30 -08001359 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001360 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001361 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001362 return;
1363 }
1364
1365 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001366 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001367 return;
1368 }
1369
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001370 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1371 // For now, we don't do anything with external display vsyncs.
1372 return;
1373 }
1374
Jamie Gennisd1700752013-10-14 12:22:52 -07001375 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001376
Jamie Gennisd1700752013-10-14 12:22:52 -07001377 { // Scope for the lock
1378 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001379 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001380 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001381 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001382 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001383
1384 if (needsHwVsync) {
1385 enableHardwareVsync();
1386 } else {
1387 disableHardwareVsync(false);
1388 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001389}
1390
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001391void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001392 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1393 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001394}
1395
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001396void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001397 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001398 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001399 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001400
Lloyd Piqueba04e622017-12-14 17:11:26 -08001401 // Ignore events that do not have the right sequenceId.
1402 if (sequenceId != getBE().mComposerSequenceId) {
1403 return;
1404 }
1405
Steven Thomasb02664d2017-07-26 18:48:28 -07001406 // Only lock if we're not on the main thread. This function is normally
1407 // called on a hwbinder thread, but for the primary display it's called on
1408 // the main thread with the state lock already held, so don't attempt to
1409 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001410 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001411
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001412 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001413
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001414 if (std::this_thread::get_id() == mMainThreadId) {
1415 // Process all pending hot plug events immediately if we are on the main thread.
1416 processDisplayHotplugEventsLocked();
1417 }
1418
Lloyd Piqueba04e622017-12-14 17:11:26 -08001419 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001420}
1421
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001422void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001423 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001424 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001425 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001426 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001427 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001428}
1429
Dan Stoza9e56aa02015-11-02 13:00:03 -08001430void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001431 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001432 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001433 getHwComposer().setVsyncEnabled(disp,
1434 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001435}
1436
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001437// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001438void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001439 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001440 // Clear the drawing state so that the logic inside of
1441 // handleTransactionLocked will fire. It will determine the delta between
1442 // mCurrentState and mDrawingState and re-apply all changes when we make the
1443 // transition.
1444 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001445 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001446 mDisplays.clear();
1447}
1448
Steven Thomas050b2c82017-03-06 11:45:16 -08001449void SurfaceFlinger::updateVrFlinger() {
1450 if (!mVrFlinger)
1451 return;
1452 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001453 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001454 return;
1455 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001456
David Sodman105b7dc2017-11-04 20:28:14 -07001457 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001458 ALOGE("Vr flinger is only supported for remote hardware composer"
1459 " service connections. Ignoring request to transition to vr"
1460 " flinger.");
1461 mVrFlingerRequestsDisplay = false;
1462 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001463 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001464
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001465 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001466
Steven Thomas0123ac62018-07-12 11:32:34 -07001467 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001468 LOG_ALWAYS_FATAL_IF(!display);
1469 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001470 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1471 // called below. Clear the reference now so we don't accidentally use it
1472 // later.
1473 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001474
Steven Thomasb02664d2017-07-26 18:48:28 -07001475 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001476 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001477 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001478
Steven Thomasb02664d2017-07-26 18:48:28 -07001479 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001480 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001481 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1482 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001483 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001484
David Sodman105b7dc2017-11-04 20:28:14 -07001485 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1486 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001487
1488 if (vrFlingerRequestsDisplay) {
1489 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001490 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001491
1492 mVisibleRegionsDirty = true;
1493 invalidateHwcGeometry();
1494
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001495 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001496 display = getDefaultDisplayDeviceLocked();
1497 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001498 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001499
Steven Thomasb02664d2017-07-26 18:48:28 -07001500 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001501 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001502 const nsecs_t period = activeConfig->getVsyncPeriod();
1503 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001504
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001505 // The present fences returned from vr_hwc are not an accurate
1506 // representation of vsync times.
1507 mPrimaryDispSync.setIgnorePresentFences(
1508 getBE().mHwc->isUsingVrComposer() || !hasSyncFramework);
1509
Steven Thomasb02664d2017-07-26 18:48:28 -07001510 // Use phase of 0 since phase is not known.
1511 // Use latency of 0, which will snap to the ideal latency.
1512 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001513
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001514 resyncToHardwareVsync(false);
1515
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001516 android_atomic_or(1, &mRepaintEverything);
1517 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001518}
1519
Mathias Agopian4fec8732012-06-29 14:12:52 -07001520void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001521 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001522 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001523 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001524 bool frameMissed = !mHadClientComposition &&
1525 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001526 (mPreviousPresentFence->getSignalTime() ==
1527 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001528 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001529 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001530 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001531 mTimeStats.incrementMissedFrames();
1532 if (mPropagateBackpressure) {
1533 signalLayerUpdate();
1534 break;
1535 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001536 }
Dan Stoza50182882016-07-08 12:02:20 -07001537
Steven Thomas050b2c82017-03-06 11:45:16 -08001538 // Now that we're going to make it to the handleMessageTransaction()
1539 // call below it's safe to call updateVrFlinger(), which will
1540 // potentially trigger a display handoff.
1541 updateVrFlinger();
1542
Dan Stoza6b9454d2014-11-07 16:00:59 -08001543 bool refreshNeeded = handleMessageTransaction();
1544 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001545 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001546 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001547 // Signal a refresh if a transaction modified the window state,
1548 // a new buffer was latched, or if HWC has requested a full
1549 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001550 signalRefresh();
1551 }
1552 break;
1553 }
1554 case MessageQueue::REFRESH: {
1555 handleMessageRefresh();
1556 break;
1557 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001558 }
1559}
1560
Dan Stoza6b9454d2014-11-07 16:00:59 -08001561bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001562 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001563 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001564 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001565 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001566 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001567 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001568}
1569
Dan Stoza6b9454d2014-11-07 16:00:59 -08001570bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001571 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001572 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001573}
1574
1575void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001576 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001577
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001578 mRefreshPending = false;
1579
Lloyd Pique074e8122018-07-26 12:57:23 -07001580 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1581
1582 preComposition(refreshStartTime);
1583 rebuildLayerStacks();
1584 setUpHWComposer();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001585 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001586 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001587 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001588 doComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001589 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001590
Dan Stozabfbffeb2016-07-21 14:49:33 -07001591 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001592 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001593 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001594 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001595 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001596 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001597
Dan Stoza9e56aa02015-11-02 13:00:03 -08001598 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001599}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001600
Mathias Agopiancd60f992012-08-16 16:28:27 -07001601void SurfaceFlinger::doDebugFlashRegions()
1602{
1603 // is debugging enabled
1604 if (CC_LIKELY(!mDebugRegion))
1605 return;
1606
1607 const bool repaintEverything = mRepaintEverything;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001608 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001609 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001610 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001611 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001612 if (!dirtyRegion.isEmpty()) {
1613 // redraw the whole screen
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001614 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001615
1616 // and draw the dirty region
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001617 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001618 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001619 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1620
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001621 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001622 }
1623 }
1624 }
1625
1626 postFramebuffer();
1627
1628 if (mDebugRegion > 1) {
1629 usleep(mDebugRegion * 1000);
1630 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001631
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001632 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001633 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001634 continue;
1635 }
1636
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001637 status_t result = display->prepareFrame(*getBE().mHwc);
1638 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001639 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001640 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001641}
1642
Adrian Roos1e1a1282017-11-01 19:05:31 +01001643void SurfaceFlinger::doTracing(const char* where) {
1644 ATRACE_CALL();
1645 ATRACE_NAME(where);
1646 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001647 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001648 }
1649}
1650
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001651void SurfaceFlinger::logLayerStats() {
1652 ATRACE_CALL();
1653 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001654 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001655 if (display->isPrimary()) {
1656 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001657 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001658 }
1659 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001660
1661 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001662 }
1663}
1664
Lloyd Pique074e8122018-07-26 12:57:23 -07001665void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001666{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001667 ATRACE_CALL();
1668 ALOGV("preComposition");
1669
Mathias Agopiancd60f992012-08-16 16:28:27 -07001670 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001671 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique074e8122018-07-26 12:57:23 -07001672 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001673 needExtraInvalidate = true;
1674 }
Robert Carr2047fae2016-11-28 14:09:09 -08001675 });
1676
Mathias Agopiancd60f992012-08-16 16:28:27 -07001677 if (needExtraInvalidate) {
1678 signalLayerUpdate();
1679 }
1680}
1681
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001682void SurfaceFlinger::updateCompositorTiming(
1683 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1684 std::shared_ptr<FenceTime>& presentFenceTime) {
1685 // Update queue of past composite+present times and determine the
1686 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001687 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001688 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001689 while (!getBE().mCompositePresentTimes.empty()) {
1690 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001691 // Cached values should have been updated before calling this method,
1692 // which helps avoid duplicate syscalls.
1693 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1694 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1695 break;
1696 }
1697 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001698 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001699 }
1700
1701 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001702 while (getBE().mCompositePresentTimes.size() > 16) {
1703 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001704 }
1705
Brian Andersond0010582017-03-07 13:20:31 -08001706 setCompositorTimingSnapped(
1707 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1708}
1709
1710void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1711 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001712 // Integer division and modulo round toward 0 not -inf, so we need to
1713 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001714 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001715 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1716 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1717
Brian Andersond0010582017-03-07 13:20:31 -08001718 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1719 if (idealLatency <= 0) {
1720 idealLatency = vsyncInterval;
1721 }
1722
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001723 // Snap the latency to a value that removes scheduling jitter from the
1724 // composition and present times, which often have >1ms of jitter.
1725 // Reducing jitter is important if an app attempts to extrapolate
1726 // something (such as user input) to an accurate diasplay time.
1727 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1728 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001729 nsecs_t bias = vsyncInterval / 2;
1730 int64_t extraVsyncs =
1731 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1732 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1733 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001734
David Sodman99974d22017-11-28 12:04:33 -08001735 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1736 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1737 getBE().mCompositorTiming.interval = vsyncInterval;
1738 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001739}
1740
Lloyd Pique074e8122018-07-26 12:57:23 -07001741void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001742{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001743 ATRACE_CALL();
1744 ALOGV("postComposition");
1745
Brian Anderson3546a3f2016-07-14 11:51:14 -07001746 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001747 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001748 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001749 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001750 }
1751
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001752 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001753 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001754
David Sodman73beded2017-11-15 11:56:06 -08001755 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001756 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001757 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001758 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001759 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001760 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001761 } else {
1762 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1763 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001764
David Sodman73beded2017-11-15 11:56:06 -08001765 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001766 mPreviousPresentFence =
1767 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1768 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001769 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001770
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001771 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1772 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1773
Lloyd Pique074e8122018-07-26 12:57:23 -07001774 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001775 // when we started doing work for this frame, but that should be okay
1776 // since updateCompositorTiming has snapping logic.
1777 updateCompositorTiming(
Lloyd Pique074e8122018-07-26 12:57:23 -07001778 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001779 CompositorTiming compositorTiming;
1780 {
David Sodman99974d22017-11-28 12:04:33 -08001781 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1782 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001783 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001784
Robert Carr2047fae2016-11-28 14:09:09 -08001785 mDrawingState.traverseInZOrder([&](Layer* layer) {
1786 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001787 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001788 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001789 recordBufferingStats(layer->getName().string(),
1790 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001791 }
Robert Carr2047fae2016-11-28 14:09:09 -08001792 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001793
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001794 if (presentFenceTime->isValid()) {
1795 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001796 enableHardwareVsync();
1797 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001798 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001799 }
1800 }
1801
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001802 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001803 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001804 enableHardwareVsync();
1805 }
1806 }
1807
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001808 if (mAnimCompositionPending) {
1809 mAnimCompositionPending = false;
1810
Brian Anderson4e606e32017-03-16 15:34:57 -07001811 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001812 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001813 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001814 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001815 // The HWC doesn't support present fences, so use the refresh
1816 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001817 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001818 mAnimFrameTracker.setActualPresentTime(presentTime);
1819 }
1820 mAnimFrameTracker.advanceFrame();
1821 }
Dan Stozab90cf072015-03-05 11:05:59 -08001822
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001823 mTimeStats.incrementTotalFrames();
1824 if (mHadClientComposition) {
1825 mTimeStats.incrementClientCompositionFrames();
1826 }
1827
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001828 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001829 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001830 return;
1831 }
1832
1833 nsecs_t currentTime = systemTime();
1834 if (mHasPoweredOff) {
1835 mHasPoweredOff = false;
1836 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001837 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001838 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001839 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1840 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001841 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001842 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001843 }
David Sodman4a36e932017-11-07 14:29:47 -08001844 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001845 }
David Sodman4a36e932017-11-07 14:29:47 -08001846 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001847
1848 {
1849 std::lock_guard lock(mTexturePoolMutex);
1850 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1851 if (refillCount > 0) {
1852 const size_t offset = mTexturePool.size();
1853 mTexturePool.resize(mTexturePoolSize);
1854 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1855 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1856 }
1857 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001858}
1859
1860void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001861 ATRACE_CALL();
1862 ALOGV("rebuildLayerStacks");
1863
Mathias Agopiancd60f992012-08-16 16:28:27 -07001864 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001865 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001866 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001867 mVisibleRegionsDirty = false;
1868 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001869
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001870 for (const auto& pair : mDisplays) {
1871 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001872 Region opaqueRegion;
1873 Region dirtyRegion;
1874 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001875 Vector<sp<Layer>> layersNeedingFences;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001876 const Transform& tr = display->getTransform();
1877 const Rect bounds = display->getBounds();
1878 if (display->isPoweredOn()) {
1879 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001880
Jeff Sharkey76488112017-02-27 14:15:18 -07001881 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001882 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001883 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001884 Region drawRegion(tr.transform(
1885 layer->visibleNonTransparentRegion));
1886 drawRegion.andSelf(bounds);
1887 if (!drawRegion.isEmpty()) {
1888 layersSortedByZ.add(layer);
1889 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001890 // Clear out the HWC layer if this layer was
1891 // previously visible, but no longer is
1892 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001893 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001894 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001895 // WM changes display->layerStack upon sleep/awake.
1896 // Here we make sure we delete the HWC layers even if
1897 // WM changed their layer stack.
1898 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001899 }
1900
1901 // If a layer is not going to get a release fence because
1902 // it is invisible, but it is also going to release its
1903 // old buffer, add it to the list of layers needing
1904 // fences.
1905 if (hwcLayerDestroyed) {
1906 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1907 mLayersWithQueuedFrames.cend(), layer);
1908 if (found != mLayersWithQueuedFrames.cend()) {
1909 layersNeedingFences.add(layer);
1910 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001911 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001912 });
1913 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001914 display->setVisibleLayersSortedByZ(layersSortedByZ);
1915 display->setLayersNeedingFences(layersNeedingFences);
1916 display->undefinedRegion.set(bounds);
1917 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1918 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001919 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001920 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001921}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001922
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001923// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001924// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001925// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001926// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001927// The returned HDR data space is one of
1928// - Dataspace::UNKNOWN
1929// - Dataspace::BT2020_HLG
1930// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001931Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1932 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001933 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001934 *outHdrDataSpace = Dataspace::UNKNOWN;
1935
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001936 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001937 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001938 case Dataspace::V0_SCRGB:
1939 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001940 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001941 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001942 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001943 case Dataspace::BT2020_PQ:
1944 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001945 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001946 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001947 case Dataspace::BT2020_HLG:
1948 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001949 // When there's mixed PQ content and HLG content, we set the HDR
1950 // data space to be BT2020_PQ and convert HLG to PQ.
1951 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1952 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001953 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001954 break;
1955 default:
1956 break;
1957 }
Romain Guy54f154a2017-10-24 21:40:32 +01001958 }
1959
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001960 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001961}
1962
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001963// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001964void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1965 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001966 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1967 *outMode = ColorMode::NATIVE;
1968 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001969 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001970 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001971 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001972
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001973 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001974 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001975
Peiyong Lindfde5112018-06-05 10:58:41 -07001976 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001977 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001978 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001979 if (isHdr) {
1980 bestDataSpace = hdrDataSpace;
1981 }
1982
Chia-I Wu0d711262018-05-21 15:19:35 -07001983 RenderIntent intent;
1984 switch (mDisplayColorSetting) {
1985 case DisplayColorSetting::MANAGED:
1986 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001987 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001988 break;
1989 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001990 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001991 break;
1992 default: // vendor display color setting
1993 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1994 break;
1995 }
Chia-I Wube02ec02018-05-18 10:59:36 -07001996
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001997 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001998}
1999
Lloyd Pique074e8122018-07-26 12:57:23 -07002000void SurfaceFlinger::setUpHWComposer() {
2001 ATRACE_CALL();
2002 ALOGV("setUpHWComposer");
Lloyd Piqueb7d12302018-07-26 12:56:47 -07002003
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002004 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002005 bool dirty = !display->getDirtyRegion(mRepaintEverything).isEmpty();
2006 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2007 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
Jesse Hallb7a05492014-08-14 15:45:06 -07002008
2009 // If nothing has changed (!dirty), don't recompose.
2010 // If something changed, but we don't currently have any visible layers,
2011 // and didn't when we last did a composition, then skip it this time.
2012 // The second rule does two things:
2013 // - When all layers are removed from a display, we'll emit one black
2014 // frame, then nothing more until we get new layers.
2015 // - When a display is created with a private layer stack, we won't
2016 // emit any black frames until a layer is added to the layer stack.
2017 bool mustRecompose = dirty && !(empty && wasEmpty);
2018
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002019 ALOGV_IF(display->isVirtual(), "Display %d: %s composition (%sdirty %sempty %swasEmpty)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002020 display->getId(), mustRecompose ? "doing" : "skipping", dirty ? "+" : "-",
2021 empty ? "+" : "-", wasEmpty ? "+" : "-");
Jesse Hallb7a05492014-08-14 15:45:06 -07002022
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002023 display->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07002024
2025 if (mustRecompose) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002026 display->lastCompositionHadVisibleLayers = !empty;
Jesse Hallb7a05492014-08-14 15:45:06 -07002027 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07002028 }
2029
Lloyd Pique074e8122018-07-26 12:57:23 -07002030 // build the h/w work list
2031 if (CC_UNLIKELY(mGeometryInvalid)) {
2032 mGeometryInvalid = false;
2033 for (const auto& [token, display] : mDisplays) {
2034 const auto displayId = display->getId();
2035 if (displayId >= 0) {
2036 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
2037 for (size_t i = 0; i < currentLayers.size(); i++) {
2038 const auto& layer = currentLayers[i];
2039 if (!layer->hasHwcLayer(displayId)) {
2040 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
2041 layer->forceClientComposition(displayId);
2042 continue;
2043 }
2044 }
2045
2046 layer->setGeometry(display, i);
2047 if (mDebugDisableHWC || mDebugRegion) {
2048 layer->forceClientComposition(displayId);
2049 }
2050 }
2051 }
2052 }
2053 }
2054
2055 // Set the per-frame data
2056 for (const auto& [token, display] : mDisplays) {
2057 const auto displayId = display->getId();
2058 if (displayId < 0) {
2059 continue;
2060 }
2061
2062 if (mDrawingState.colorMatrixChanged) {
2063 display->setColorTransform(mDrawingState.colorMatrix);
2064 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
2065 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %d: %d",
2066 displayId, result);
2067 }
2068 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2069 if (layer->isHdrY410()) {
2070 layer->forceClientComposition(displayId);
2071 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2072 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
2073 !display->hasHDR10Support()) {
2074 layer->forceClientComposition(displayId);
2075 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2076 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
2077 !display->hasHLGSupport()) {
2078 layer->forceClientComposition(displayId);
2079 }
2080
2081 if (layer->getForceClientComposition(displayId)) {
2082 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2083 layer->setCompositionType(displayId, HWC2::Composition::Client);
2084 continue;
2085 }
2086
2087 layer->setPerFrameData(display);
2088 }
2089
2090 if (hasWideColorDisplay) {
2091 ColorMode colorMode;
2092 Dataspace dataSpace;
2093 RenderIntent renderIntent;
2094 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
2095 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
2096 }
2097 }
2098
2099 mDrawingState.colorMatrixChanged = false;
2100
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002101 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002102 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002103 continue;
2104 }
2105
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002106 status_t result = display->prepareFrame(*getBE().mHwc);
2107 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002108 display->getId(), result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002109 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002110}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002111
Mathias Agopiancd60f992012-08-16 16:28:27 -07002112void SurfaceFlinger::doComposition() {
2113 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002114 ALOGV("doComposition");
2115
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002116 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002117 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002118 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002119 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002120 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002121
2122 // repaint the framebuffer (if needed)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002123 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002124
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002125 display->dirtyRegion.clear();
2126 display->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002127 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002128 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002129 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002130}
2131
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002132void SurfaceFlinger::postFramebuffer()
2133{
Mathias Agopian841cde52012-03-01 15:44:37 -08002134 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002135 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002136
Mathias Agopiana44b0412011-10-16 18:46:35 -07002137 const nsecs_t now = systemTime();
2138 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002139
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002140 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002141 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002142 continue;
2143 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07002144 const auto displayId = display->getId();
2145 if (displayId >= 0) {
2146 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002147 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002148 display->onSwapBuffersCompleted();
2149 display->makeCurrent();
2150 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002151 sp<Fence> releaseFence = Fence::NO_FENCE;
2152
Chia-I Wu7b549592017-11-15 09:14:57 -08002153 // The layer buffer from the previous frame (if any) is released
2154 // by HWC only when the release fence from this frame (if any) is
2155 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002156 auto hwcLayer = layer->getHwcLayer(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002157 if (displayId >= 0) {
2158 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
2159 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002160
2161 // If the layer was client composited in the previous frame, we
2162 // need to merge with the previous client target acquire fence.
2163 // Since we do not track that, always merge with the current
2164 // client target acquire fence when it is available, even though
2165 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002166 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002167 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002168 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002169 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002170
David Sodmanb8af7922017-12-21 15:17:55 -08002171 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002172 }
Chia-I Wu83806892017-11-16 10:50:20 -08002173
2174 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002175 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002176 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002177 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002178 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002179 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002180 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002181 }
2182 }
2183
Dominik Laskowski7e045462018-05-30 13:02:02 -07002184 if (displayId >= 0) {
2185 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002186 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002187 }
2188
Mathias Agopiana44b0412011-10-16 18:46:35 -07002189 mLastSwapBufferTime = systemTime() - now;
2190 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002191
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002192 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002193 const auto display = getDefaultDisplayDeviceLocked();
2194 if (display && getHwComposer().isConnected(display->getId())) {
2195 const uint32_t flipCount = display->getPageFlipCount();
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002196 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2197 logFrameStats();
2198 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002199 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002200}
2201
Mathias Agopian87baae12012-07-31 12:38:26 -07002202void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002203{
Mathias Agopian841cde52012-03-01 15:44:37 -08002204 ATRACE_CALL();
2205
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002206 // here we keep a copy of the drawing state (that is the state that's
2207 // going to be overwritten by handleTransactionLocked()) outside of
2208 // mStateLock so that the side-effects of the State assignment
2209 // don't happen with mStateLock held (which can cause deadlocks).
2210 State drawingState(mDrawingState);
2211
Mathias Agopianca4d3602011-05-19 15:38:14 -07002212 Mutex::Autolock _l(mStateLock);
2213 const nsecs_t now = systemTime();
2214 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002215
Mathias Agopianca4d3602011-05-19 15:38:14 -07002216 // Here we're guaranteed that some transaction flags are set
2217 // so we can call handleTransactionLocked() unconditionally.
2218 // We call getTransactionFlags(), which will also clear the flags,
2219 // with mStateLock held to guarantee that mCurrentState won't change
2220 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002221
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002222 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002223 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002224 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002225
Mathias Agopianca4d3602011-05-19 15:38:14 -07002226 mLastTransactionTime = systemTime() - now;
2227 mDebugInTransaction = 0;
2228 invalidateHwcGeometry();
2229 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002230}
2231
Dominik Laskowski7e045462018-05-30 13:02:02 -07002232DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002233 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002234 // Figure out whether the event is for the primary display or an
2235 // external display by matching the Hwc display id against one for a
2236 // connected display. If we did not find a match, we then check what
2237 // displays are not already connected to determine the type. If we don't
2238 // have a connected primary display, we assume the new display is meant to
2239 // be the primary display, and then if we don't have an external display,
2240 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002241 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2242 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002243 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002244 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002245 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002246 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002247 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002248 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002249 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002250 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002251 return DisplayDevice::DISPLAY_EXTERNAL;
2252 }
2253
2254 return DisplayDevice::DISPLAY_ID_INVALID;
2255}
2256
Lloyd Piqueba04e622017-12-14 17:11:26 -08002257void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2258 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002259 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002260 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002261 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002262 continue;
2263 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002264
2265 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2266 ALOGE("External displays are not supported by the vr hardware composer.");
2267 continue;
2268 }
2269
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002270 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002271 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002272 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002273 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002274 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002275
2276 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002277 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002278 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002279 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002280 DisplayDeviceState info;
2281 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002282 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2283 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002284 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002285 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002286 mInterceptor->saveDisplayCreation(info);
2287 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002288 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002289 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002290
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002291 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002292 if (idx >= 0) {
2293 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002294 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002295 mCurrentState.displays.removeItemsAt(idx);
2296 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002297 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002298 }
2299
2300 processDisplayChangesLocked();
2301 }
2302
2303 mPendingHotplugEvents.clear();
2304}
2305
Lloyd Pique99d3da52018-01-22 17:48:03 -08002306sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002307 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002308 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002309 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002310 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002311 HdrCapabilities hdrCapabilities;
2312 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002313
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002314 if (hasWideColorDisplay && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002315 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002316 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002317 if (isWideColorMode(colorMode)) {
2318 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002319 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002320
Dominik Laskowski7e045462018-05-30 13:02:02 -07002321 std::vector<RenderIntent> renderIntents =
2322 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002323 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002324 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002325
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002326 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2327 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2328 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002329
2330 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2331 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2332
2333 /*
2334 * Create our display's surface
2335 */
2336 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2337 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002338 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002339 renderSurface->setNativeWindow(nativeWindow.get());
2340 const int displayWidth = renderSurface->queryWidth();
2341 const int displayHeight = renderSurface->queryHeight();
2342
2343 // Make sure that composition can never be stalled by a virtual display
2344 // consumer that isn't processing buffers fast enough. We have to do this
2345 // in two places:
2346 // * Here, in case the display is composed entirely by HWC.
2347 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2348 // window's swap interval in eglMakeCurrent, so they'll override the
2349 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002350 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002351 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2352 }
2353
2354 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002355 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002356
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002357 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002358 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2359 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2360 displayHeight, hasWideColorGamut, hdrCapabilities,
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002361 supportedPerFrameMetadata, hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002362
2363 if (maxFrameBufferAcquiredBuffers >= 3) {
2364 nativeWindowSurface->preallocateBuffers();
2365 }
2366
2367 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002368 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2369 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002370 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002371 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002372 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002373 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002374 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002375 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002376 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002377 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002378 display->setLayerStack(state.layerStack);
2379 display->setProjection(state.orientation, state.viewport, state.frame);
2380 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002381
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002382 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002383}
2384
Lloyd Pique347200f2017-12-14 17:00:15 -08002385void SurfaceFlinger::processDisplayChangesLocked() {
2386 // here we take advantage of Vector's copy-on-write semantics to
2387 // improve performance by skipping the transaction entirely when
2388 // know that the lists are identical
2389 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2390 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2391 if (!curr.isIdenticalTo(draw)) {
2392 mVisibleRegionsDirty = true;
2393 const size_t cc = curr.size();
2394 size_t dc = draw.size();
2395
2396 // find the displays that were removed
2397 // (ie: in drawing state but not in current state)
2398 // also handle displays that changed
2399 // (ie: displays that are in both lists)
2400 for (size_t i = 0; i < dc;) {
2401 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2402 if (j < 0) {
2403 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002404 // Call makeCurrent() on the primary display so we can
2405 // be sure that nothing associated with this display
2406 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002407 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2408 defaultDisplay->makeCurrent();
2409 }
2410 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2411 display->disconnect(getHwComposer());
2412 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002413 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2414 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2415 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2416 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2417 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002418 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002419 } else {
2420 // this display is in both lists. see if something changed.
2421 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002422 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002423 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2424 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2425 if (state_binder != draw_binder) {
2426 // changing the surface is like destroying and
2427 // recreating the DisplayDevice, so we just remove it
2428 // from the drawing state, so that it get re-added
2429 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002430 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2431 display->disconnect(getHwComposer());
2432 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002433 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002434 mDrawingState.displays.removeItemsAt(i);
2435 dc--;
2436 // at this point we must loop to the next item
2437 continue;
2438 }
2439
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002440 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002441 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002442 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002443 }
2444 if ((state.orientation != draw[i].orientation) ||
2445 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002446 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002447 }
2448 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002449 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002450 }
2451 }
2452 }
2453 ++i;
2454 }
2455
2456 // find displays that were added
2457 // (ie: in current state but not in drawing state)
2458 for (size_t i = 0; i < cc; i++) {
2459 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2460 const DisplayDeviceState& state(curr[i]);
2461
2462 sp<DisplaySurface> dispSurface;
2463 sp<IGraphicBufferProducer> producer;
2464 sp<IGraphicBufferProducer> bqProducer;
2465 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002466 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002467
Dominik Laskowski7e045462018-05-30 13:02:02 -07002468 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002469 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002470 // Virtual displays without a surface are dormant:
2471 // they have external state (layer stack, projection,
2472 // etc.) but no internal state (i.e. a DisplayDevice).
2473 if (state.surface != nullptr) {
2474 // Allow VR composer to use virtual displays.
2475 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2476 int width = 0;
2477 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2478 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2479 int height = 0;
2480 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2481 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2482 int intFormat = 0;
2483 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2484 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002485 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002486
Dominik Laskowski7e045462018-05-30 13:02:02 -07002487 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2488 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002489 }
2490
2491 // TODO: Plumb requested format back up to consumer
2492
2493 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002494 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002495 bqProducer, bqConsumer,
2496 state.displayName);
2497
2498 dispSurface = vds;
2499 producer = vds;
2500 }
2501 } else {
2502 ALOGE_IF(state.surface != nullptr,
2503 "adding a supported display, but rendering "
2504 "surface is provided (%p), ignoring it",
2505 state.surface.get());
2506
Dominik Laskowski7e045462018-05-30 13:02:02 -07002507 displayId = state.type;
2508 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002509 producer = bqProducer;
2510 }
2511
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002512 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002513 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002514 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002515 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002516 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002517 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002518 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2519 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2520 true);
2521 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2522 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2523 true);
2524 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002525 }
2526 }
2527 }
2528 }
2529 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002530
2531 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002532}
2533
Mathias Agopian87baae12012-07-31 12:38:26 -07002534void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002535{
Dan Stoza7dde5992015-05-22 09:51:44 -07002536 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002537 mCurrentState.traverseInZOrder([](Layer* layer) {
2538 layer->notifyAvailableFrames();
2539 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002540
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002541 /*
2542 * Traversal of the children
2543 * (perform the transaction for each of them if needed)
2544 */
2545
Mathias Agopian3559b072012-08-15 13:46:03 -07002546 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002547 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002548 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002549 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002550
2551 const uint32_t flags = layer->doTransaction(0);
2552 if (flags & Layer::eVisibleRegion)
2553 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002554 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002555 }
2556
2557 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002558 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002559 */
2560
Mathias Agopiane57f2922012-08-09 16:29:12 -07002561 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002562 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002563 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002564 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002565
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002566 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002567 // The transform hint might have changed for some layers
2568 // (either because a display has changed, or because a layer
2569 // as changed).
2570 //
2571 // Walk through all the layers in currentLayers,
2572 // and update their transform hint.
2573 //
2574 // If a layer is visible only on a single display, then that
2575 // display is used to calculate the hint, otherwise we use the
2576 // default display.
2577 //
2578 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2579 // the hint is set before we acquire a buffer from the surface texture.
2580 //
2581 // NOTE: layer transactions have taken place already, so we use their
2582 // drawing state. However, SurfaceFlinger's own transaction has not
2583 // happened yet, so we must use the current state layer list
2584 // (soon to become the drawing state list).
2585 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002586 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002587 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002588 bool first = true;
2589 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002590 // NOTE: we rely on the fact that layers are sorted by
2591 // layerStack first (so we don't have to traverse the list
2592 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002593 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002594 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002595 currentlayerStack = layerStack;
2596 // figure out if this layerstack is mirrored
2597 // (more than one display) if so, pick the default display,
2598 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002599 hintDisplay = nullptr;
2600 for (const auto& [token, display] : mDisplays) {
2601 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2602 if (hintDisplay) {
2603 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002604 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002605 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002606 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002607 }
2608 }
2609 }
2610 }
Chet Haase91d25932013-04-11 15:24:55 -07002611
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002612 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002613 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2614 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002615
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002616 // could be null when this layer is using a layerStack
2617 // that is not visible on any display. Also can occur at
2618 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002619 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002620 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002621
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002622 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002623 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002624 if (hintDisplay) {
2625 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002626 }
Robert Carr2047fae2016-11-28 14:09:09 -08002627
2628 first = false;
2629 });
Mathias Agopian84300952012-11-21 16:02:13 -08002630 }
2631
2632
Mathias Agopian3559b072012-08-15 13:46:03 -07002633 /*
2634 * Perform our own transaction if needed
2635 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002636
2637 if (mLayersAdded) {
2638 mLayersAdded = false;
2639 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002640 mVisibleRegionsDirty = true;
2641 }
2642
2643 // some layers might have been removed, so
2644 // we need to update the regions they're exposing.
2645 if (mLayersRemoved) {
2646 mLayersRemoved = false;
2647 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002648 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002649 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002650 // this layer is not visible anymore
2651 // TODO: we could traverse the tree from front to back and
2652 // compute the actual visible region
2653 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002654 Region visibleReg;
2655 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002656 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002657 }
Robert Carr2047fae2016-11-28 14:09:09 -08002658 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002659 }
2660
2661 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002662
2663 updateCursorAsync();
2664}
2665
2666void SurfaceFlinger::updateCursorAsync()
2667{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002668 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002669 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002670 continue;
2671 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002672
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002673 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2674 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002675 }
2676 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002677}
2678
2679void SurfaceFlinger::commitTransaction()
2680{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002681 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002682 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002683 for (const auto& l : mLayersPendingRemoval) {
2684 recordBufferingStats(l->getName().string(),
2685 l->getOccupancyHistory(true));
2686 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002687 }
2688 mLayersPendingRemoval.clear();
2689 }
2690
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002691 // If this transaction is part of a window animation then the next frame
2692 // we composite should be considered an animation as well.
2693 mAnimCompositionPending = mAnimTransactionPending;
2694
Mathias Agopian4fec8732012-06-29 14:12:52 -07002695 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002696 // clear the "changed" flags in current state
2697 mCurrentState.colorMatrixChanged = false;
2698
Robert Carr1f0a16a2016-10-24 16:27:39 -07002699 mDrawingState.traverseInZOrder([](Layer* layer) {
2700 layer->commitChildList();
2701 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002702 mTransactionPending = false;
2703 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002704 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002705}
2706
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002707void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2708 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002709 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002710 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002711
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002712 Region aboveOpaqueLayers;
2713 Region aboveCoveredLayers;
2714 Region dirty;
2715
Mathias Agopian87baae12012-07-31 12:38:26 -07002716 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002717
Robert Carr2047fae2016-11-28 14:09:09 -08002718 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002719 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002720 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002721
Jesse Hall01e29052013-02-19 16:13:35 -08002722 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002723 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002724 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002725 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002726
Mathias Agopianab028732010-03-16 16:41:46 -07002727 /*
2728 * opaqueRegion: area of a surface that is fully opaque.
2729 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002730 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002731
2732 /*
2733 * visibleRegion: area of a surface that is visible on screen
2734 * and not fully transparent. This is essentially the layer's
2735 * footprint minus the opaque regions above it.
2736 * Areas covered by a translucent surface are considered visible.
2737 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002738 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002739
2740 /*
2741 * coveredRegion: area of a surface that is covered by all
2742 * visible regions above it (which includes the translucent areas).
2743 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002744 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002745
Jesse Halla8026d22012-09-25 13:25:04 -07002746 /*
2747 * transparentRegion: area of a surface that is hinted to be completely
2748 * transparent. This is only used to tell when the layer has no visible
2749 * non-transparent regions and can be removed from the layer list. It
2750 * does not affect the visibleRegion of this layer or any layers
2751 * beneath it. The hint may not be correct if apps don't respect the
2752 * SurfaceView restrictions (which, sadly, some don't).
2753 */
2754 Region transparentRegion;
2755
Mathias Agopianab028732010-03-16 16:41:46 -07002756
2757 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002758 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002759 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002760 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002761 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002762 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002763 if (!visibleRegion.isEmpty()) {
2764 // Remove the transparent area from the visible region
2765 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002766 if (tr.preserveRects()) {
2767 // transform the transparent region
2768 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002769 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002770 // transformation too complex, can't do the
2771 // transparent region optimization.
2772 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002773 }
Mathias Agopianab028732010-03-16 16:41:46 -07002774 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002775
Mathias Agopianab028732010-03-16 16:41:46 -07002776 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002777 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002778 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002779 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2780 // the opaque region is the layer's footprint
2781 opaqueRegion = visibleRegion;
2782 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002783 }
2784 }
2785
Robert Carre5f4f692018-01-12 13:12:28 -08002786 if (visibleRegion.isEmpty()) {
2787 layer->clearVisibilityRegions();
2788 return;
2789 }
2790
Mathias Agopianab028732010-03-16 16:41:46 -07002791 // Clip the covered region to the visible region
2792 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2793
2794 // Update aboveCoveredLayers for next (lower) layer
2795 aboveCoveredLayers.orSelf(visibleRegion);
2796
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002797 // subtract the opaque region covered by the layers above us
2798 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002799
2800 // compute this layer's dirty region
2801 if (layer->contentDirty) {
2802 // we need to invalidate the whole region
2803 dirty = visibleRegion;
2804 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002805 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002806 layer->contentDirty = false;
2807 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002808 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002809 * the exposed region consists of two components:
2810 * 1) what's VISIBLE now and was COVERED before
2811 * 2) what's EXPOSED now less what was EXPOSED before
2812 *
2813 * note that (1) is conservative, we start with the whole
2814 * visible region but only keep what used to be covered by
2815 * something -- which mean it may have been exposed.
2816 *
2817 * (2) handles areas that were not covered by anything but got
2818 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002819 */
Mathias Agopianab028732010-03-16 16:41:46 -07002820 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002821 const Region oldVisibleRegion = layer->visibleRegion;
2822 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002823 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2824 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002825 }
2826 dirty.subtractSelf(aboveOpaqueLayers);
2827
2828 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002829 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002830
Mathias Agopianab028732010-03-16 16:41:46 -07002831 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002832 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002833
Jesse Halla8026d22012-09-25 13:25:04 -07002834 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002835 layer->setVisibleRegion(visibleRegion);
2836 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002837 layer->setVisibleNonTransparentRegion(
2838 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002839 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002840
Mathias Agopian87baae12012-07-31 12:38:26 -07002841 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002842}
2843
Chia-I Wuab0c3192017-08-01 11:29:00 -07002844void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002845 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002846 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2847 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002848 }
2849 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002850}
2851
Dan Stoza6b9454d2014-11-07 16:00:59 -08002852bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002853{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002854 ALOGV("handlePageFlip");
2855
Brian Andersond6927fb2016-07-23 23:37:30 -07002856 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002857
Mathias Agopian4fec8732012-06-29 14:12:52 -07002858 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002859 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002860 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002861
2862 // Store the set of layers that need updates. This set must not change as
2863 // buffers are being latched, as this could result in a deadlock.
2864 // Example: Two producers share the same command stream and:
2865 // 1.) Layer 0 is latched
2866 // 2.) Layer 0 gets a new frame
2867 // 2.) Layer 1 gets a new frame
2868 // 3.) Layer 1 is latched.
2869 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2870 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002871 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002872 if (layer->hasQueuedFrame()) {
2873 frameQueued = true;
2874 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002875 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002876 } else {
2877 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002878 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002879 } else {
2880 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002881 }
Robert Carr2047fae2016-11-28 14:09:09 -08002882 });
2883
Dan Stoza9e56aa02015-11-02 13:00:03 -08002884 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002885 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002886 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002887 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002888 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002889 newDataLatched = true;
2890 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002891 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002892
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002893 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002894
2895 // If we will need to wake up at some time in the future to deal with a
2896 // queued frame that shouldn't be displayed during this vsync period, wake
2897 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002898 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002899 signalLayerUpdate();
2900 }
2901
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002902 // enter boot animation on first buffer latch
2903 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2904 ALOGI("Enter boot animation");
2905 mBootStage = BootStage::BOOTANIMATION;
2906 }
2907
Dan Stoza6b9454d2014-11-07 16:00:59 -08002908 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002909 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002910}
2911
Mathias Agopianad456f92011-01-13 17:53:01 -08002912void SurfaceFlinger::invalidateHwcGeometry()
2913{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002914 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002915}
2916
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002917void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2918 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002919 // We only need to actually compose the display if:
2920 // 1) It is being handled by hardware composer, which may need this to
2921 // keep its virtual display state machine in sync, or
2922 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002923 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002924 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002925 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002926 return;
2927 }
2928
Dan Stoza9e56aa02015-11-02 13:00:03 -08002929 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002930 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002931
2932 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002933 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002934}
2935
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002936bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002937 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002938
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002939 const Region bounds(display->bounds());
2940 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002941 const auto displayId = display->getId();
2942 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002943 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002944
Chia-I Wu8e50e692018-05-04 10:12:37 -07002945 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002946 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002947
Dan Stoza9e56aa02015-11-02 13:00:03 -08002948 if (hasClientComposition) {
2949 ALOGV("hasClientComposition");
2950
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002951 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002952 if (display->hasWideColorGamut()) {
2953 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002954 }
2955 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002956 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002957 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002958
Dominik Laskowski7e045462018-05-30 13:02:02 -07002959 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002960 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2961 HWC2::Capability::SkipClientColorTransform);
2962
Chia-I Wud49d6692018-06-27 07:17:41 +08002963 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002964 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2965 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08002966 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002967 }
2968
Chia-I Wud49d6692018-06-27 07:17:41 +08002969 // The current enhanced saturation matrix is designed to enhance Display P3,
2970 // thus we only apply this matrix when the render intent is not colorimetric
2971 // and the output color space is Display P3.
2972 needsEnhancedColorMatrix =
2973 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2974 outputDataspace == Dataspace::DISPLAY_P3);
2975 if (needsEnhancedColorMatrix) {
2976 colorMatrix *= mEnhancedSaturationMatrix;
2977 }
2978
2979 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002980
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002981 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002982 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002983 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002984 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002985
2986 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002987 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
2988 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
2989 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07002990 }
2991 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002992 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002993
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002994 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002995 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002996 // when using overlays, we assume a fully transparent framebuffer
2997 // NOTE: we could reduce how much we need to clear, for instance
2998 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002999 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003000 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003001 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003002 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003003 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003004 // we're left with the letterbox region
3005 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003006 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003007
3008 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003009 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003010
Mathias Agopianb9494d52012-04-18 02:28:45 -07003011 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003012 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003013 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003014 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003015 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003016 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003017
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003018 if (!display->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07003019 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07003020 // scissor on the main display. It should never be needed
3021 // anyways (though in theory it could since the API allows it).
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003022 const Rect& bounds = display->getBounds();
3023 const Rect& scissor = display->getScissor();
Mathias Agopianf45c5102012-10-24 16:29:17 -07003024 if (scissor != bounds) {
3025 // scissor doesn't match the screen's dimensions, so we
3026 // need to clear everything outside of it and enable
3027 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003028
Mathias Agopianf45c5102012-10-24 16:29:17 -07003029 // enable scissor for this frame
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003030 const uint32_t height = display->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08003031 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07003032 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003033 }
3034 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003035 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003036
Mathias Agopian85d751c2012-08-29 16:59:24 -07003037 /*
3038 * and then, render the layers targeted at the framebuffer
3039 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003040
Dan Stoza9e56aa02015-11-02 13:00:03 -08003041 ALOGV("Rendering client layers");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003042 const Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003043 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003044 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003045 const Region clip(bounds.intersect(
3046 displayTransform.transform(layer->visibleRegion)));
3047 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07003048 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003049 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003050 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003051 case HWC2::Composition::Cursor:
3052 case HWC2::Composition::Device:
3053 case HWC2::Composition::Sideband:
3054 case HWC2::Composition::SolidColor: {
3055 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07003056 if (layer->getClearClientTarget(displayId) && !firstLayer &&
Rajavenu Kyatham2eae6d32018-04-10 12:34:05 +05303057 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3058 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003059 // never clear the very first layer since we're
3060 // guaranteed the FB is already cleared
3061 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003062 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003063 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003064 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003065 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003066 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003067 break;
3068 }
3069 default:
3070 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003071 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003072 } else {
3073 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003074 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003075 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003076 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003077
Chia-I Wud49d6692018-06-27 07:17:41 +08003078 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003079 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003080 }
3081
Mathias Agopianf45c5102012-10-24 16:29:17 -07003082 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003083 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003084 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003085}
3086
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003087void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
3088 const Region& region) const {
3089 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003090 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003091 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003092}
3093
Dan Stoza7d89d062015-04-30 13:29:25 -07003094status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003095 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003096 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003097 const sp<Layer>& lbc,
3098 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003099{
Dan Stoza7d89d062015-04-30 13:29:25 -07003100 // add this layer to the current state list
3101 {
3102 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003103 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003104 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3105 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003106 return NO_MEMORY;
3107 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003108 if (parent == nullptr) {
3109 mCurrentState.layersSortedByZ.add(lbc);
3110 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003111 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003112 ALOGE("addClientLayer called with a removed parent");
3113 return NAME_NOT_FOUND;
3114 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003115 parent->addChild(lbc);
3116 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003117
Yiwei Zhang243b3782018-05-15 17:40:04 -07003118 if (gbc != nullptr) {
3119 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3120 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3121 mMaxGraphicBufferProducerListSize,
3122 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3123 mGraphicBufferProducerList.size(),
3124 mMaxGraphicBufferProducerListSize, mNumLayers);
3125 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003126 mLayersAdded = true;
3127 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003128 }
3129
Mathias Agopian96f08192010-06-02 23:28:45 -07003130 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003131 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003132
Dan Stoza7d89d062015-04-30 13:29:25 -07003133 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003134}
3135
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003136status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003137 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003138 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3139}
Robert Carr7f9b8992017-03-10 11:08:39 -08003140
chaviwca27f252018-02-06 16:46:39 -08003141status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3142 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003143 if (layer->isPendingRemoval()) {
3144 return NO_ERROR;
3145 }
3146
Robert Carr1f0a16a2016-10-24 16:27:39 -07003147 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003148 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003149 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003150 if (topLevelOnly) {
3151 return NO_ERROR;
3152 }
3153
Chia-I Wu98f1c102017-05-30 14:54:08 -07003154 sp<Layer> ancestor = p;
3155 while (ancestor->getParent() != nullptr) {
3156 ancestor = ancestor->getParent();
3157 }
3158 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3159 ALOGE("removeLayer called with a layer whose parent has been removed");
3160 return NAME_NOT_FOUND;
3161 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003162
3163 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003164 } else {
3165 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003166 }
3167
Robert Carr136e2f62017-02-08 17:54:29 -08003168 // As a matter of normal operation, the LayerCleaner will produce a second
3169 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3170 // so we will succeed in promoting it, but it's already been removed
3171 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3172 // otherwise something has gone wrong and we are leaking the layer.
3173 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003174 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3175 layer->getName().string(),
3176 (p != nullptr) ? p->getName().string() : "no-parent");
3177 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003178 } else if (index < 0) {
3179 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003180 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003181
Chia-I Wuc6657022017-08-15 11:18:17 -07003182 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003183 mLayersPendingRemoval.add(layer);
3184 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003185 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003186 setTransactionFlags(eTransactionNeeded);
3187 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003188}
3189
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003190uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003191 return android_atomic_release_load(&mTransactionFlags);
3192}
3193
Mathias Agopian3f844832013-08-07 21:24:32 -07003194uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003195 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3196}
3197
Mathias Agopian3f844832013-08-07 21:24:32 -07003198uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003199 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3200}
3201
3202uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3203 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003204 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003205 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003206 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003207 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003208 }
3209 return old;
3210}
3211
chaviwca27f252018-02-06 16:46:39 -08003212bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3213 for (const ComposerState& state : states) {
3214 // Here we need to check that the interface we're given is indeed
3215 // one of our own. A malicious client could give us a nullptr
3216 // IInterface, or one of its own or even one of our own but a
3217 // different type. All these situations would cause us to crash.
3218 if (state.client == nullptr) {
3219 return true;
3220 }
3221
3222 sp<IBinder> binder = IInterface::asBinder(state.client);
3223 if (binder == nullptr) {
3224 return true;
3225 }
3226
3227 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3228 return true;
3229 }
3230 }
3231 return false;
3232}
3233
Mathias Agopian8b33f032012-07-24 20:43:54 -07003234void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003235 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003236 const Vector<DisplayState>& displays,
3237 uint32_t flags)
3238{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003239 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003240 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003241 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003242
chaviwca27f252018-02-06 16:46:39 -08003243 if (containsAnyInvalidClientState(states)) {
3244 return;
3245 }
3246
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003247 if (flags & eAnimation) {
3248 // For window updates that are part of an animation we must wait for
3249 // previous animation "frames" to be handled.
3250 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003251 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003252 if (CC_UNLIKELY(err != NO_ERROR)) {
3253 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003254 // caller after a few seconds.
3255 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3256 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003257 mAnimTransactionPending = false;
3258 break;
3259 }
3260 }
3261 }
3262
chaviwca27f252018-02-06 16:46:39 -08003263 for (const DisplayState& display : displays) {
3264 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003265 }
3266
chaviwca27f252018-02-06 16:46:39 -08003267 for (const ComposerState& state : states) {
3268 transactionFlags |= setClientStateLocked(state);
3269 }
3270
3271 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3272 // as destroyed should only occur after setting all other states. This is to allow for a
3273 // child re-parent to happen before marking its original parent as destroyed (which would
3274 // then mark the child as destroyed).
3275 for (const ComposerState& state : states) {
3276 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003277 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003278
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003279 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3280 // anyway. This can be used as a flush mechanism for previous async transactions.
3281 // Empty animation transaction can be used to simulate back-pressure, so also force a
3282 // transaction for empty animation transactions.
3283 if (transactionFlags == 0 &&
3284 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003285 transactionFlags = eTransactionNeeded;
3286 }
3287
Mathias Agopian386aa982011-11-07 21:58:03 -08003288 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003289 if (mInterceptor->isEnabled()) {
3290 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003291 }
Irvel468051e2016-06-13 16:44:44 -07003292
Mathias Agopian386aa982011-11-07 21:58:03 -08003293 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003294 const auto start = (flags & eEarlyWakeup)
3295 ? VSyncModulator::TransactionStart::EARLY
3296 : VSyncModulator::TransactionStart::NORMAL;
3297 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003298
3299 // if this is a synchronous transaction, wait for it to take effect
3300 // before returning.
3301 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003302 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003303 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003304 if (flags & eAnimation) {
3305 mAnimTransactionPending = true;
3306 }
3307 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003308 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3309 if (CC_UNLIKELY(err != NO_ERROR)) {
3310 // just in case something goes wrong in SF, return to the
3311 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003312 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3313 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003314 break;
3315 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003316 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003317 }
3318}
3319
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003320uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3321 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3322 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003323
Mathias Agopiane57f2922012-08-09 16:29:12 -07003324 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003325 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3326
3327 const uint32_t what = s.what;
3328 if (what & DisplayState::eSurfaceChanged) {
3329 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3330 state.surface = s.surface;
3331 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003332 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003333 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003334 if (what & DisplayState::eLayerStackChanged) {
3335 if (state.layerStack != s.layerStack) {
3336 state.layerStack = s.layerStack;
3337 flags |= eDisplayTransactionNeeded;
3338 }
3339 }
3340 if (what & DisplayState::eDisplayProjectionChanged) {
3341 if (state.orientation != s.orientation) {
3342 state.orientation = s.orientation;
3343 flags |= eDisplayTransactionNeeded;
3344 }
3345 if (state.frame != s.frame) {
3346 state.frame = s.frame;
3347 flags |= eDisplayTransactionNeeded;
3348 }
3349 if (state.viewport != s.viewport) {
3350 state.viewport = s.viewport;
3351 flags |= eDisplayTransactionNeeded;
3352 }
3353 }
3354 if (what & DisplayState::eDisplaySizeChanged) {
3355 if (state.width != s.width) {
3356 state.width = s.width;
3357 flags |= eDisplayTransactionNeeded;
3358 }
3359 if (state.height != s.height) {
3360 state.height = s.height;
3361 flags |= eDisplayTransactionNeeded;
3362 }
3363 }
3364
Mathias Agopiane57f2922012-08-09 16:29:12 -07003365 return flags;
3366}
3367
Robert Carrd4ae7f32018-06-07 16:10:57 -07003368bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3369 IPCThreadState* ipc = IPCThreadState::self();
3370 const int pid = ipc->getCallingPid();
3371 const int uid = ipc->getCallingUid();
3372
3373 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3374 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3375 return false;
3376 }
3377 return true;
3378}
3379
chaviwca27f252018-02-06 16:46:39 -08003380uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3381 const layer_state_t& s = composerState.state;
3382 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3383
Mathias Agopian13127d82013-03-05 17:47:11 -08003384 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003385 if (layer == nullptr) {
3386 return 0;
3387 }
3388
3389 if (layer->isPendingRemoval()) {
3390 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3391 return 0;
3392 }
3393
3394 uint32_t flags = 0;
3395
3396 const uint32_t what = s.what;
3397 bool geometryAppliesWithResize =
3398 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003399
3400 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3401 // pending state will also be deferred.
3402 if (what & layer_state_t::eDeferTransaction) {
3403 layer->pushPendingState();
3404 }
3405
chaviw8b3871a2017-11-01 17:41:01 -07003406 if (what & layer_state_t::ePositionChanged) {
3407 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3408 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003409 }
chaviw8b3871a2017-11-01 17:41:01 -07003410 }
3411 if (what & layer_state_t::eLayerChanged) {
3412 // NOTE: index needs to be calculated before we update the state
3413 const auto& p = layer->getParent();
3414 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003415 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003416 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003417 mCurrentState.layersSortedByZ.removeAt(idx);
3418 mCurrentState.layersSortedByZ.add(layer);
3419 // we need traversal (state changed)
3420 // AND transaction (list changed)
3421 flags |= eTransactionNeeded|eTraversalNeeded;
3422 }
chaviw8b3871a2017-11-01 17:41:01 -07003423 } else {
3424 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003425 flags |= eTransactionNeeded|eTraversalNeeded;
3426 }
3427 }
chaviw8b3871a2017-11-01 17:41:01 -07003428 }
3429 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003430 // NOTE: index needs to be calculated before we update the state
3431 const auto& p = layer->getParent();
3432 if (p == nullptr) {
3433 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3434 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3435 mCurrentState.layersSortedByZ.removeAt(idx);
3436 mCurrentState.layersSortedByZ.add(layer);
3437 // we need traversal (state changed)
3438 // AND transaction (list changed)
3439 flags |= eTransactionNeeded|eTraversalNeeded;
3440 }
3441 } else {
3442 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3443 flags |= eTransactionNeeded|eTraversalNeeded;
3444 }
chaviw8b3871a2017-11-01 17:41:01 -07003445 }
3446 }
3447 if (what & layer_state_t::eSizeChanged) {
3448 if (layer->setSize(s.w, s.h)) {
3449 flags |= eTraversalNeeded;
3450 }
3451 }
3452 if (what & layer_state_t::eAlphaChanged) {
3453 if (layer->setAlpha(s.alpha))
3454 flags |= eTraversalNeeded;
3455 }
3456 if (what & layer_state_t::eColorChanged) {
3457 if (layer->setColor(s.color))
3458 flags |= eTraversalNeeded;
3459 }
3460 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003461 // TODO: b/109894387
3462 //
3463 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3464 // rotation. To see the problem observe that if we have a square parent, and a child
3465 // of the same size, then we rotate the child 45 degrees around it's center, the child
3466 // must now be cropped to a non rectangular 8 sided region.
3467 //
3468 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3469 // private API, and the WindowManager only uses rotation in one case, which is on a top
3470 // level layer in which cropping is not an issue.
3471 //
3472 // However given that abuse of rotation matrices could lead to surfaces extending outside
3473 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3474 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3475 // transformations.
3476 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003477 flags |= eTraversalNeeded;
3478 }
3479 if (what & layer_state_t::eTransparentRegionChanged) {
3480 if (layer->setTransparentRegionHint(s.transparentRegion))
3481 flags |= eTraversalNeeded;
3482 }
3483 if (what & layer_state_t::eFlagsChanged) {
3484 if (layer->setFlags(s.flags, s.mask))
3485 flags |= eTraversalNeeded;
3486 }
3487 if (what & layer_state_t::eCropChanged) {
3488 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3489 flags |= eTraversalNeeded;
3490 }
3491 if (what & layer_state_t::eFinalCropChanged) {
3492 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3493 flags |= eTraversalNeeded;
3494 }
3495 if (what & layer_state_t::eLayerStackChanged) {
3496 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3497 // We only allow setting layer stacks for top level layers,
3498 // everything else inherits layer stack from its parent.
3499 if (layer->hasParent()) {
3500 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3501 layer->getName().string());
3502 } else if (idx < 0) {
3503 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3504 "that also does not appear in the top level layer list. Something"
3505 " has gone wrong.", layer->getName().string());
3506 } else if (layer->setLayerStack(s.layerStack)) {
3507 mCurrentState.layersSortedByZ.removeAt(idx);
3508 mCurrentState.layersSortedByZ.add(layer);
3509 // we need traversal (state changed)
3510 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003511 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003512 }
3513 }
3514 if (what & layer_state_t::eDeferTransaction) {
3515 if (s.barrierHandle != nullptr) {
3516 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3517 } else if (s.barrierGbp != nullptr) {
3518 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3519 if (authenticateSurfaceTextureLocked(gbp)) {
3520 const auto& otherLayer =
3521 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3522 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3523 } else {
3524 ALOGE("Attempt to defer transaction to to an"
3525 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003526 }
3527 }
chaviw8b3871a2017-11-01 17:41:01 -07003528 // We don't trigger a traversal here because if no other state is
3529 // changed, we don't want this to cause any more work
3530 }
3531 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003532 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003533 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003534 if (!hadParent) {
3535 mCurrentState.layersSortedByZ.remove(layer);
3536 }
chaviw8b3871a2017-11-01 17:41:01 -07003537 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003538 }
chaviw8b3871a2017-11-01 17:41:01 -07003539 }
3540 if (what & layer_state_t::eReparentChildren) {
3541 if (layer->reparentChildren(s.reparentHandle)) {
3542 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003543 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003544 }
chaviw8b3871a2017-11-01 17:41:01 -07003545 if (what & layer_state_t::eDetachChildren) {
3546 layer->detachChildren();
3547 }
3548 if (what & layer_state_t::eOverrideScalingModeChanged) {
3549 layer->setOverrideScalingMode(s.overrideScalingMode);
3550 // We don't trigger a traversal here because if no other state is
3551 // changed, we don't want this to cause any more work
3552 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003553 return flags;
3554}
3555
chaviwca27f252018-02-06 16:46:39 -08003556void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3557 const layer_state_t& state = composerState.state;
3558 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3559
3560 sp<Layer> layer(client->getLayerUser(state.surface));
3561 if (layer == nullptr) {
3562 return;
3563 }
3564
3565 if (layer->isPendingRemoval()) {
3566 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3567 return;
3568 }
3569
3570 if (state.what & layer_state_t::eDestroySurface) {
3571 removeLayerLocked(mStateLock, layer);
3572 }
3573}
3574
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003575status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003576 const String8& name,
3577 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003578 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003579 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003580 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003581{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003582 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003583 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003584 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003585 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003586 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003587
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003588 status_t result = NO_ERROR;
3589
3590 sp<Layer> layer;
3591
Cody Northropbc755282017-03-31 12:00:08 -06003592 String8 uniqueName = getUniqueLayerName(name);
3593
Mathias Agopian3165cc22012-08-08 19:42:09 -07003594 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3595 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003596 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003597 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003598 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003599
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003600 break;
chaviw13fdc492017-06-27 12:40:18 -07003601 case ISurfaceComposerClient::eFXSurfaceColor:
3602 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003603 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003604 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003605 break;
3606 default:
3607 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003608 break;
3609 }
3610
Dan Stoza7d89d062015-04-30 13:29:25 -07003611 if (result != NO_ERROR) {
3612 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003613 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003614
Chia-I Wuab0c3192017-08-01 11:29:00 -07003615 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3616 // TODO b/64227542
3617 if (windowType == 441731) {
3618 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3619 layer->setPrimaryDisplayOnly();
3620 }
3621
Albert Chaulk479c60c2017-01-27 14:21:34 -05003622 layer->setInfo(windowType, ownerUid);
3623
Robert Carr1f0a16a2016-10-24 16:27:39 -07003624 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003625 if (result != NO_ERROR) {
3626 return result;
3627 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003628 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003629
3630 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003631 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003632}
3633
Cody Northropbc755282017-03-31 12:00:08 -06003634String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3635{
3636 bool matchFound = true;
3637 uint32_t dupeCounter = 0;
3638
3639 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3640 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3641
Dan Stoza436ccf32018-06-21 12:10:12 -07003642 // Grab the state lock since we're accessing mCurrentState
3643 Mutex::Autolock lock(mStateLock);
3644
Cody Northropbc755282017-03-31 12:00:08 -06003645 // Loop over layers until we're sure there is no matching name
3646 while (matchFound) {
3647 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003648 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003649 if (layer->getName() == uniqueName) {
3650 matchFound = true;
3651 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3652 }
3653 });
3654 }
3655
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003656 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3657 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003658
3659 return uniqueName;
3660}
3661
David Sodman0c69cad2017-08-21 12:12:51 -07003662status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003663 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3664 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003665{
3666 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003667 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003668 case PIXEL_FORMAT_TRANSPARENT:
3669 case PIXEL_FORMAT_TRANSLUCENT:
3670 format = PIXEL_FORMAT_RGBA_8888;
3671 break;
3672 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003673 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003674 break;
3675 }
3676
David Sodman0c69cad2017-08-21 12:12:51 -07003677 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3678 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003679 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003680 *handle = layer->getHandle();
3681 *gbp = layer->getProducer();
3682 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003683 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003684
David Sodman0c69cad2017-08-21 12:12:51 -07003685 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003686 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003687}
3688
chaviw13fdc492017-06-27 12:40:18 -07003689status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003690 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003691 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003692{
chaviw13fdc492017-06-27 12:40:18 -07003693 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003694 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003695 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003696}
3697
Mathias Agopianac9fa422013-02-11 16:40:36 -08003698status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003699{
Robert Carr9524cb32017-02-13 11:32:32 -08003700 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003701 status_t err = NO_ERROR;
3702 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003703 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003704 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003705 err = removeLayer(l);
3706 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3707 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003708 }
3709 return err;
3710}
3711
Mathias Agopian13127d82013-03-05 17:47:11 -08003712status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003713{
Mathias Agopian67106042013-03-14 19:18:13 -07003714 // called by ~LayerCleaner() when all references to the IBinder (handle)
3715 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003716 sp<Layer> l = layer.promote();
3717 if (l == nullptr) {
3718 // The layer has already been removed, carry on
3719 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003720 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003721 // If we have a parent, then we can continue to live as long as it does.
3722 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003723}
3724
Mathias Agopianb60314a2012-04-10 22:09:54 -07003725// ---------------------------------------------------------------------------
3726
Andy McFadden13a082e2012-08-24 10:16:42 -07003727void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003728 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3729 if (!displayToken) return;
3730
Jesse Hall01e29052013-02-19 16:13:35 -08003731 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003732 Vector<ComposerState> state;
3733 Vector<DisplayState> displays;
3734 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003735 d.what = DisplayState::eDisplayProjectionChanged |
3736 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003737 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003738 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003739 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003740 d.frame.makeInvalid();
3741 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003742 d.width = 0;
3743 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003744 displays.add(d);
3745 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003746
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003747 const auto display = getDisplayDevice(displayToken);
3748 if (!display) return;
3749
3750 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3751
3752 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003753 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003754 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003755
Brian Andersond0010582017-03-07 13:20:31 -08003756 // Use phase of 0 since phase is not known.
3757 // Use latency of 0, which will snap to the ideal latency.
3758 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003759}
3760
3761void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003762 // Async since we may be called from the main thread.
3763 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003764}
3765
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003766void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3767 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003768 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003769 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003770
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003771 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003772 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003773 return;
3774 }
3775
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003776 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003777 ALOGW("Trying to set power mode for virtual display");
3778 return;
3779 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003780
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003781 display->setPowerMode(mode);
3782
Lloyd Pique4dccc412018-01-22 17:21:36 -08003783 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003784 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003785 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003786 if (idx < 0) {
3787 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3788 return;
3789 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003790 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003791 }
3792
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003793 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003794 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003795 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003796 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003797 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003798 // FIXME: eventthread only knows about the main display right now
3799 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003800 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003801 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003802
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003803 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003804 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003805 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003806
3807 struct sched_param param = {0};
3808 param.sched_priority = 1;
3809 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3810 ALOGW("Couldn't set SCHED_FIFO on display on");
3811 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003812 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003813 // Turn off the display
3814 struct sched_param param = {0};
3815 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3816 ALOGW("Couldn't set SCHED_OTHER on display off");
3817 }
3818
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003819 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003820 disableHardwareVsync(true); // also cancels any in-progress resync
3821
Mathias Agopiancde87a32012-09-13 14:09:01 -07003822 // FIXME: eventthread only knows about the main display right now
3823 mEventThread->onScreenReleased();
3824 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003825
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003826 getHwComposer().setPowerMode(type, mode);
3827 mVisibleRegionsDirty = true;
3828 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003829 } else if (mode == HWC_POWER_MODE_DOZE ||
3830 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003831 // Update display while dozing
3832 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003833 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003834 // FIXME: eventthread only knows about the main display right now
3835 mEventThread->onScreenAcquired();
3836 resyncToHardwareVsync(true);
3837 }
3838 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3839 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003840 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003841 disableHardwareVsync(true); // also cancels any in-progress resync
3842 // FIXME: eventthread only knows about the main display right now
3843 mEventThread->onScreenReleased();
3844 }
3845 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003846 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003847 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003848 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003849 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003850
3851 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003852}
3853
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003854void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003855 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003856 const auto display = getDisplayDevice(displayToken);
3857 if (!display) {
3858 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3859 displayToken.get());
3860 } else if (display->isVirtual()) {
3861 ALOGW("Attempt to set power mode %d for virtual display", mode);
3862 } else {
3863 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003864 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003865 }));
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 Zhang7124ad32018-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 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003974
3975 if ((index < numArgs) &&
3976 (args[index] == String16("--display-identification"))) {
3977 index++;
3978 dumpDisplayIdentificationData(result);
3979 dumpAll = false;
3980 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003981
3982 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3983 index++;
3984 mTimeStats.parseArgs(asProto, args, index, result);
3985 dumpAll = false;
3986 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003987 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003988
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003989 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003990 if (asProto) {
3991 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3992 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3993 } else {
3994 dumpAllLocked(args, index, result);
3995 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003996 }
3997
Mathias Agopian9795c422009-08-26 16:36:26 -07003998 if (locked) {
3999 mStateLock.unlock();
4000 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004001 }
4002 write(fd, result.string(), result.size());
4003 return NO_ERROR;
4004}
4005
Dan Stozac7014012014-02-14 15:03:43 -08004006void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4007 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004008{
Robert Carr2047fae2016-11-28 14:09:09 -08004009 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004010 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004011 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004012}
4013
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004014void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004015 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004016{
4017 String8 name;
4018 if (index < args.size()) {
4019 name = String8(args[index]);
4020 index++;
4021 }
4022
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004023 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4024 getHwComposer().isConnected(displayId)) {
4025 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4026 const nsecs_t period = activeConfig->getVsyncPeriod();
4027 result.appendFormat("%" PRId64 "\n", period);
4028 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004029
4030 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004031 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004032 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004033 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004034 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004035 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004036 }
Robert Carr2047fae2016-11-28 14:09:09 -08004037 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004038 }
4039}
4040
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004041void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004042 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004043{
4044 String8 name;
4045 if (index < args.size()) {
4046 name = String8(args[index]);
4047 index++;
4048 }
4049
Robert Carr2047fae2016-11-28 14:09:09 -08004050 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004051 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004052 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004053 }
Robert Carr2047fae2016-11-28 14:09:09 -08004054 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004055
Svetoslavd85084b2014-03-20 10:28:31 -07004056 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004057}
4058
Jamie Gennis6547ff42013-07-16 20:12:42 -07004059// This should only be called from the main thread. Otherwise it would need
4060// the lock and should use mCurrentState rather than mDrawingState.
4061void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004062 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004063 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004064 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004065
4066 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4067}
4068
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004069void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004070{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004071 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004072
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004073 if (isLayerTripleBufferingDisabled())
4074 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004075
4076 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004077 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004078 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004079 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004080 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4081 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004082 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004083}
4084
Dan Stozab90cf072015-03-05 11:05:59 -08004085void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4086{
4087 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004088 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4089 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004090 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004091 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004092 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4093 b + 1, bucketTimeSec, percent);
4094 }
David Sodman4a36e932017-11-07 14:29:47 -08004095 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004096 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004097 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004098 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004099 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004100}
4101
Dan Stozae77c7662016-05-13 11:37:28 -07004102void SurfaceFlinger::recordBufferingStats(const char* layerName,
4103 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004104 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4105 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004106 for (const auto& segment : history) {
4107 if (!segment.usedThirdBuffer) {
4108 stats.twoBufferTime += segment.totalTime;
4109 }
4110 if (segment.occupancyAverage < 1.0f) {
4111 stats.doubleBufferedTime += segment.totalTime;
4112 } else if (segment.occupancyAverage < 2.0f) {
4113 stats.tripleBufferedTime += segment.totalTime;
4114 }
4115 ++stats.numSegments;
4116 stats.totalTime += segment.totalTime;
4117 }
4118}
4119
Brian Andersond6927fb2016-07-23 23:37:30 -07004120void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4121 result.appendFormat("Layer frame timestamps:\n");
4122
4123 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4124 const size_t count = currentLayers.size();
4125 for (size_t i=0 ; i<count ; i++) {
4126 currentLayers[i]->dumpFrameEvents(result);
4127 }
4128}
4129
Dan Stozae77c7662016-05-13 11:37:28 -07004130void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4131 result.append("Buffering stats:\n");
4132 result.append(" [Layer name] <Active time> <Two buffer> "
4133 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004134 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004135 typedef std::tuple<std::string, float, float, float> BufferTuple;
4136 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004137 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004138 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004139 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004140 if (stats.numSegments == 0) {
4141 continue;
4142 }
4143 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4144 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4145 stats.totalTime;
4146 float doubleBufferRatio = static_cast<float>(
4147 stats.doubleBufferedTime) / stats.totalTime;
4148 float tripleBufferRatio = static_cast<float>(
4149 stats.tripleBufferedTime) / stats.totalTime;
4150 sorted.insert({activeTime, {name, twoBufferRatio,
4151 doubleBufferRatio, tripleBufferRatio}});
4152 }
4153 for (const auto& sortedPair : sorted) {
4154 float activeTime = sortedPair.first;
4155 const BufferTuple& values = sortedPair.second;
4156 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4157 std::get<0>(values).c_str(), activeTime,
4158 std::get<1>(values), std::get<2>(values),
4159 std::get<3>(values));
4160 }
4161 result.append("\n");
4162}
4163
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004164void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004165 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004166 const int32_t displayId = display->getId();
4167 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4168 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004169 continue;
4170 }
4171
Dominik Laskowski7e045462018-05-30 13:02:02 -07004172 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004173 uint8_t port;
4174 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004175 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004176 result.append("no identification data\n");
4177 continue;
4178 }
4179
4180 if (!isEdid(data)) {
4181 result.append("unknown identification data: ");
4182 for (uint8_t byte : data) {
4183 result.appendFormat("%x ", byte);
4184 }
4185 result.append("\n");
4186 continue;
4187 }
4188
4189 const auto edid = parseEdid(data);
4190 if (!edid) {
4191 result.append("invalid EDID: ");
4192 for (uint8_t byte : data) {
4193 result.appendFormat("%x ", byte);
4194 }
4195 result.append("\n");
4196 continue;
4197 }
4198
4199 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4200 result.append(edid->displayName.data(), edid->displayName.length());
4201 result.append("\"\n");
4202 }
4203 result.append("\n");
4204}
4205
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004206void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4207 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004208 result.appendFormat("DisplayColorSetting: %s\n",
4209 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004210
4211 // TODO: print out if wide-color mode is active or not
4212
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004213 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004214 const int32_t displayId = display->getId();
4215 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004216 continue;
4217 }
4218
Dominik Laskowski7e045462018-05-30 13:02:02 -07004219 result.appendFormat("Display %d color modes:\n", displayId);
4220 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004221 for (auto&& mode : modes) {
4222 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4223 }
4224
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004225 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004226 result.appendFormat(" Current color mode: %s (%d)\n",
4227 decodeColorMode(currentMode).c_str(), currentMode);
4228 }
4229 result.append("\n");
4230}
4231
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004232LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004233 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004234 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4235 const State& state = useDrawing ? mDrawingState : mCurrentState;
4236 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004237 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004238 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004239 });
4240
4241 return layersProto;
4242}
4243
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004244LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004245 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004246
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004247 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004248 resolution->set_w(display.getWidth());
4249 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004250
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004251 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4252 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4253 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004254
Dominik Laskowski7e045462018-05-30 13:02:02 -07004255 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004256 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004257 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004258 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004259 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004260 }
4261 });
4262
4263 return layersProto;
4264}
4265
Mathias Agopian74d211a2013-04-22 16:55:35 +02004266void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4267 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004268{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004269 bool colorize = false;
4270 if (index < args.size()
4271 && (args[index] == String16("--color"))) {
4272 colorize = true;
4273 index++;
4274 }
4275
4276 Colorizer colorizer(colorize);
4277
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004278 // figure out if we're stuck somewhere
4279 const nsecs_t now = systemTime();
4280 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4281 const nsecs_t inTransaction(mDebugInTransaction);
4282 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4283 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4284
4285 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004286 * Dump library configuration.
4287 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004288
4289 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004290 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004291 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004292 appendSfConfigString(result);
4293 appendUiConfigString(result);
4294 appendGuiConfigString(result);
4295 result.append("\n");
4296
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004297 result.append("\nDisplay identification data:\n");
4298 dumpDisplayIdentificationData(result);
4299
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004300 result.append("\nWide-Color information:\n");
4301 dumpWideColorInfo(result);
4302
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004303 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004304 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004305 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004306 result.append(SyncFeatures::getInstance().toString());
4307 result.append("\n");
4308
Andy McFadden41d67d72014-04-25 16:58:34 -07004309 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004310 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004311 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004312
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004313 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4314 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004315 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4316 getHwComposer().isConnected(displayId)) {
4317 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004318 result.appendFormat("Display %d: "
4319 "app phase %" PRId64 " ns, "
4320 "sf phase %" PRId64 " ns, "
4321 "early app phase %" PRId64 " ns, "
4322 "early sf phase %" PRId64 " ns, "
4323 "early app gl phase %" PRId64 " ns, "
4324 "early sf gl phase %" PRId64 " ns, "
4325 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4326 displayId,
4327 vsyncPhaseOffsetNs,
4328 sfVsyncPhaseOffsetNs,
4329 appEarlyOffset,
4330 sfEarlyOffset,
4331 appEarlyGlOffset,
4332 sfEarlyOffset,
4333 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004334 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004335 result.append("\n");
4336
Dan Stozab90cf072015-03-05 11:05:59 -08004337 // Dump static screen stats
4338 result.append("\n");
4339 dumpStaticScreenStats(result);
4340 result.append("\n");
4341
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004342 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4343
Dan Stozae77c7662016-05-13 11:37:28 -07004344 dumpBufferingStats(result);
4345
Andy McFadden4803b742012-09-24 19:07:20 -07004346 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004347 * Dump the visible layer list
4348 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004349 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004350 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004351 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4352 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004353 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004354
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004355 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004356 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004357 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004358 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004359
4360 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004361 * Dump Display state
4362 */
4363
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004364 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004365 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004366 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004367 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004368 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004369 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004370 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004371
4372 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004373 * Dump SurfaceFlinger global state
4374 */
4375
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004376 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004377 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004378 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004379
Mathias Agopian888c8222012-08-04 21:10:38 -07004380 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004381 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004382
David Sodmanbc815282017-11-05 18:57:52 -08004383 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004384
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004385 if (display) {
4386 display->undefinedRegion.dump(result, "undefinedRegion");
4387 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4388 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004389 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004390 result.appendFormat(" last eglSwapBuffers() time: %f us\n"
4391 " last transaction time : %f us\n"
4392 " transaction-flags : %08x\n"
4393 " gpu_to_cpu_unsupported : %d\n",
4394 mLastSwapBufferTime / 1000.0, mLastTransactionTime / 1000.0,
4395 mTransactionFlags, !mGpuToCpuSupported);
4396
4397 if (display) {
4398 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4399 result.appendFormat(" refresh-rate : %f fps\n"
4400 " x-dpi : %f\n"
4401 " y-dpi : %f\n",
4402 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4403 activeConfig->getDpiY());
4404 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004405
Mathias Agopian74d211a2013-04-22 16:55:35 +02004406 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004407 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004408
Mathias Agopian74d211a2013-04-22 16:55:35 +02004409 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004410 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004411
4412 /*
4413 * VSYNC state
4414 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004415 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004416 result.append("\n");
4417
4418 /*
4419 * HWC layer minidump
4420 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004421 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004422 const int32_t displayId = display->getId();
4423 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004424 continue;
4425 }
4426
Dominik Laskowski7e045462018-05-30 13:02:02 -07004427 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004428 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004429 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004430 result.append("\n");
4431 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004432
4433 /*
4434 * Dump HWComposer state
4435 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004436 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004437 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004438 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004439 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004440 result.appendFormat(" h/w composer %s\n",
4441 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004442 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004443
4444 /*
4445 * Dump gralloc state
4446 */
4447 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4448 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004449
4450 /*
4451 * Dump VrFlinger state if in use.
4452 */
4453 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4454 result.append("VrFlinger state:\n");
4455 result.append(mVrFlinger->Dump().c_str());
4456 result.append("\n");
4457 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004458}
4459
Dominik Laskowski7e045462018-05-30 13:02:02 -07004460const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004461 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004462 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004463 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004464 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004465 }
4466 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004467
4468 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4469 static const Vector<sp<Layer>> empty;
4470 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004471}
4472
Keun young Park63f165f2012-08-31 10:53:36 -07004473bool SurfaceFlinger::startDdmConnection()
4474{
4475 void* libddmconnection_dso =
4476 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4477 if (!libddmconnection_dso) {
4478 return false;
4479 }
4480 void (*DdmConnection_start)(const char* name);
4481 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004482 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004483 if (!DdmConnection_start) {
4484 dlclose(libddmconnection_dso);
4485 return false;
4486 }
4487 (*DdmConnection_start)(getServiceName());
4488 return true;
4489}
4490
Chia-I Wu28f320b2018-05-03 11:02:56 -07004491void SurfaceFlinger::updateColorMatrixLocked() {
4492 mat4 colorMatrix;
4493 if (mGlobalSaturationFactor != 1.0f) {
4494 // Rec.709 luma coefficients
4495 float3 luminance{0.213f, 0.715f, 0.072f};
4496 luminance *= 1.0f - mGlobalSaturationFactor;
4497 mat4 saturationMatrix = mat4(
4498 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4499 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4500 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4501 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4502 );
4503 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4504 } else {
4505 colorMatrix = mClientColorMatrix * mDaltonizer();
4506 }
4507
4508 if (mCurrentState.colorMatrix != colorMatrix) {
4509 mCurrentState.colorMatrix = colorMatrix;
4510 mCurrentState.colorMatrixChanged = true;
4511 setTransactionFlags(eTransactionNeeded);
4512 }
4513}
4514
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004515status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004516 switch (code) {
4517 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004518 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004519 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004520 case CLEAR_ANIMATION_FRAME_STATS:
4521 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004522 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004523 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004524 case ENABLE_VSYNC_INJECTIONS:
4525 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004526 {
4527 // codes that require permission check
Robert Carrd4ae7f32018-06-07 16:10:57 -07004528 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4529 IPCThreadState* ipc = IPCThreadState::self();
4530 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4531 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004532 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004533 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004534 break;
4535 }
Robert Carr1db73f62016-12-21 12:58:51 -08004536 /*
4537 * Calling setTransactionState is safe, because you need to have been
4538 * granted a reference to Client* and Handle* to do anything with it.
4539 *
4540 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4541 */
4542 case SET_TRANSACTION_STATE:
4543 case CREATE_SCOPED_CONNECTION:
4544 {
4545 return OK;
4546 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004547 case CAPTURE_SCREEN:
4548 {
4549 // codes that require permission check
4550 IPCThreadState* ipc = IPCThreadState::self();
4551 const int pid = ipc->getCallingPid();
4552 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004553 if ((uid != AID_GRAPHICS) &&
4554 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004555 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004556 return PERMISSION_DENIED;
4557 }
4558 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004559 }
chaviwa76b2712017-09-20 12:02:26 -07004560 case CAPTURE_LAYERS: {
4561 IPCThreadState* ipc = IPCThreadState::self();
4562 const int pid = ipc->getCallingPid();
4563 const int uid = ipc->getCallingUid();
4564 if ((uid != AID_GRAPHICS) &&
4565 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4566 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4567 return PERMISSION_DENIED;
4568 }
4569 break;
4570 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004571 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004572 return OK;
4573}
4574
4575status_t SurfaceFlinger::onTransact(
4576 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4577{
4578 status_t credentialCheck = CheckTransactCodeCredentials(code);
4579 if (credentialCheck != OK) {
4580 return credentialCheck;
4581 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004582
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004583 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4584 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004585 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004586 IPCThreadState* ipc = IPCThreadState::self();
4587 const int uid = ipc->getCallingUid();
4588 if (CC_UNLIKELY(uid != AID_SYSTEM
4589 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004590 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004591 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004592 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004593 return PERMISSION_DENIED;
4594 }
4595 int n;
4596 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004597 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004598 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004599 return NO_ERROR;
4600 case 1002: // SHOW_UPDATES
4601 n = data.readInt32();
4602 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004603 invalidateHwcGeometry();
4604 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004605 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004606 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004607 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004608 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004609 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004610 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004611 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004612 setTransactionFlags(
4613 eTransactionNeeded|
4614 eDisplayTransactionNeeded|
4615 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004616 return NO_ERROR;
4617 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004618 case 1006:{ // send empty update
4619 signalRefresh();
4620 return NO_ERROR;
4621 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004622 case 1008: // toggle use of hw composer
4623 n = data.readInt32();
4624 mDebugDisableHWC = n ? 1 : 0;
4625 invalidateHwcGeometry();
4626 repaintEverything();
4627 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004628 case 1009: // toggle use of transform hint
4629 n = data.readInt32();
4630 mDebugDisableTransformHint = n ? 1 : 0;
4631 invalidateHwcGeometry();
4632 repaintEverything();
4633 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004634 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004635 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004636 reply->writeInt32(0);
4637 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004638 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004639 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004640 return NO_ERROR;
4641 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004642 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004643 if (!display) {
4644 return NAME_NOT_FOUND;
4645 }
4646
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004647 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004648 return NO_ERROR;
4649 }
4650 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004651 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004652 // daltonize
4653 n = data.readInt32();
4654 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004655 case 1:
4656 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4657 break;
4658 case 2:
4659 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4660 break;
4661 case 3:
4662 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4663 break;
4664 default:
4665 mDaltonizer.setType(ColorBlindnessType::None);
4666 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004667 }
4668 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004669 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004670 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004671 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004672 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004673
4674 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004675 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004676 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004677 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004678 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004679 // apply a color matrix
4680 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004681 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004682 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004683 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004684 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004685 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004686 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004687 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004688 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004689 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004690 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004691
4692 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4693 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004694 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004695 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4696 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4697 }
4698
Chia-I Wu28f320b2018-05-03 11:02:56 -07004699 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004700 return NO_ERROR;
4701 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004702 // This is an experimental interface
4703 // Needs to be shifted to proper binder interface when we productize
4704 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004705 n = data.readInt32();
4706 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004707 return NO_ERROR;
4708 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004709 case 1017: {
4710 n = data.readInt32();
4711 mForceFullDamage = static_cast<bool>(n);
4712 return NO_ERROR;
4713 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004714 case 1018: { // Modify Choreographer's phase offset
4715 n = data.readInt32();
4716 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4717 return NO_ERROR;
4718 }
4719 case 1019: { // Modify SurfaceFlinger's phase offset
4720 n = data.readInt32();
4721 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4722 return NO_ERROR;
4723 }
Irvel468051e2016-06-13 16:44:44 -07004724 case 1020: { // Layer updates interceptor
4725 n = data.readInt32();
4726 if (n) {
4727 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004728 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004729 }
4730 else{
4731 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004732 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004733 }
4734 return NO_ERROR;
4735 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004736 case 1021: { // Disable HWC virtual displays
4737 n = data.readInt32();
4738 mUseHwcVirtualDisplays = !n;
4739 return NO_ERROR;
4740 }
Romain Guy0147a172017-06-01 13:53:56 -07004741 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004742 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004743 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004744
Chia-I Wu28f320b2018-05-03 11:02:56 -07004745 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004746 return NO_ERROR;
4747 }
Romain Guy54f154a2017-10-24 21:40:32 +01004748 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004749 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004750 invalidateHwcGeometry();
4751 repaintEverything();
4752 return NO_ERROR;
4753 }
4754 case 1024: { // Is wide color gamut rendering/color management supported?
4755 reply->writeBool(hasWideColorDisplay);
4756 return NO_ERROR;
4757 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004758 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004759 n = data.readInt32();
4760 if (n) {
4761 ALOGV("LayerTracing enabled");
4762 mTracing.enable();
4763 doTracing("tracing.enable");
4764 reply->writeInt32(NO_ERROR);
4765 } else {
4766 ALOGV("LayerTracing disabled");
4767 status_t err = mTracing.disable();
4768 reply->writeInt32(err);
4769 }
4770 return NO_ERROR;
4771 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004772 case 1026: { // Get layer tracing status
4773 reply->writeBool(mTracing.isEnabled());
4774 return NO_ERROR;
4775 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004776 // Is a DisplayColorSetting supported?
4777 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004778 const auto display = getDefaultDisplayDevice();
4779 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004780 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004781 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004782
4783 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4784 switch (setting) {
4785 case DisplayColorSetting::MANAGED:
4786 reply->writeBool(hasWideColorDisplay);
4787 break;
4788 case DisplayColorSetting::UNMANAGED:
4789 reply->writeBool(true);
4790 break;
4791 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004792 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004793 break;
4794 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004795 reply->writeBool(
4796 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004797 break;
4798 }
4799 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004800 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004801 // Is VrFlinger active?
4802 case 1028: {
4803 Mutex::Autolock _l(mStateLock);
4804 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4805 return NO_ERROR;
4806 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004807 }
4808 }
4809 return err;
4810}
4811
Steven Thomas6d8110b2017-08-31 18:24:21 -07004812void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004813 android_atomic_or(1, &mRepaintEverything);
4814 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004815}
4816
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004817// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4818class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004819public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004820 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4821 ~WindowDisconnector() {
4822 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004823 }
4824
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004825private:
4826 ANativeWindow* mWindow;
4827 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004828};
4829
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004830status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4831 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4832 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4833 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004834 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004835 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004836
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004837 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004838
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004839 const auto display = getDisplayDeviceLocked(displayToken);
4840 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004841
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004842 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004843
4844 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004845 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004846 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004847}
4848
4849status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004850 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004851 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004852 ATRACE_CALL();
4853
4854 class LayerRenderArea : public RenderArea {
4855 public:
Robert Carr578038f2018-03-09 12:25:24 -08004856 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4857 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004858 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004859 mLayer(layer),
4860 mCrop(crop),
4861 mFlinger(flinger),
4862 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004863 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004864 Rect getBounds() const override {
4865 const Layer::State& layerState(mLayer->getDrawingState());
4866 return Rect(layerState.active.w, layerState.active.h);
4867 }
4868 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4869 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4870 bool isSecure() const override { return false; }
4871 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004872 Rect getSourceCrop() const override {
4873 if (mCrop.isEmpty()) {
4874 return getBounds();
4875 } else {
4876 return mCrop;
4877 }
4878 }
Robert Carr578038f2018-03-09 12:25:24 -08004879 class ReparentForDrawing {
4880 public:
4881 const sp<Layer>& oldParent;
4882 const sp<Layer>& newParent;
4883
4884 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4885 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004886 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004887 }
Robert Carr15eae092018-03-23 13:43:53 -07004888 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004889 };
4890
4891 void render(std::function<void()> drawLayers) override {
4892 if (!mChildrenOnly) {
4893 mTransform = mLayer->getTransform().inverse();
4894 drawLayers();
4895 } else {
4896 Rect bounds = getBounds();
4897 screenshotParentLayer =
4898 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4899 bounds.getWidth(), bounds.getHeight(), 0);
4900
4901 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4902 drawLayers();
4903 }
4904 }
chaviwa76b2712017-09-20 12:02:26 -07004905
chaviwa76b2712017-09-20 12:02:26 -07004906 private:
chaviw7206d492017-11-10 16:16:12 -08004907 const sp<Layer> mLayer;
4908 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004909
4910 // In the "childrenOnly" case we reparent the children to a screenshot
4911 // layer which has no properties set and which does not draw.
4912 sp<ContainerLayer> screenshotParentLayer;
4913 Transform mTransform;
4914
4915 SurfaceFlinger* mFlinger;
4916 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004917 };
4918
4919 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4920 auto parent = layerHandle->owner.promote();
4921
chaviw7206d492017-11-10 16:16:12 -08004922 if (parent == nullptr || parent->isPendingRemoval()) {
4923 ALOGE("captureLayers called with a removed parent");
4924 return NAME_NOT_FOUND;
4925 }
4926
Robert Carr578038f2018-03-09 12:25:24 -08004927 const int uid = IPCThreadState::self()->getCallingUid();
4928 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4929 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4930 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4931 return PERMISSION_DENIED;
4932 }
4933
chaviw7206d492017-11-10 16:16:12 -08004934 Rect crop(sourceCrop);
4935 if (sourceCrop.width() <= 0) {
4936 crop.left = 0;
4937 crop.right = parent->getCurrentState().active.w;
4938 }
4939
4940 if (sourceCrop.height() <= 0) {
4941 crop.top = 0;
4942 crop.bottom = parent->getCurrentState().active.h;
4943 }
4944
4945 int32_t reqWidth = crop.width() * frameScale;
4946 int32_t reqHeight = crop.height() * frameScale;
4947
Robert Carr578038f2018-03-09 12:25:24 -08004948 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004949
Robert Carr578038f2018-03-09 12:25:24 -08004950 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004951 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4952 if (!layer->isVisible()) {
4953 return;
Robert Carr578038f2018-03-09 12:25:24 -08004954 } else if (childrenOnly && layer == parent.get()) {
4955 return;
chaviwa76b2712017-09-20 12:02:26 -07004956 }
4957 visitor(layer);
4958 });
4959 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004960 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004961}
4962
4963status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4964 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004965 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004966 bool useIdentityTransform) {
4967 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004968
Iris Chang7501ed62018-04-30 14:45:42 +08004969 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004970
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004971 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4972 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4973 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4974 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004975
4976 // This mutex protects syncFd and captureResult for communication of the return values from the
4977 // main thread back to this Binder thread
4978 std::mutex captureMutex;
4979 std::condition_variable captureCondition;
4980 std::unique_lock<std::mutex> captureLock(captureMutex);
4981 int syncFd = -1;
4982 std::optional<status_t> captureResult;
4983
Robert Carr03480e22018-01-04 16:02:06 -08004984 const int uid = IPCThreadState::self()->getCallingUid();
4985 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4986
Dominik Laskowski8c001672018-05-30 16:52:06 -07004987 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004988 // If there is a refresh pending, bug out early and tell the binder thread to try again
4989 // after the refresh.
4990 if (mRefreshPending) {
4991 ATRACE_NAME("Skipping screenshot for now");
4992 std::unique_lock<std::mutex> captureLock(captureMutex);
4993 captureResult = std::make_optional<status_t>(EAGAIN);
4994 captureCondition.notify_one();
4995 return;
4996 }
4997
4998 status_t result = NO_ERROR;
4999 int fd = -1;
5000 {
5001 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005002 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005003 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5004 useIdentityTransform, forSystem, &fd);
5005 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005006 }
5007
5008 {
5009 std::unique_lock<std::mutex> captureLock(captureMutex);
5010 syncFd = fd;
5011 captureResult = std::make_optional<status_t>(result);
5012 captureCondition.notify_one();
5013 }
5014 });
5015
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005016 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005017 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005018 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005019 while (*captureResult == EAGAIN) {
5020 captureResult.reset();
5021 result = postMessageAsync(message);
5022 if (result != NO_ERROR) {
5023 return result;
5024 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005025 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005026 }
5027 result = *captureResult;
5028 }
5029
5030 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005031 sync_wait(syncFd, -1);
5032 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005033 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005034
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005035 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005036}
5037
chaviwa76b2712017-09-20 12:02:26 -07005038void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5039 TraverseLayersFunction traverseLayers, bool yswap,
5040 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005041 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005042
Lloyd Pique144e1162017-12-20 16:44:52 -08005043 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005044
5045 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005046 const auto raWidth = renderArea.getWidth();
5047 const auto raHeight = renderArea.getHeight();
5048
5049 const auto reqWidth = renderArea.getReqWidth();
5050 const auto reqHeight = renderArea.getReqHeight();
5051 Rect sourceCrop = renderArea.getSourceCrop();
5052
Iris Chang7501ed62018-04-30 14:45:42 +08005053 bool filtering = false;
5054 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5055 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5056 static_cast<int32_t>(reqHeight) != raWidth;
5057 } else {
5058 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5059 static_cast<int32_t>(reqHeight) != raHeight;
5060 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005061
Dan Stozac1879002014-05-22 15:59:05 -07005062 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005063 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005064 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005065 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005066 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5067 Transform tr;
5068 uint32_t flags = 0x00;
5069 switch (mPrimaryDisplayOrientation) {
5070 case DisplayState::eOrientation90:
5071 flags = Transform::ROT_90;
5072 break;
5073 case DisplayState::eOrientation180:
5074 flags = Transform::ROT_180;
5075 break;
5076 case DisplayState::eOrientation270:
5077 flags = Transform::ROT_270;
5078 break;
5079 }
5080 tr.set(flags, raWidth, raHeight);
5081 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005082 }
5083
5084 // ensure that sourceCrop is inside screen
5085 if (sourceCrop.left < 0) {
5086 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5087 }
chaviwa76b2712017-09-20 12:02:26 -07005088 if (sourceCrop.right > raWidth) {
5089 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005090 }
5091 if (sourceCrop.top < 0) {
5092 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5093 }
chaviwa76b2712017-09-20 12:02:26 -07005094 if (sourceCrop.bottom > raHeight) {
5095 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005096 }
5097
Chia-I Wu36574d92018-05-16 10:54:36 -07005098 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5099 engine.setOutputDataSpace(Dataspace::SRGB);
5100 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005101
Mathias Agopian180f10d2013-04-10 22:55:41 -07005102 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005103 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005104
Iris Chang7501ed62018-04-30 14:45:42 +08005105 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5106 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5107 // convert hw orientation into flag presentation
5108 // here inverse transform needed
5109 uint8_t hw_rot_90 = 0x00;
5110 uint8_t hw_flip_hv = 0x00;
5111 switch (mPrimaryDisplayOrientation) {
5112 case DisplayState::eOrientation90:
5113 hw_rot_90 = Transform::ROT_90;
5114 hw_flip_hv = Transform::ROT_180;
5115 break;
5116 case DisplayState::eOrientation180:
5117 hw_flip_hv = Transform::ROT_180;
5118 break;
5119 case DisplayState::eOrientation270:
5120 hw_rot_90 = Transform::ROT_90;
5121 break;
5122 }
5123
5124 // transform flags operation
5125 // 1) flip H V if both have ROT_90 flag
5126 // 2) XOR these flags
5127 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5128 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5129 if (rotation_rot_90 & hw_rot_90) {
5130 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5131 }
5132 rotation = static_cast<Transform::orientation_flags>
5133 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5134 }
5135
Mathias Agopian180f10d2013-04-10 22:55:41 -07005136 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005137 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005138 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005139 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005140
chaviw50da5042018-04-09 13:49:37 -07005141 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005142 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005143 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005144
chaviwa76b2712017-09-20 12:02:26 -07005145 traverseLayers([&](Layer* layer) {
5146 if (filtering) layer->setFiltering(true);
David Sodmanca10ed22018-04-16 14:10:25 -07005147 layer->drawNow(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005148 if (filtering) layer->setFiltering(false);
5149 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005150}
5151
chaviwa76b2712017-09-20 12:02:26 -07005152status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5153 TraverseLayersFunction traverseLayers,
5154 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005155 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005156 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005157 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005158 ATRACE_CALL();
5159
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005160 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005161
5162 traverseLayers([&](Layer* layer) {
5163 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5164 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005165
Robert Carr03480e22018-01-04 16:02:06 -08005166 // We allow the system server to take screenshots of secure layers for
5167 // use in situations like the Screen-rotation animation and place
5168 // the impetus on WindowManager to not persist them.
5169 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005170 ALOGW("FB is protected: PERMISSION_DENIED");
5171 return PERMISSION_DENIED;
5172 }
5173
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005174 // this binds the given EGLImage as a framebuffer for the
5175 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005176 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005177 if (bufferBond.getStatus() != NO_ERROR) {
5178 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005179 return INVALID_OPERATION;
5180 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005181
Dan Stozaabcda352017-06-01 14:37:39 -07005182 // this will in fact render into our dequeued buffer
5183 // via an FBO, which means we didn't have to create
5184 // an EGLSurface and therefore we're not
5185 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005186 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005187
Dan Stozaabcda352017-06-01 14:37:39 -07005188 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005189 getRenderEngine().finish();
5190 *outSyncFd = -1;
5191
chaviwa76b2712017-09-20 12:02:26 -07005192 const auto reqWidth = renderArea.getReqWidth();
5193 const auto reqHeight = renderArea.getReqHeight();
5194
Dan Stozaabcda352017-06-01 14:37:39 -07005195 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5196 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005197 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005198 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005199 } else {
5200 base::unique_fd syncFd = getRenderEngine().flush();
5201 if (syncFd < 0) {
5202 getRenderEngine().finish();
5203 }
5204 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005205 }
5206
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005207 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005208}
5209
Mathias Agopiand5556842013-09-19 17:08:37 -07005210void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005211 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005212 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005213 for (size_t y = 0; y < h; y++) {
5214 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5215 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005216 if (p[x] != 0xFF000000) return;
5217 }
5218 }
chaviwa76b2712017-09-20 12:02:26 -07005219 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005220
Robert Carr2047fae2016-11-28 14:09:09 -08005221 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005222 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005223 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005224 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5225 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5226 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5227 static_cast<float>(state.color.a));
5228 i++;
5229 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005230 }
5231}
5232
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005233// ---------------------------------------------------------------------------
5234
Dan Stoza412903f2017-04-27 13:42:17 -07005235void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5236 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005237}
5238
Dan Stoza412903f2017-04-27 13:42:17 -07005239void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5240 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005241}
5242
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005243void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5244 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005245 const LayerVector::Visitor& visitor) {
5246 // We loop through the first level of layers without traversing,
5247 // as we need to interpret min/max layer Z in the top level Z space.
5248 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005249 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005250 continue;
5251 }
5252 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005253 // relative layers are traversed in Layer::traverseInZOrder
5254 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005255 continue;
5256 }
5257 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005258 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005259 return;
5260 }
chaviwa76b2712017-09-20 12:02:26 -07005261 if (!layer->isVisible()) {
5262 return;
5263 }
5264 visitor(layer);
5265 });
5266 }
5267}
5268
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005269}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005270
Lloyd Pique074e8122018-07-26 12:57:23 -07005271
Mathias Agopian3f844832013-08-07 21:24:32 -07005272#if defined(__gl_h_)
5273#error "don't include gl/gl.h in this file"
5274#endif
5275
5276#if defined(__gl2_h_)
5277#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005278#endif