blob: 9378756ea6f685a198fa040eead26a19422ce292 [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>
Peiyong Lincbc184f2018-08-22 13:24:10 -070050#include <renderengine/RenderEngine.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070051#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"
Marissa Wallfd668622018-05-10 10:21:13 -070066#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070067#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020070#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080072#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080073#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Steven Thomasb02664d2017-07-26 18:48:28 -070079#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070080#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070084#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070085#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070086#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070087#include "Scheduler/EventControlThread.h"
88#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070089#include "Scheduler/InjectVSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070090
Mathias Agopianff2ed702013-09-01 21:36:12 -070091#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070092
David Sodman7e4ae112018-02-09 15:02:28 -080093#include "android-base/stringprintf.h"
94
Jiyong Park4b20c2e2017-01-14 19:45:11 +090095#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080096#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -070097#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080098#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090099#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900100
chaviw1d044282017-09-27 12:19:28 -0700101#include <layerproto/LayerProtoParser.h>
102
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800103#define DISPLAY_COUNT 1
104
Mathias Agopianfee2b462013-07-03 12:34:01 -0700105/*
106 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
107 * black pixels.
108 */
109#define DEBUG_SCREENSHOTS false
110
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800111namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700112
Jaesoo Lee43518572017-01-23 19:03:16 +0900113using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900114using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700115using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700116using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700117using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700118using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900119
Steven Thomasb02664d2017-07-26 18:48:28 -0700120namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700121
122#pragma clang diagnostic push
123#pragma clang diagnostic error "-Wswitch-enum"
124
125bool isWideColorMode(const ColorMode colorMode) {
126 switch (colorMode) {
127 case ColorMode::DISPLAY_P3:
128 case ColorMode::ADOBE_RGB:
129 case ColorMode::DCI_P3:
130 case ColorMode::BT2020:
131 case ColorMode::BT2100_PQ:
132 case ColorMode::BT2100_HLG:
133 return true;
134 case ColorMode::NATIVE:
135 case ColorMode::STANDARD_BT601_625:
136 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
137 case ColorMode::STANDARD_BT601_525:
138 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
139 case ColorMode::STANDARD_BT709:
140 case ColorMode::SRGB:
141 return false;
142 }
143 return false;
144}
145
146#pragma clang diagnostic pop
147
Steven Thomasb02664d2017-07-26 18:48:28 -0700148class ConditionalLock {
149public:
150 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
151 if (lock) {
152 mMutex.lock();
153 }
154 }
155 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
156private:
157 Mutex& mMutex;
158 bool mLocked;
159};
Peiyong Linfca547f2018-07-09 13:03:33 -0700160
Steven Thomasb02664d2017-07-26 18:48:28 -0700161} // namespace anonymous
162
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800163// ---------------------------------------------------------------------------
164
Mathias Agopian99b49842011-06-27 16:05:52 -0700165const String16 sHardwareTest("android.permission.HARDWARE_TEST");
166const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
167const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
168const String16 sDump("android.permission.DUMP");
169
170// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800171int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
172int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700173int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700174bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800175uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800176bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800177bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800178int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800179// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600180bool SurfaceFlinger::hasWideColorDisplay;
Peiyong Lin13effd12018-07-24 17:01:47 -0700181bool SurfaceFlinger::useColorManagement;
Mathias Agopian99b49842011-06-27 16:05:52 -0700182
Kalle Raitaa099a242017-01-11 11:17:29 -0800183
184std::string getHwcServiceName() {
185 char value[PROPERTY_VALUE_MAX] = {};
186 property_get("debug.sf.hwc_service_name", value, "default");
187 ALOGI("Using HWComposer service: '%s'", value);
188 return std::string(value);
189}
190
191bool useTrebleTestingOverride() {
192 char value[PROPERTY_VALUE_MAX] = {};
193 property_get("debug.sf.treble_testing_override", value, "false");
194 ALOGI("Treble testing override: '%s'", value);
195 return std::string(value) == "true";
196}
197
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800198std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
199 switch(displayColorSetting) {
200 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700201 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800202 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700203 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800204 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700205 return std::string("Enhanced");
206 default:
207 return std::string("Unknown ") +
208 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800209 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800210}
211
Lloyd Pique99d3da52018-01-22 17:48:03 -0800212NativeWindowSurface::~NativeWindowSurface() = default;
213
214namespace impl {
215
216class NativeWindowSurface final : public android::NativeWindowSurface {
217public:
218 static std::unique_ptr<android::NativeWindowSurface> create(
219 const sp<IGraphicBufferProducer>& producer) {
220 return std::make_unique<NativeWindowSurface>(producer);
221 }
222
223 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
224 : surface(new Surface(producer, false)) {}
225
226 ~NativeWindowSurface() override = default;
227
228private:
229 sp<ANativeWindow> getNativeWindow() const override { return surface; }
230
231 void preallocateBuffers() override { surface->allocateBuffers(); }
232
233 sp<Surface> surface;
234};
235
236} // namespace impl
237
David Sodmanbc815282017-11-05 18:57:52 -0800238SurfaceFlingerBE::SurfaceFlingerBE()
239 : mHwcServiceName(getHwcServiceName()),
240 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800241 mFrameBuckets(),
242 mTotalTime(0),
243 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800244 mComposerSequenceId(0) {
245}
246
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800247SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800248 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800249 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700250 mTransactionPending(false),
251 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700252 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700253 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700254 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800255 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700256 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800258 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800259 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800260 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800261 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700262 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700263 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700264 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700265 mDebugInTransaction(0),
266 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700267 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700268 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700269 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800270 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800271 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800272 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700273 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800274 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800275 mCreateBufferQueue(&BufferQueue::createBufferQueue),
276 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800277
278SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800279 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800280
281 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
282 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
283
284 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
285 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
286
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800287 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
288 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800289
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700290 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
291 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
292
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700293 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
294 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
295
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800296 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
297 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
298
Steven Thomas050b2c82017-03-06 11:45:16 -0800299 // Vr flinger is only enabled on Daydream ready devices.
300 useVrFlinger = getBool< ISurfaceFlingerConfigs,
301 &ISurfaceFlingerConfigs::useVrFlinger>(false);
302
Fabien Sanglard1971b632017-03-10 14:50:03 -0800303 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
304 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
305
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600306 hasWideColorDisplay =
307 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700308 useColorManagement =
309 getBool<V1_2::ISurfaceFlingerConfigs, &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600310
Iris Chang7501ed62018-04-30 14:45:42 +0800311 V1_1::DisplayOrientation primaryDisplayOrientation =
312 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
313 V1_1::DisplayOrientation::ORIENTATION_0);
314
315 switch (primaryDisplayOrientation) {
316 case V1_1::DisplayOrientation::ORIENTATION_90:
317 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
318 break;
319 case V1_1::DisplayOrientation::ORIENTATION_180:
320 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
321 break;
322 case V1_1::DisplayOrientation::ORIENTATION_270:
323 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
324 break;
325 default:
326 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
327 break;
328 }
329 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
330
Lloyd Pique41be5d22018-06-21 13:11:48 -0700331 // Note: We create a local temporary with the real DispSync implementation
332 // type temporarily so we can initialize it with the configured values,
333 // before storing it for more generic use using the interface type.
334 auto primaryDispSync = std::make_unique<impl::DispSync>("PrimaryDispSync");
335 primaryDispSync->init(SurfaceFlinger::hasSyncFramework,
336 SurfaceFlinger::dispSyncPresentTimeOffset);
337 mPrimaryDispSync = std::move(primaryDispSync);
Saurabh Shahf4174532017-07-13 10:45:07 -0700338
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800339 // debugging stuff...
340 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700341
Mathias Agopianb4b17302013-03-20 18:36:41 -0700342 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700343 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700344
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800345 property_get("debug.sf.showupdates", value, "0");
346 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700347
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700348 property_get("debug.sf.ddms", value, "0");
349 mDebugDDMS = atoi(value);
350 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700351 if (!startDdmConnection()) {
352 // start failed, and DDMS debugging not enabled
353 mDebugDDMS = 0;
354 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700355 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700356 ALOGI_IF(mDebugRegion, "showupdates enabled");
357 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700358
359 property_get("debug.sf.disable_backpressure", value, "0");
360 mPropagateBackpressure = !atoi(value);
361 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700362
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800363 property_get("debug.sf.enable_hwc_vds", value, "0");
364 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800365 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800366
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800367 property_get("ro.sf.disable_triple_buffer", value, "1");
368 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800369 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700370
Yiwei Zhang243b3782018-05-15 17:40:04 -0700371 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700372 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
373 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
374
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200375 property_get("debug.sf.early_phase_offset_ns", value, "-1");
376 const int earlySfOffsetNs = atoi(value);
377
378 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
379 const int earlyGlSfOffsetNs = atoi(value);
380
381 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
382 const int earlyAppOffsetNs = atoi(value);
383
384 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
385 const int earlyGlAppOffsetNs = atoi(value);
386
387 const VSyncModulator::Offsets earlyOffsets =
388 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
389 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
390 const VSyncModulator::Offsets earlyGlOffsets =
391 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
392 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
393 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
394 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700395
Romain Guy11d63f42017-07-20 12:47:14 -0700396 // We should be reading 'persist.sys.sf.color_saturation' here
397 // but since /data may be encrypted, we need to wait until after vold
398 // comes online to attempt to read the property. The property is
399 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800400
401 if (useTrebleTestingOverride()) {
402 // Without the override SurfaceFlinger cannot connect to HIDL
403 // services that are not listed in the manifests. Considered
404 // deriving the setting from the set service name, but it
405 // would be brittle if the name that's not 'default' is used
406 // for production purposes later on.
407 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
408 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800409}
410
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800411void SurfaceFlinger::onFirstRef()
412{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800413 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800414}
415
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800416SurfaceFlinger::~SurfaceFlinger()
417{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800418}
419
Dan Stozac7014012014-02-14 15:03:43 -0800420void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800421{
422 // the window manager died on us. prepare its eulogy.
423
Andy McFadden13a082e2012-08-24 10:16:42 -0700424 // restore initial conditions (default device unblank, etc)
425 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800426
427 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700428 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800429}
430
Robert Carr1db73f62016-12-21 12:58:51 -0800431static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700432 status_t err = client->initCheck();
433 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800434 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800435 }
Robert Carr1db73f62016-12-21 12:58:51 -0800436 return nullptr;
437}
438
439sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
440 return initClient(new Client(this));
441}
442
443sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
444 const sp<IGraphicBufferProducer>& gbp) {
445 if (authenticateSurfaceTexture(gbp) == false) {
446 return nullptr;
447 }
448 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
449 if (layer == nullptr) {
450 return nullptr;
451 }
452
453 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800454}
455
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700456sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
457 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700458{
459 class DisplayToken : public BBinder {
460 sp<SurfaceFlinger> flinger;
461 virtual ~DisplayToken() {
462 // no more references, this display must be terminated
463 Mutex::Autolock _l(flinger->mStateLock);
464 flinger->mCurrentState.displays.removeItem(this);
465 flinger->setTransactionFlags(eDisplayTransactionNeeded);
466 }
467 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700468 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700469 : flinger(flinger) {
470 }
471 };
472
473 sp<BBinder> token = new DisplayToken(this);
474
475 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700476 DisplayDeviceState info;
477 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700478 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700479 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700480 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800481 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700482 return token;
483}
484
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700485void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700486 Mutex::Autolock _l(mStateLock);
487
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700488 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700489 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700490 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700491 return;
492 }
493
494 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700495 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700496 ALOGE("destroyDisplay called for non-virtual display");
497 return;
498 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700499 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700500 mCurrentState.displays.removeItemsAt(idx);
501 setTransactionFlags(eDisplayTransactionNeeded);
502}
503
Mathias Agopiane57f2922012-08-09 16:29:12 -0700504sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700505 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700506 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800507 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700508 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700509 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700510}
511
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800512void SurfaceFlinger::bootFinished()
513{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700514 if (mStartPropertySetThread->join() != NO_ERROR) {
515 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800516 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800517 const nsecs_t now = systemTime();
518 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000519 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700520
521 // wait patiently for the window manager death
522 const String16 name("window");
523 sp<IBinder> window(defaultServiceManager()->getService(name));
524 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700525 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700526 }
527
Steven Thomas050b2c82017-03-06 11:45:16 -0800528 if (mVrFlinger) {
529 mVrFlinger->OnBootFinished();
530 }
531
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700532 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700533 // formerly we would just kill the process, but we now ask it to exit so it
534 // can choose where to stop the animation.
535 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700536
537 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
538 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
539 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700540
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800541 postMessageAsync(new LambdaMessage([this] {
542 readPersistentProperties();
543 mBootStage = BootStage::FINISHED;
544 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800545}
546
Dan Stoza436ccf32018-06-21 12:10:12 -0700547uint32_t SurfaceFlinger::getNewTexture() {
548 {
549 std::lock_guard lock(mTexturePoolMutex);
550 if (!mTexturePool.empty()) {
551 uint32_t name = mTexturePool.back();
552 mTexturePool.pop_back();
553 ATRACE_INT("TexturePoolSize", mTexturePool.size());
554 return name;
555 }
556
557 // The pool was too small, so increase it for the future
558 ++mTexturePoolSize;
559 }
560
561 // The pool was empty, so we need to get a new texture name directly using a
562 // blocking call to the main thread
563 uint32_t name = 0;
564 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
565 return name;
566}
567
Mathias Agopian3f844832013-08-07 21:24:32 -0700568void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700569 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700570}
571
Wei Wangf9b05ee2017-07-19 20:59:39 -0700572// Do not call property_set on main thread which will be blocked by init
573// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700574void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700575 ALOGI( "SurfaceFlinger's main thread ready to run. "
576 "Initializing graphics H/W...");
577
Thierry Strudel2924d012017-08-14 15:19:37 -0700578 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900579
Steven Thomasb02664d2017-07-26 18:48:28 -0700580 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800581
Steven Thomasb02664d2017-07-26 18:48:28 -0700582 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800583 mEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700584 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
585 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800586 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700587 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800588 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800589 "appEventThread");
590 mSfEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700591 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800592 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800593
Lloyd Pique24b0a482018-03-09 18:52:26 -0800594 mSFEventThread =
595 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700596 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800597 [this](nsecs_t timestamp) {
598 mInterceptor->saveVSyncEvent(timestamp);
599 },
600 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800601 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200602 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800603
Steven Thomasb02664d2017-07-26 18:48:28 -0700604 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700605 int32_t renderEngineFeature = 0;
606 renderEngineFeature |= (useColorManagement ? RE::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Lloyd Pique144e1162017-12-20 16:44:52 -0800607 getBE().mRenderEngine =
Peiyong Lin13effd12018-07-24 17:01:47 -0700608 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888, renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800609 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700610
611 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
612 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800613 getBE().mHwc.reset(
614 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700615 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800616 // Process any initial hotplug and resulting display changes.
617 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700618 const auto display = getDefaultDisplayDeviceLocked();
619 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
620 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
621 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800622
Lloyd Piquefcd86612017-12-14 17:15:36 -0800623 // make the default display GLContext current so that we can create textures
624 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700625 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800626
Steven Thomas050b2c82017-03-06 11:45:16 -0800627 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700628 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700629 // This callback is called from the vr flinger dispatch thread. We
630 // need to call signalTransaction(), which requires holding
631 // mStateLock when we're not on the main thread. Acquiring
632 // mStateLock from the vr flinger dispatch thread might trigger a
633 // deadlock in surface flinger (see b/66916578), so post a message
634 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700635 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700636 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
637 mVrFlingerRequestsDisplay = requestDisplay;
638 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700639 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800640 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700641 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
642 getHwComposer()
643 .getHwcDisplayId(display->getId())
644 .value_or(0),
645 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800646 if (!mVrFlinger) {
647 ALOGE("Failed to start vrflinger");
648 }
649 }
650
Lloyd Pique379adc12018-01-22 17:31:47 -0800651 mEventControlThread = std::make_unique<impl::EventControlThread>(
652 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700653
Mathias Agopian92a979a2012-08-02 18:32:23 -0700654 // initialize our drawing state
655 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700656
Andy McFadden13a082e2012-08-24 10:16:42 -0700657 // set initial conditions (e.g. unblank default device)
658 initializeDisplays();
659
David Sodmanbc815282017-11-05 18:57:52 -0800660 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700661
Wei Wangf9b05ee2017-07-19 20:59:39 -0700662 // Inform native graphics APIs whether the present timestamp is supported:
663 if (getHwComposer().hasCapability(
664 HWC2::Capability::PresentFenceIsNotReliable)) {
665 mStartPropertySetThread = new StartPropertySetThread(false);
666 } else {
667 mStartPropertySetThread = new StartPropertySetThread(true);
668 }
669
670 if (mStartPropertySetThread->Start() != NO_ERROR) {
671 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800672 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800673
Chia-I Wud49d6692018-06-27 07:17:41 +0800674 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
675 // is used to saturate legacy sRGB content. However, to make sure the same color under
676 // Display P3 will be saturated to the same color, we intentionally break the API spec
677 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
678 // such saturation matrix on Display P3 is understood fully, the API should always return
679 // identify matrix.
680 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
681 Dataspace::SRGB_LINEAR);
682
683 // we will apply this on Display P3.
684 if (mEnhancedSaturationMatrix != mat4()) {
685 ColorSpace srgb(ColorSpace::sRGB());
686 ColorSpace displayP3(ColorSpace::DisplayP3());
687 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
688 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
689 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
690 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800691
Dan Stoza9e56aa02015-11-02 13:00:03 -0800692 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700693}
694
Romain Guy11d63f42017-07-20 12:47:14 -0700695void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700696 Mutex::Autolock _l(mStateLock);
697
Romain Guy11d63f42017-07-20 12:47:14 -0700698 char value[PROPERTY_VALUE_MAX];
699
700 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800701 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700702 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800703 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100704
705 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700706 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700707}
708
Mathias Agopiana67e4182012-06-19 17:26:12 -0700709void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800710 // Start boot animation service by setting a property mailbox
711 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700712 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800713 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700714 if (mStartPropertySetThread->join() != NO_ERROR) {
715 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800716 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700717}
718
Mathias Agopian875d8e12013-06-07 15:35:48 -0700719size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800720 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700721}
722
Mathias Agopian875d8e12013-06-07 15:35:48 -0700723size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800724 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700725}
726
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800727// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800728
Jamie Gennis582270d2011-08-17 18:19:00 -0700729bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800730 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800731 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800732 return authenticateSurfaceTextureLocked(bufferProducer);
733}
734
735bool SurfaceFlinger::authenticateSurfaceTextureLocked(
736 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800737 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800738 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800739}
740
Brian Anderson6b376712017-04-04 10:51:39 -0700741status_t SurfaceFlinger::getSupportedFrameTimestamps(
742 std::vector<FrameEvent>* outSupported) const {
743 *outSupported = {
744 FrameEvent::REQUESTED_PRESENT,
745 FrameEvent::ACQUIRE,
746 FrameEvent::LATCH,
747 FrameEvent::FIRST_REFRESH_START,
748 FrameEvent::LAST_REFRESH_START,
749 FrameEvent::GPU_COMPOSITION_DONE,
750 FrameEvent::DEQUEUE_READY,
751 FrameEvent::RELEASE,
752 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700753 ConditionalLock _l(mStateLock,
754 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700755 if (!getHwComposer().hasCapability(
756 HWC2::Capability::PresentFenceIsNotReliable)) {
757 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
758 }
759 return NO_ERROR;
760}
761
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700762status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
763 Vector<DisplayInfo>* configs) {
764 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700765 return BAD_VALUE;
766 }
767
Jesse Hall692c7232012-11-08 15:41:56 -0800768 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700769 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
770 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700771 type = i;
772 break;
773 }
774 }
775
776 if (type < 0) {
777 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700778 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700779
Mathias Agopian8b736f12012-08-13 17:54:26 -0700780 // TODO: Not sure if display density should handled by SF any longer
781 class Density {
782 static int getDensityFromProperty(char const* propName) {
783 char property[PROPERTY_VALUE_MAX];
784 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800785 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700786 density = atoi(property);
787 }
788 return density;
789 }
790 public:
791 static int getEmuDensity() {
792 return getDensityFromProperty("qemu.sf.lcd_density"); }
793 static int getBuildDensity() {
794 return getDensityFromProperty("ro.sf.lcd_density"); }
795 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700796
Dan Stoza7f7da322014-05-02 15:26:25 -0700797 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700798
Steven Thomas6d8110b2017-08-31 18:24:21 -0700799 ConditionalLock _l(mStateLock,
800 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800801 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700802 DisplayInfo info = DisplayInfo();
803
Dan Stoza9e56aa02015-11-02 13:00:03 -0800804 float xdpi = hwConfig->getDpiX();
805 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700806
807 if (type == DisplayDevice::DISPLAY_PRIMARY) {
808 // The density of the device is provided by a build property
809 float density = Density::getBuildDensity() / 160.0f;
810 if (density == 0) {
811 // the build doesn't provide a density -- this is wrong!
812 // use xdpi instead
813 ALOGE("ro.sf.lcd_density must be defined as a build property");
814 density = xdpi / 160.0f;
815 }
816 if (Density::getEmuDensity()) {
817 // if "qemu.sf.lcd_density" is specified, it overrides everything
818 xdpi = ydpi = density = Density::getEmuDensity();
819 density /= 160.0f;
820 }
821 info.density = density;
822
823 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700824 const auto display = getDefaultDisplayDeviceLocked();
825 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700826 } else {
827 // TODO: where should this value come from?
828 static const int TV_DENSITY = 213;
829 info.density = TV_DENSITY / 160.0f;
830 info.orientation = 0;
831 }
832
Dan Stoza9e56aa02015-11-02 13:00:03 -0800833 info.w = hwConfig->getWidth();
834 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700835 info.xdpi = xdpi;
836 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800837 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900838 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800839
Andy McFadden91b2ca82014-06-13 14:04:23 -0700840 // This is how far in advance a buffer must be queued for
841 // presentation at a given time. If you want a buffer to appear
842 // on the screen at time N, you must submit the buffer before
843 // (N - presentationDeadline).
844 //
845 // Normally it's one full refresh period (to give SF a chance to
846 // latch the buffer), but this can be reduced by configuring a
847 // DispSync offset. Any additional delays introduced by the hardware
848 // composer or panel must be accounted for here.
849 //
850 // We add an additional 1ms to allow for processing time and
851 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800852 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800853 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700854
855 // All non-virtual displays are currently considered secure.
856 info.secure = true;
857
Iris Chang7501ed62018-04-30 14:45:42 +0800858 if (type == DisplayDevice::DISPLAY_PRIMARY &&
859 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
860 std::swap(info.w, info.h);
861 }
862
Michael Wright28f24d02016-07-12 13:30:53 -0700863 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700864 }
865
Dan Stoza7f7da322014-05-02 15:26:25 -0700866 return NO_ERROR;
867}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700868
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700869status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
870 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700871 return BAD_VALUE;
872 }
873
874 // FIXME for now we always return stats for the primary display
875 memset(stats, 0, sizeof(*stats));
Lloyd Pique41be5d22018-06-21 13:11:48 -0700876 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
877 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700878 return NO_ERROR;
879}
880
Yiwei Zhangcd3f9e92018-08-21 15:15:42 -0700881status_t SurfaceFlinger::getDisplayViewport(const sp<IBinder>& display, Rect* outViewport) {
882 if (outViewport == nullptr || display.get() == nullptr) {
883 return BAD_VALUE;
884 }
885
886 sp<const DisplayDevice> device(getDisplayDevice(display));
887 if (device == nullptr) {
888 return BAD_VALUE;
889 }
890
891 *outViewport = device->getViewport();
892
893 return NO_ERROR;
894}
895
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700896int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
897 const auto display = getDisplayDevice(displayToken);
898 if (!display) {
899 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800900 return BAD_VALUE;
901 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700902
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700903 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700904}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700905
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700906void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
907 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700908 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700909 return;
910 }
911
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700912 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700913 ALOGW("Trying to set config for virtual display");
914 return;
915 }
916
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700917 display->setActiveConfig(mode);
918 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700919}
920
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700921status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700922 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700923 Vector<DisplayInfo> configs;
924 getDisplayConfigs(displayToken, &configs);
925 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
926 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
927 configs.size());
928 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700929 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700930 const auto display = getDisplayDevice(displayToken);
931 if (!display) {
932 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
933 displayToken.get());
934 } else if (display->isVirtual()) {
935 ALOGW("Attempt to set active config %d for virtual display", mode);
936 } else {
937 setActiveConfigInternal(display, mode);
938 }
939 }));
940
Mathias Agopian888c8222012-08-04 21:10:38 -0700941 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700942}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700943status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
944 Vector<ColorMode>* outColorModes) {
945 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700946 return BAD_VALUE;
947 }
948
Michael Wright28f24d02016-07-12 13:30:53 -0700949 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700950 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
951 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700952 type = i;
953 break;
954 }
955 }
956
957 if (type < 0) {
958 return type;
959 }
960
Peiyong Lina52f0292018-03-14 17:26:31 -0700961 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700962 {
963 ConditionalLock _l(mStateLock,
964 std::this_thread::get_id() != mMainThreadId);
965 modes = getHwComposer().getColorModes(type);
966 }
Michael Wright28f24d02016-07-12 13:30:53 -0700967 outColorModes->clear();
968 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
969
970 return NO_ERROR;
971}
972
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700973ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
974 if (const auto display = getDisplayDevice(displayToken)) {
975 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700976 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700977 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700978}
979
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700980void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
981 Dataspace dataSpace, RenderIntent renderIntent) {
982 ColorMode currentMode = display->getActiveColorMode();
983 Dataspace currentDataSpace = display->getCompositionDataSpace();
984 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -0700985
Peiyong Lin38e9a562018-04-10 16:24:20 -0700986 if (mode == currentMode && dataSpace == currentDataSpace &&
987 renderIntent == currentRenderIntent) {
988 return;
989 }
990
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700991 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -0700992 ALOGW("Trying to set config for virtual display");
993 return;
994 }
995
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700996 display->setActiveColorMode(mode);
997 display->setCompositionDataSpace(dataSpace);
998 display->setActiveRenderIntent(renderIntent);
999 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001000
1001 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001002 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1003 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001004}
1005
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001006status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001007 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001008 Vector<ColorMode> modes;
1009 getDisplayColorModes(displayToken, &modes);
1010 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1011 if (mode < ColorMode::NATIVE || !exists) {
1012 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1013 decodeColorMode(mode).c_str(), mode, displayToken.get());
1014 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001015 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001016 const auto display = getDisplayDevice(displayToken);
1017 if (!display) {
1018 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1019 decodeColorMode(mode).c_str(), mode, displayToken.get());
1020 } else if (display->isVirtual()) {
1021 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1022 decodeColorMode(mode).c_str(), mode);
1023 } else {
1024 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1025 RenderIntent::COLORIMETRIC);
1026 }
1027 }));
1028
Michael Wright28f24d02016-07-12 13:30:53 -07001029 return NO_ERROR;
1030}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001031
Svetoslavd85084b2014-03-20 10:28:31 -07001032status_t SurfaceFlinger::clearAnimationFrameStats() {
1033 Mutex::Autolock _l(mStateLock);
1034 mAnimFrameTracker.clearStats();
1035 return NO_ERROR;
1036}
1037
1038status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1039 Mutex::Autolock _l(mStateLock);
1040 mAnimFrameTracker.getStats(outStats);
1041 return NO_ERROR;
1042}
1043
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001044status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1045 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001046 Mutex::Autolock _l(mStateLock);
1047
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001048 const auto display = getDisplayDeviceLocked(displayToken);
1049 if (!display) {
1050 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001051 return BAD_VALUE;
1052 }
1053
Peiyong Linfb069302018-04-25 14:34:31 -07001054 // At this point the DisplayDeivce should already be set up,
1055 // meaning the luminance information is already queried from
1056 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001057 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001058 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1059 capabilities.getDesiredMaxLuminance(),
1060 capabilities.getDesiredMaxAverageLuminance(),
1061 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001062
1063 return NO_ERROR;
1064}
1065
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001066status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001067 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001068 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001069
Chia-I Wu90f669f2017-10-05 14:24:41 -07001070 if (mInjectVSyncs == enable) {
1071 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001072 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001073
1074 if (enable) {
1075 ALOGV("VSync Injections enabled");
1076 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001077 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001078 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001079 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001080 impl::EventThread::InterceptVSyncsCallback(),
1081 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001082 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001083 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001084 } else {
1085 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001086 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001087 }
1088
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001089 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001090 }));
1091
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001092 return NO_ERROR;
1093}
1094
1095status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001096 Mutex::Autolock _l(mStateLock);
1097
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001098 if (!mInjectVSyncs) {
1099 ALOGE("VSync Injections not enabled");
1100 return BAD_VALUE;
1101 }
1102 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1103 ALOGV("Injecting VSync inside SurfaceFlinger");
1104 mVSyncInjector->onInjectSyncEvent(when);
1105 }
1106 return NO_ERROR;
1107}
1108
Lloyd Pique755e3192018-01-31 16:46:15 -08001109status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1110 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001111 // Try to acquire a lock for 1s, fail gracefully
1112 const status_t err = mStateLock.timedLock(s2ns(1));
1113 const bool locked = (err == NO_ERROR);
1114 if (!locked) {
1115 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1116 return TIMED_OUT;
1117 }
1118
1119 outLayers->clear();
1120 mCurrentState.traverseInZOrder([&](Layer* layer) {
1121 outLayers->push_back(layer->getLayerDebugInfo());
1122 });
1123
1124 mStateLock.unlock();
1125 return NO_ERROR;
1126}
1127
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001128// ----------------------------------------------------------------------------
1129
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001130sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1131 ISurfaceComposer::VsyncSource vsyncSource) {
1132 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1133 return mSFEventThread->createEventConnection();
1134 } else {
1135 return mEventThread->createEventConnection();
1136 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001137}
1138
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001139// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001140
1141void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001142 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001143}
1144
1145void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001146 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001147}
1148
1149void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001150 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001151}
1152
1153void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001154 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001155 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001156}
1157
1158status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001159 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001160 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001161}
1162
1163status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001164 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001165 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001166 if (res == NO_ERROR) {
1167 msg->wait();
1168 }
1169 return res;
1170}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001171
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001172void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001173 do {
1174 waitForEvent();
1175 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001176}
1177
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001178void SurfaceFlinger::enableHardwareVsync() {
1179 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001180 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001181 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001182 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001183 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001184 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001185}
1186
Jesse Hall948fe0c2013-10-14 12:56:09 -07001187void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001188 Mutex::Autolock _l(mHWVsyncLock);
1189
Jesse Hall948fe0c2013-10-14 12:56:09 -07001190 if (makeAvailable) {
1191 mHWVsyncAvailable = true;
1192 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001193 // Hardware vsync is not currently available, so abort the resync
1194 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001195 return;
1196 }
1197
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001198 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1199 if (!getHwComposer().isConnected(displayId)) {
1200 return;
1201 }
1202
1203 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001204 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001205
Lloyd Pique41be5d22018-06-21 13:11:48 -07001206 mPrimaryDispSync->reset();
1207 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001208
1209 if (!mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001210 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001211 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001212 mPrimaryHWVsyncEnabled = true;
1213 }
1214}
1215
Jesse Hall948fe0c2013-10-14 12:56:09 -07001216void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001217 Mutex::Autolock _l(mHWVsyncLock);
1218 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001219 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001220 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001221 mPrimaryHWVsyncEnabled = false;
1222 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001223 if (makeUnavailable) {
1224 mHWVsyncAvailable = false;
1225 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001226}
1227
Tim Murray4a4e4a22016-04-19 16:29:23 +00001228void SurfaceFlinger::resyncWithRateLimit() {
1229 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001230
1231 // No explicit locking is needed here since EventThread holds a lock while calling this method
1232 static nsecs_t sLastResyncAttempted = 0;
1233 const nsecs_t now = systemTime();
1234 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001235 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001236 }
Dan Stoza57164302017-05-08 14:03:54 -07001237 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001238}
1239
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001240void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1241 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001242 ATRACE_NAME("SF onVsync");
1243
Steven Thomas3cfac282017-02-06 12:29:30 -08001244 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001245 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001246 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001247 return;
1248 }
1249
1250 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001251 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001252 return;
1253 }
1254
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001255 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1256 // For now, we don't do anything with external display vsyncs.
1257 return;
1258 }
1259
Jamie Gennisd1700752013-10-14 12:22:52 -07001260 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001261
Jamie Gennisd1700752013-10-14 12:22:52 -07001262 { // Scope for the lock
1263 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001264 if (mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001265 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001266 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001267 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001268
1269 if (needsHwVsync) {
1270 enableHardwareVsync();
1271 } else {
1272 disableHardwareVsync(false);
1273 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001274}
1275
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001276void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001277 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1278 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001279}
1280
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001281void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001282 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001283 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001284 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001285
Lloyd Piqueba04e622017-12-14 17:11:26 -08001286 // Ignore events that do not have the right sequenceId.
1287 if (sequenceId != getBE().mComposerSequenceId) {
1288 return;
1289 }
1290
Steven Thomasb02664d2017-07-26 18:48:28 -07001291 // Only lock if we're not on the main thread. This function is normally
1292 // called on a hwbinder thread, but for the primary display it's called on
1293 // the main thread with the state lock already held, so don't attempt to
1294 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001295 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001296
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001297 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001298
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001299 if (std::this_thread::get_id() == mMainThreadId) {
1300 // Process all pending hot plug events immediately if we are on the main thread.
1301 processDisplayHotplugEventsLocked();
1302 }
1303
Lloyd Piqueba04e622017-12-14 17:11:26 -08001304 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001305}
1306
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001307void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001308 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001309 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001310 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001311 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001312 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001313}
1314
Dan Stoza9e56aa02015-11-02 13:00:03 -08001315void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001316 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001317 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001318 getHwComposer().setVsyncEnabled(disp,
1319 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001320}
1321
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001322// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001323void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001324 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001325 // Clear the drawing state so that the logic inside of
1326 // handleTransactionLocked will fire. It will determine the delta between
1327 // mCurrentState and mDrawingState and re-apply all changes when we make the
1328 // transition.
1329 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001330 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001331 mDisplays.clear();
1332}
1333
Steven Thomas050b2c82017-03-06 11:45:16 -08001334void SurfaceFlinger::updateVrFlinger() {
1335 if (!mVrFlinger)
1336 return;
1337 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001338 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001339 return;
1340 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001341
David Sodman105b7dc2017-11-04 20:28:14 -07001342 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001343 ALOGE("Vr flinger is only supported for remote hardware composer"
1344 " service connections. Ignoring request to transition to vr"
1345 " flinger.");
1346 mVrFlingerRequestsDisplay = false;
1347 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001348 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001349
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001350 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001351
Steven Thomas0123ac62018-07-12 11:32:34 -07001352 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001353 LOG_ALWAYS_FATAL_IF(!display);
1354 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001355 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1356 // called below. Clear the reference now so we don't accidentally use it
1357 // later.
1358 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001359
Steven Thomasb02664d2017-07-26 18:48:28 -07001360 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001361 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001362 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001363
Steven Thomasb02664d2017-07-26 18:48:28 -07001364 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001365 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001366 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1367 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001368 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001369
David Sodman105b7dc2017-11-04 20:28:14 -07001370 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1371 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001372
1373 if (vrFlingerRequestsDisplay) {
1374 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001375 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001376
1377 mVisibleRegionsDirty = true;
1378 invalidateHwcGeometry();
1379
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001380 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001381 display = getDefaultDisplayDeviceLocked();
1382 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001383 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001384
Steven Thomasb02664d2017-07-26 18:48:28 -07001385 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001386 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001387 const nsecs_t period = activeConfig->getVsyncPeriod();
1388 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001389
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001390 // The present fences returned from vr_hwc are not an accurate
1391 // representation of vsync times.
Lloyd Pique41be5d22018-06-21 13:11:48 -07001392 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1393 !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001394
Steven Thomasb02664d2017-07-26 18:48:28 -07001395 // Use phase of 0 since phase is not known.
1396 // Use latency of 0, which will snap to the ideal latency.
1397 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001398
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001399 resyncToHardwareVsync(false);
1400
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001401 android_atomic_or(1, &mRepaintEverything);
1402 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001403}
1404
Mathias Agopian4fec8732012-06-29 14:12:52 -07001405void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001406 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001407 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001408 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001409 bool frameMissed = !mHadClientComposition &&
1410 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001411 (mPreviousPresentFence->getSignalTime() ==
1412 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001413 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001414 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001415 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001416 mTimeStats.incrementMissedFrames();
1417 if (mPropagateBackpressure) {
1418 signalLayerUpdate();
1419 break;
1420 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001421 }
Dan Stoza50182882016-07-08 12:02:20 -07001422
Steven Thomas050b2c82017-03-06 11:45:16 -08001423 // Now that we're going to make it to the handleMessageTransaction()
1424 // call below it's safe to call updateVrFlinger(), which will
1425 // potentially trigger a display handoff.
1426 updateVrFlinger();
1427
Dan Stoza6b9454d2014-11-07 16:00:59 -08001428 bool refreshNeeded = handleMessageTransaction();
1429 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001430 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001431 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001432 // Signal a refresh if a transaction modified the window state,
1433 // a new buffer was latched, or if HWC has requested a full
1434 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001435 signalRefresh();
1436 }
1437 break;
1438 }
1439 case MessageQueue::REFRESH: {
1440 handleMessageRefresh();
1441 break;
1442 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001443 }
1444}
1445
Dan Stoza6b9454d2014-11-07 16:00:59 -08001446bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001447 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001448 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001449 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001450 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001451 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001452 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001453}
1454
Mathias Agopian4fec8732012-06-29 14:12:52 -07001455void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001456 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001457
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001458 mRefreshPending = false;
1459
David Sodmanfa9b2af2017-12-24 13:28:59 -08001460 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
David Sodman2b406362017-12-15 13:33:47 -08001461 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001462 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001463 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001464 for (const auto& [token, display] : mDisplays) {
1465 beginFrame(display);
1466 prepareFrame(display);
1467 doDebugFlashRegions(display, repaintEverything);
1468 doComposition(display, repaintEverything);
1469 }
1470
Adrian Roos1e1a1282017-11-01 19:05:31 +01001471 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001472 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001473
1474 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001475 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001476
Dan Stozabfbffeb2016-07-21 14:49:33 -07001477 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001478 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001479 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001480 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001481 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001482
Jorim Jaggi90535212018-05-23 23:44:06 +02001483 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001484
David Sodman7e4ae112018-02-09 15:02:28 -08001485 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001486 for (const auto& [token, display] : mDisplays) {
1487 const auto displayId = display->getId();
David Sodman7e4ae112018-02-09 15:02:28 -08001488 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[displayId]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001489 compositionInfo.hwc.hwcLayer = nullptr;
1490 }
David Sodmanba340492018-08-05 21:51:33 -07001491 }
David Sodman7e4ae112018-02-09 15:02:28 -08001492
1493 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001494}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001495
David Sodmanfa9b2af2017-12-24 13:28:59 -08001496
1497bool SurfaceFlinger::handleMessageInvalidate() {
1498 ATRACE_CALL();
1499 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001500}
1501
David Sodman79bba0e2018-08-05 18:07:49 -07001502void SurfaceFlinger::calculateWorkingSet() {
1503 ATRACE_CALL();
1504 ALOGV(__FUNCTION__);
1505
David Sodman79bba0e2018-08-05 18:07:49 -07001506 // build the h/w work list
1507 if (CC_UNLIKELY(mGeometryInvalid)) {
1508 mGeometryInvalid = false;
1509 for (const auto& [token, display] : mDisplays) {
1510 const auto displayId = display->getId();
1511 if (displayId >= 0) {
1512 const Vector<sp<Layer>>& currentLayers(
1513 display->getVisibleLayersSortedByZ());
1514 for (size_t i = 0; i < currentLayers.size(); i++) {
1515 const auto& layer = currentLayers[i];
1516
1517 if (!layer->hasHwcLayer(displayId)) {
1518 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1519 layer->forceClientComposition(displayId);
1520 continue;
1521 }
1522 }
1523
1524 layer->setGeometry(display, i);
1525 if (mDebugDisableHWC || mDebugRegion) {
1526 layer->forceClientComposition(displayId);
1527 }
1528 }
1529 }
1530 }
1531 }
1532
1533 // Set the per-frame data
1534 for (const auto& [token, display] : mDisplays) {
1535 const auto displayId = display->getId();
1536 if (displayId < 0) {
1537 continue;
1538 }
1539
1540 if (mDrawingState.colorMatrixChanged) {
1541 display->setColorTransform(mDrawingState.colorMatrix);
1542 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1543 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1544 "display %d: %d", displayId, result);
1545 }
1546 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1547 if (layer->isHdrY410()) {
1548 layer->forceClientComposition(displayId);
1549 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1550 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1551 !display->hasHDR10Support()) {
1552 layer->forceClientComposition(displayId);
1553 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1554 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1555 !display->hasHLGSupport()) {
1556 layer->forceClientComposition(displayId);
1557 }
1558
1559 if (layer->getForceClientComposition(displayId)) {
1560 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1561 layer->setCompositionType(displayId, HWC2::Composition::Client);
1562 continue;
1563 }
1564
1565 layer->setPerFrameData(display);
1566 }
1567
Peiyong Lin13effd12018-07-24 17:01:47 -07001568 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001569 ColorMode colorMode;
1570 Dataspace dataSpace;
1571 RenderIntent renderIntent;
1572 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1573 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1574 }
1575 }
1576
1577 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001578
1579 for (const auto& [token, display] : mDisplays) {
David Sodman15fb96e2018-01-07 10:23:24 -08001580 const auto displayId = display->getId();
1581 getBE().mCompositionInfo[displayId].clear();
David Sodmanba340492018-08-05 21:51:33 -07001582 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1583 auto displayId = display->getId();
1584 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1585 if (!layer->setHwcLayer(displayId)) {
1586 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1587 }
David Sodman15fb96e2018-01-07 10:23:24 -08001588 layer->getBE().compositionInfo.hwc.displayId = displayId;
1589 getBE().mCompositionInfo[displayId].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001590 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1591 }
1592 }
David Sodman79bba0e2018-08-05 18:07:49 -07001593}
1594
David Sodmanfa9b2af2017-12-24 13:28:59 -08001595void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001596{
1597 // is debugging enabled
1598 if (CC_LIKELY(!mDebugRegion))
1599 return;
1600
David Sodmanfa9b2af2017-12-24 13:28:59 -08001601 if (display->isPoweredOn()) {
1602 // transform the dirty region into this screen's coordinate space
1603 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1604 if (!dirtyRegion.isEmpty()) {
1605 // redraw the whole screen
1606 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001607
David Sodmanfa9b2af2017-12-24 13:28:59 -08001608 // and draw the dirty region
1609 const int32_t height = display->getHeight();
1610 auto& engine(getRenderEngine());
1611 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001612
David Sodmanfa9b2af2017-12-24 13:28:59 -08001613 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001614 }
1615 }
1616
David Sodmanfa9b2af2017-12-24 13:28:59 -08001617 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001618
1619 if (mDebugRegion > 1) {
1620 usleep(mDebugRegion * 1000);
1621 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001622
David Sodmanfa9b2af2017-12-24 13:28:59 -08001623 if (display->isPoweredOn()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001624 status_t result = display->prepareFrame(*getBE().mHwc);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001625 ALOGE_IF(result != NO_ERROR,
1626 "prepareFrame for display %d failed:"
1627 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001628 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001629 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001630}
1631
Adrian Roos1e1a1282017-11-01 19:05:31 +01001632void SurfaceFlinger::doTracing(const char* where) {
1633 ATRACE_CALL();
1634 ATRACE_NAME(where);
1635 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001636 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001637 }
1638}
1639
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001640void SurfaceFlinger::logLayerStats() {
1641 ATRACE_CALL();
1642 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001643 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001644 if (display->isPrimary()) {
1645 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001646 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001647 }
1648 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001649
1650 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001651 }
1652}
1653
David Sodman2b406362017-12-15 13:33:47 -08001654void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001655{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001656 ATRACE_CALL();
1657 ALOGV("preComposition");
1658
David Sodman2b406362017-12-15 13:33:47 -08001659 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1660
Mathias Agopiancd60f992012-08-16 16:28:27 -07001661 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001662 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001663 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001664 needExtraInvalidate = true;
1665 }
Robert Carr2047fae2016-11-28 14:09:09 -08001666 });
1667
Mathias Agopiancd60f992012-08-16 16:28:27 -07001668 if (needExtraInvalidate) {
1669 signalLayerUpdate();
1670 }
1671}
1672
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001673void SurfaceFlinger::updateCompositorTiming(
1674 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1675 std::shared_ptr<FenceTime>& presentFenceTime) {
1676 // Update queue of past composite+present times and determine the
1677 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001678 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001679 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001680 while (!getBE().mCompositePresentTimes.empty()) {
1681 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001682 // Cached values should have been updated before calling this method,
1683 // which helps avoid duplicate syscalls.
1684 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1685 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1686 break;
1687 }
1688 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001689 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001690 }
1691
1692 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001693 while (getBE().mCompositePresentTimes.size() > 16) {
1694 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001695 }
1696
Brian Andersond0010582017-03-07 13:20:31 -08001697 setCompositorTimingSnapped(
1698 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1699}
1700
1701void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1702 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001703 // Integer division and modulo round toward 0 not -inf, so we need to
1704 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001705 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001706 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1707 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1708
Brian Andersond0010582017-03-07 13:20:31 -08001709 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1710 if (idealLatency <= 0) {
1711 idealLatency = vsyncInterval;
1712 }
1713
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001714 // Snap the latency to a value that removes scheduling jitter from the
1715 // composition and present times, which often have >1ms of jitter.
1716 // Reducing jitter is important if an app attempts to extrapolate
1717 // something (such as user input) to an accurate diasplay time.
1718 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1719 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001720 nsecs_t bias = vsyncInterval / 2;
1721 int64_t extraVsyncs =
1722 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1723 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1724 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001725
David Sodman99974d22017-11-28 12:04:33 -08001726 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1727 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1728 getBE().mCompositorTiming.interval = vsyncInterval;
1729 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001730}
1731
David Sodman2b406362017-12-15 13:33:47 -08001732void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001733{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001734 ATRACE_CALL();
1735 ALOGV("postComposition");
1736
Brian Anderson3546a3f2016-07-14 11:51:14 -07001737 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001738 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001739 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001740 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001741 }
1742
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001743 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001744 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001745
David Sodman73beded2017-11-15 11:56:06 -08001746 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001747 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001748 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001749 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001750 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001751 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001752 } else {
1753 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1754 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001755
David Sodman73beded2017-11-15 11:56:06 -08001756 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001757 mPreviousPresentFence =
1758 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1759 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001760 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001761
Lloyd Pique41be5d22018-06-21 13:11:48 -07001762 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1763 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001764
David Sodman2b406362017-12-15 13:33:47 -08001765 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001766 // when we started doing work for this frame, but that should be okay
1767 // since updateCompositorTiming has snapping logic.
1768 updateCompositorTiming(
David Sodman2b406362017-12-15 13:33:47 -08001769 vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001770 CompositorTiming compositorTiming;
1771 {
David Sodman99974d22017-11-28 12:04:33 -08001772 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1773 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001774 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001775
Robert Carr2047fae2016-11-28 14:09:09 -08001776 mDrawingState.traverseInZOrder([&](Layer* layer) {
1777 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001778 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001779 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001780 recordBufferingStats(layer->getName().string(),
1781 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001782 }
Robert Carr2047fae2016-11-28 14:09:09 -08001783 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001784
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001785 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001786 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001787 enableHardwareVsync();
1788 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001789 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001790 }
1791 }
1792
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001793 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001794 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001795 enableHardwareVsync();
1796 }
1797 }
1798
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001799 if (mAnimCompositionPending) {
1800 mAnimCompositionPending = false;
1801
Brian Anderson4e606e32017-03-16 15:34:57 -07001802 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001803 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001804 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001805 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001806 // The HWC doesn't support present fences, so use the refresh
1807 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001808 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001809 mAnimFrameTracker.setActualPresentTime(presentTime);
1810 }
1811 mAnimFrameTracker.advanceFrame();
1812 }
Dan Stozab90cf072015-03-05 11:05:59 -08001813
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001814 mTimeStats.incrementTotalFrames();
1815 if (mHadClientComposition) {
1816 mTimeStats.incrementClientCompositionFrames();
1817 }
1818
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001819 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001820 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001821 return;
1822 }
1823
1824 nsecs_t currentTime = systemTime();
1825 if (mHasPoweredOff) {
1826 mHasPoweredOff = false;
1827 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001828 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001829 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001830 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1831 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001832 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001833 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001834 }
David Sodman4a36e932017-11-07 14:29:47 -08001835 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001836 }
David Sodman4a36e932017-11-07 14:29:47 -08001837 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001838
1839 {
1840 std::lock_guard lock(mTexturePoolMutex);
1841 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1842 if (refillCount > 0) {
1843 const size_t offset = mTexturePool.size();
1844 mTexturePool.resize(mTexturePoolSize);
1845 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1846 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1847 }
1848 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001849}
1850
1851void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001852 ATRACE_CALL();
1853 ALOGV("rebuildLayerStacks");
1854
Mathias Agopiancd60f992012-08-16 16:28:27 -07001855 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001856 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001857 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001858 mVisibleRegionsDirty = false;
1859 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001860
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001861 for (const auto& pair : mDisplays) {
1862 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001863 Region opaqueRegion;
1864 Region dirtyRegion;
1865 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001866 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001867 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001868 const Rect bounds = display->getBounds();
1869 if (display->isPoweredOn()) {
1870 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001871
Jeff Sharkey76488112017-02-27 14:15:18 -07001872 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001873 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001874 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001875 Region drawRegion(tr.transform(
1876 layer->visibleNonTransparentRegion));
1877 drawRegion.andSelf(bounds);
1878 if (!drawRegion.isEmpty()) {
1879 layersSortedByZ.add(layer);
1880 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001881 // Clear out the HWC layer if this layer was
1882 // previously visible, but no longer is
1883 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001884 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001885 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001886 // WM changes display->layerStack upon sleep/awake.
1887 // Here we make sure we delete the HWC layers even if
1888 // WM changed their layer stack.
1889 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001890 }
1891
1892 // If a layer is not going to get a release fence because
1893 // it is invisible, but it is also going to release its
1894 // old buffer, add it to the list of layers needing
1895 // fences.
1896 if (hwcLayerDestroyed) {
1897 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1898 mLayersWithQueuedFrames.cend(), layer);
1899 if (found != mLayersWithQueuedFrames.cend()) {
1900 layersNeedingFences.add(layer);
1901 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001902 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001903 });
1904 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001905 display->setVisibleLayersSortedByZ(layersSortedByZ);
1906 display->setLayersNeedingFences(layersNeedingFences);
1907 display->undefinedRegion.set(bounds);
1908 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1909 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001910 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001911 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001912}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001913
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001914// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001915// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001916// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001917// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001918// The returned HDR data space is one of
1919// - Dataspace::UNKNOWN
1920// - Dataspace::BT2020_HLG
1921// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001922Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1923 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001924 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001925 *outHdrDataSpace = Dataspace::UNKNOWN;
1926
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001927 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001928 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001929 case Dataspace::V0_SCRGB:
1930 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001931 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001932 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001933 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001934 case Dataspace::BT2020_PQ:
1935 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001936 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001937 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001938 case Dataspace::BT2020_HLG:
1939 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001940 // When there's mixed PQ content and HLG content, we set the HDR
1941 // data space to be BT2020_PQ and convert HLG to PQ.
1942 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1943 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001944 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001945 break;
1946 default:
1947 break;
1948 }
Romain Guy54f154a2017-10-24 21:40:32 +01001949 }
1950
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001951 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001952}
1953
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001954// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001955void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1956 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001957 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1958 *outMode = ColorMode::NATIVE;
1959 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001960 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001961 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001962 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001963
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001964 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001965 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001966
Peiyong Lindfde5112018-06-05 10:58:41 -07001967 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001968 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001969 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001970 if (isHdr) {
1971 bestDataSpace = hdrDataSpace;
1972 }
1973
Chia-I Wu0d711262018-05-21 15:19:35 -07001974 RenderIntent intent;
1975 switch (mDisplayColorSetting) {
1976 case DisplayColorSetting::MANAGED:
1977 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001978 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001979 break;
1980 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001981 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001982 break;
1983 default: // vendor display color setting
1984 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1985 break;
1986 }
Chia-I Wube02ec02018-05-18 10:59:36 -07001987
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001988 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001989}
1990
David Sodmanfa9b2af2017-12-24 13:28:59 -08001991void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08001992{
David Sodmanfa9b2af2017-12-24 13:28:59 -08001993 bool dirty = !display->getDirtyRegion(false).isEmpty();
1994 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
1995 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08001996
David Sodmanfa9b2af2017-12-24 13:28:59 -08001997 // If nothing has changed (!dirty), don't recompose.
1998 // If something changed, but we don't currently have any visible layers,
1999 // and didn't when we last did a composition, then skip it this time.
2000 // The second rule does two things:
2001 // - When all layers are removed from a display, we'll emit one black
2002 // frame, then nothing more until we get new layers.
2003 // - When a display is created with a private layer stack, we won't
2004 // emit any black frames until a layer is added to the layer stack.
2005 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002006
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002007 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2008 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002009 mustRecompose ? "doing" : "skipping",
2010 dirty ? "+" : "-",
2011 empty ? "+" : "-",
2012 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002013
David Sodmanfa9b2af2017-12-24 13:28:59 -08002014 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002015
David Sodmanfa9b2af2017-12-24 13:28:59 -08002016 if (mustRecompose) {
2017 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002018 }
2019}
2020
David Sodmanfa9b2af2017-12-24 13:28:59 -08002021void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002022{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002023 if (!display->isPoweredOn()) {
2024 return;
David Sodman2b406362017-12-15 13:33:47 -08002025 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002026
2027 status_t result = display->prepareFrame(*getBE().mHwc);
2028 ALOGE_IF(result != NO_ERROR,
2029 "prepareFrame for display %d failed:"
2030 " %d (%s)",
2031 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002032}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002033
David Sodmanfa9b2af2017-12-24 13:28:59 -08002034void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002035 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002036 ALOGV("doComposition");
2037
David Sodmanfa9b2af2017-12-24 13:28:59 -08002038 if (display->isPoweredOn()) {
2039 // transform the dirty region into this screen's coordinate space
2040 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002041
David Sodmanfa9b2af2017-12-24 13:28:59 -08002042 // repaint the framebuffer (if needed)
2043 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002044
David Sodmanfa9b2af2017-12-24 13:28:59 -08002045 display->dirtyRegion.clear();
2046 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002047 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002048 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002049}
2050
David Sodmanfa9b2af2017-12-24 13:28:59 -08002051void SurfaceFlinger::postFrame()
2052{
2053 // |mStateLock| not needed as we are on the main thread
2054 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2055 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2056 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2057 logFrameStats();
2058 }
2059 }
2060}
2061
2062void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002063{
Mathias Agopian841cde52012-03-01 15:44:37 -08002064 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002065 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002066
David Sodmanfa9b2af2017-12-24 13:28:59 -08002067 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002068
David Sodmanfa9b2af2017-12-24 13:28:59 -08002069 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002070 const auto displayId = display->getId();
2071 if (displayId >= 0) {
2072 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002073 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002074 display->onSwapBuffersCompleted();
2075 display->makeCurrent();
2076 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002077 sp<Fence> releaseFence = Fence::NO_FENCE;
2078
Chia-I Wu7b549592017-11-15 09:14:57 -08002079 // The layer buffer from the previous frame (if any) is released
2080 // by HWC only when the release fence from this frame (if any) is
2081 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002082 auto hwcLayer = layer->getHwcLayer(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002083 if (displayId >= 0) {
2084 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
2085 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002086
2087 // If the layer was client composited in the previous frame, we
2088 // need to merge with the previous client target acquire fence.
2089 // Since we do not track that, always merge with the current
2090 // client target acquire fence when it is available, even though
2091 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002092 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002093 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002094 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002095 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002096
David Sodmanb8af7922017-12-21 15:17:55 -08002097 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002098 }
Chia-I Wu83806892017-11-16 10:50:20 -08002099
2100 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002101 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002102 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002103 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002104 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002105 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002106 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002107 }
2108 }
2109
Dominik Laskowski7e045462018-05-30 13:02:02 -07002110 if (displayId >= 0) {
2111 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002112 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002113 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002114}
2115
Mathias Agopian87baae12012-07-31 12:38:26 -07002116void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002117{
Mathias Agopian841cde52012-03-01 15:44:37 -08002118 ATRACE_CALL();
2119
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002120 // here we keep a copy of the drawing state (that is the state that's
2121 // going to be overwritten by handleTransactionLocked()) outside of
2122 // mStateLock so that the side-effects of the State assignment
2123 // don't happen with mStateLock held (which can cause deadlocks).
2124 State drawingState(mDrawingState);
2125
Mathias Agopianca4d3602011-05-19 15:38:14 -07002126 Mutex::Autolock _l(mStateLock);
2127 const nsecs_t now = systemTime();
2128 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002129
Mathias Agopianca4d3602011-05-19 15:38:14 -07002130 // Here we're guaranteed that some transaction flags are set
2131 // so we can call handleTransactionLocked() unconditionally.
2132 // We call getTransactionFlags(), which will also clear the flags,
2133 // with mStateLock held to guarantee that mCurrentState won't change
2134 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002135
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002136 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002137 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002138 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002139
Mathias Agopianca4d3602011-05-19 15:38:14 -07002140 mLastTransactionTime = systemTime() - now;
2141 mDebugInTransaction = 0;
2142 invalidateHwcGeometry();
2143 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002144}
2145
Dominik Laskowski7e045462018-05-30 13:02:02 -07002146DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002147 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002148 // Figure out whether the event is for the primary display or an
2149 // external display by matching the Hwc display id against one for a
2150 // connected display. If we did not find a match, we then check what
2151 // displays are not already connected to determine the type. If we don't
2152 // have a connected primary display, we assume the new display is meant to
2153 // be the primary display, and then if we don't have an external display,
2154 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002155 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2156 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002157 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002158 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002159 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002160 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002161 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002162 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002163 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002164 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002165 return DisplayDevice::DISPLAY_EXTERNAL;
2166 }
2167
2168 return DisplayDevice::DISPLAY_ID_INVALID;
2169}
2170
Lloyd Piqueba04e622017-12-14 17:11:26 -08002171void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2172 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002173 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002174 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002175 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002176 continue;
2177 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002178
2179 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2180 ALOGE("External displays are not supported by the vr hardware composer.");
2181 continue;
2182 }
2183
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002184 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002185 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002186 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002187 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002188 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002189
2190 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002191 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002192 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002193 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002194 DisplayDeviceState info;
2195 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002196 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2197 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002198 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002199 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002200 mInterceptor->saveDisplayCreation(info);
2201 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002202 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002203 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002204
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002205 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002206 if (idx >= 0) {
2207 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002208 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002209 mCurrentState.displays.removeItemsAt(idx);
2210 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002211 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002212 }
2213
2214 processDisplayChangesLocked();
2215 }
2216
2217 mPendingHotplugEvents.clear();
2218}
2219
Lloyd Pique99d3da52018-01-22 17:48:03 -08002220sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002221 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002222 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002223 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002224 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002225 HdrCapabilities hdrCapabilities;
2226 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002227
Peiyong Lin13effd12018-07-24 17:01:47 -07002228 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002229 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002230 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002231 if (isWideColorMode(colorMode)) {
2232 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002233 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002234
Dominik Laskowski7e045462018-05-30 13:02:02 -07002235 std::vector<RenderIntent> renderIntents =
2236 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002237 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002238 }
tangrobin6753a022018-08-10 10:58:54 +08002239 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002240
tangrobin6753a022018-08-10 10:58:54 +08002241 if (displayId >= 0) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002242 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2243 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2244 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002245
2246 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2247 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2248
2249 /*
2250 * Create our display's surface
2251 */
2252 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2253 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002254 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002255 renderSurface->setNativeWindow(nativeWindow.get());
2256 const int displayWidth = renderSurface->queryWidth();
2257 const int displayHeight = renderSurface->queryHeight();
2258
2259 // Make sure that composition can never be stalled by a virtual display
2260 // consumer that isn't processing buffers fast enough. We have to do this
2261 // in two places:
2262 // * Here, in case the display is composed entirely by HWC.
2263 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2264 // window's swap interval in eglMakeCurrent, so they'll override the
2265 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002266 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002267 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2268 }
2269
2270 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002271 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002272
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002273 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002274 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2275 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2276 displayHeight, hasWideColorGamut, hdrCapabilities,
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002277 supportedPerFrameMetadata, hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002278
2279 if (maxFrameBufferAcquiredBuffers >= 3) {
2280 nativeWindowSurface->preallocateBuffers();
2281 }
2282
2283 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002284 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2285 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002286 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002287 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002288 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002289 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002290 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002291 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002292 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002293 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002294 display->setLayerStack(state.layerStack);
2295 display->setProjection(state.orientation, state.viewport, state.frame);
2296 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002297
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002298 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002299}
2300
Lloyd Pique347200f2017-12-14 17:00:15 -08002301void SurfaceFlinger::processDisplayChangesLocked() {
2302 // here we take advantage of Vector's copy-on-write semantics to
2303 // improve performance by skipping the transaction entirely when
2304 // know that the lists are identical
2305 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2306 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2307 if (!curr.isIdenticalTo(draw)) {
2308 mVisibleRegionsDirty = true;
2309 const size_t cc = curr.size();
2310 size_t dc = draw.size();
2311
2312 // find the displays that were removed
2313 // (ie: in drawing state but not in current state)
2314 // also handle displays that changed
2315 // (ie: displays that are in both lists)
2316 for (size_t i = 0; i < dc;) {
2317 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2318 if (j < 0) {
2319 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002320 // Call makeCurrent() on the primary display so we can
2321 // be sure that nothing associated with this display
2322 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002323 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2324 defaultDisplay->makeCurrent();
2325 }
2326 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2327 display->disconnect(getHwComposer());
2328 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002329 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2330 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2331 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2332 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2333 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002334 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002335 } else {
2336 // this display is in both lists. see if something changed.
2337 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002338 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002339 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2340 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2341 if (state_binder != draw_binder) {
2342 // changing the surface is like destroying and
2343 // recreating the DisplayDevice, so we just remove it
2344 // from the drawing state, so that it get re-added
2345 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002346 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2347 display->disconnect(getHwComposer());
2348 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002349 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002350 mDrawingState.displays.removeItemsAt(i);
2351 dc--;
2352 // at this point we must loop to the next item
2353 continue;
2354 }
2355
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002356 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002357 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002358 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002359 }
2360 if ((state.orientation != draw[i].orientation) ||
2361 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002362 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002363 }
2364 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002365 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002366 }
2367 }
2368 }
2369 ++i;
2370 }
2371
2372 // find displays that were added
2373 // (ie: in current state but not in drawing state)
2374 for (size_t i = 0; i < cc; i++) {
2375 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2376 const DisplayDeviceState& state(curr[i]);
2377
2378 sp<DisplaySurface> dispSurface;
2379 sp<IGraphicBufferProducer> producer;
2380 sp<IGraphicBufferProducer> bqProducer;
2381 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002382 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002383
Dominik Laskowski7e045462018-05-30 13:02:02 -07002384 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002385 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002386 // Virtual displays without a surface are dormant:
2387 // they have external state (layer stack, projection,
2388 // etc.) but no internal state (i.e. a DisplayDevice).
2389 if (state.surface != nullptr) {
2390 // Allow VR composer to use virtual displays.
2391 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2392 int width = 0;
2393 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2394 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2395 int height = 0;
2396 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2397 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2398 int intFormat = 0;
2399 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2400 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002401 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002402
Dominik Laskowski7e045462018-05-30 13:02:02 -07002403 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2404 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002405 }
2406
2407 // TODO: Plumb requested format back up to consumer
2408
2409 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002410 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002411 bqProducer, bqConsumer,
2412 state.displayName);
2413
2414 dispSurface = vds;
2415 producer = vds;
2416 }
2417 } else {
2418 ALOGE_IF(state.surface != nullptr,
2419 "adding a supported display, but rendering "
2420 "surface is provided (%p), ignoring it",
2421 state.surface.get());
2422
Dominik Laskowski7e045462018-05-30 13:02:02 -07002423 displayId = state.type;
2424 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002425 producer = bqProducer;
2426 }
2427
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002428 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002429 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002430 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002431 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002432 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002433 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002434 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2435 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2436 true);
2437 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2438 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2439 true);
2440 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002441 }
2442 }
2443 }
2444 }
2445 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002446
2447 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002448}
2449
Mathias Agopian87baae12012-07-31 12:38:26 -07002450void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002451{
Dan Stoza7dde5992015-05-22 09:51:44 -07002452 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002453 mCurrentState.traverseInZOrder([](Layer* layer) {
2454 layer->notifyAvailableFrames();
2455 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002456
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002457 /*
2458 * Traversal of the children
2459 * (perform the transaction for each of them if needed)
2460 */
2461
Mathias Agopian3559b072012-08-15 13:46:03 -07002462 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002463 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002464 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002465 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002466
2467 const uint32_t flags = layer->doTransaction(0);
2468 if (flags & Layer::eVisibleRegion)
2469 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002470 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002471 }
2472
2473 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002474 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002475 */
2476
Mathias Agopiane57f2922012-08-09 16:29:12 -07002477 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002478 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002479 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002480 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002481
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002482 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002483 // The transform hint might have changed for some layers
2484 // (either because a display has changed, or because a layer
2485 // as changed).
2486 //
2487 // Walk through all the layers in currentLayers,
2488 // and update their transform hint.
2489 //
2490 // If a layer is visible only on a single display, then that
2491 // display is used to calculate the hint, otherwise we use the
2492 // default display.
2493 //
2494 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2495 // the hint is set before we acquire a buffer from the surface texture.
2496 //
2497 // NOTE: layer transactions have taken place already, so we use their
2498 // drawing state. However, SurfaceFlinger's own transaction has not
2499 // happened yet, so we must use the current state layer list
2500 // (soon to become the drawing state list).
2501 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002502 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002503 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002504 bool first = true;
2505 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002506 // NOTE: we rely on the fact that layers are sorted by
2507 // layerStack first (so we don't have to traverse the list
2508 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002509 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002510 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002511 currentlayerStack = layerStack;
2512 // figure out if this layerstack is mirrored
2513 // (more than one display) if so, pick the default display,
2514 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002515 hintDisplay = nullptr;
2516 for (const auto& [token, display] : mDisplays) {
2517 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2518 if (hintDisplay) {
2519 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002520 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002521 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002522 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002523 }
2524 }
2525 }
2526 }
Chet Haase91d25932013-04-11 15:24:55 -07002527
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002528 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002529 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2530 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002531
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002532 // could be null when this layer is using a layerStack
2533 // that is not visible on any display. Also can occur at
2534 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002535 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002536 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002537
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002538 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002539 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002540 if (hintDisplay) {
2541 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002542 }
Robert Carr2047fae2016-11-28 14:09:09 -08002543
2544 first = false;
2545 });
Mathias Agopian84300952012-11-21 16:02:13 -08002546 }
2547
2548
Mathias Agopian3559b072012-08-15 13:46:03 -07002549 /*
2550 * Perform our own transaction if needed
2551 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002552
2553 if (mLayersAdded) {
2554 mLayersAdded = false;
2555 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002556 mVisibleRegionsDirty = true;
2557 }
2558
2559 // some layers might have been removed, so
2560 // we need to update the regions they're exposing.
2561 if (mLayersRemoved) {
2562 mLayersRemoved = false;
2563 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002564 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002565 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002566 // this layer is not visible anymore
2567 // TODO: we could traverse the tree from front to back and
2568 // compute the actual visible region
2569 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002570 Region visibleReg;
2571 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002572 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002573 }
Robert Carr2047fae2016-11-28 14:09:09 -08002574 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002575 }
2576
2577 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002578
2579 updateCursorAsync();
2580}
2581
2582void SurfaceFlinger::updateCursorAsync()
2583{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002584 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002585 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002586 continue;
2587 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002588
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002589 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2590 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002591 }
2592 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002593}
2594
2595void SurfaceFlinger::commitTransaction()
2596{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002597 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002598 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002599 for (const auto& l : mLayersPendingRemoval) {
2600 recordBufferingStats(l->getName().string(),
2601 l->getOccupancyHistory(true));
2602 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002603 }
2604 mLayersPendingRemoval.clear();
2605 }
2606
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002607 // If this transaction is part of a window animation then the next frame
2608 // we composite should be considered an animation as well.
2609 mAnimCompositionPending = mAnimTransactionPending;
2610
Mathias Agopian4fec8732012-06-29 14:12:52 -07002611 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002612 // clear the "changed" flags in current state
2613 mCurrentState.colorMatrixChanged = false;
2614
Robert Carr1f0a16a2016-10-24 16:27:39 -07002615 mDrawingState.traverseInZOrder([](Layer* layer) {
2616 layer->commitChildList();
2617 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002618 mTransactionPending = false;
2619 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002620 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002621}
2622
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002623void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2624 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002625 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002626 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002627
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002628 Region aboveOpaqueLayers;
2629 Region aboveCoveredLayers;
2630 Region dirty;
2631
Mathias Agopian87baae12012-07-31 12:38:26 -07002632 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002633
Robert Carr2047fae2016-11-28 14:09:09 -08002634 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002635 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002636 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002637
Jesse Hall01e29052013-02-19 16:13:35 -08002638 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002639 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002640 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002641 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002642
Mathias Agopianab028732010-03-16 16:41:46 -07002643 /*
2644 * opaqueRegion: area of a surface that is fully opaque.
2645 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002646 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002647
2648 /*
2649 * visibleRegion: area of a surface that is visible on screen
2650 * and not fully transparent. This is essentially the layer's
2651 * footprint minus the opaque regions above it.
2652 * Areas covered by a translucent surface are considered visible.
2653 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002654 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002655
2656 /*
2657 * coveredRegion: area of a surface that is covered by all
2658 * visible regions above it (which includes the translucent areas).
2659 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002660 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002661
Jesse Halla8026d22012-09-25 13:25:04 -07002662 /*
2663 * transparentRegion: area of a surface that is hinted to be completely
2664 * transparent. This is only used to tell when the layer has no visible
2665 * non-transparent regions and can be removed from the layer list. It
2666 * does not affect the visibleRegion of this layer or any layers
2667 * beneath it. The hint may not be correct if apps don't respect the
2668 * SurfaceView restrictions (which, sadly, some don't).
2669 */
2670 Region transparentRegion;
2671
Mathias Agopianab028732010-03-16 16:41:46 -07002672
2673 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002674 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002675 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002676 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002677 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002678 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002679 if (!visibleRegion.isEmpty()) {
2680 // Remove the transparent area from the visible region
2681 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002682 if (tr.preserveRects()) {
2683 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002684 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002685 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002686 // transformation too complex, can't do the
2687 // transparent region optimization.
2688 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002689 }
Mathias Agopianab028732010-03-16 16:41:46 -07002690 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002691
Mathias Agopianab028732010-03-16 16:41:46 -07002692 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002693 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002694 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002695 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002696 // the opaque region is the layer's footprint
2697 opaqueRegion = visibleRegion;
2698 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002699 }
2700 }
2701
Robert Carre5f4f692018-01-12 13:12:28 -08002702 if (visibleRegion.isEmpty()) {
2703 layer->clearVisibilityRegions();
2704 return;
2705 }
2706
Mathias Agopianab028732010-03-16 16:41:46 -07002707 // Clip the covered region to the visible region
2708 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2709
2710 // Update aboveCoveredLayers for next (lower) layer
2711 aboveCoveredLayers.orSelf(visibleRegion);
2712
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002713 // subtract the opaque region covered by the layers above us
2714 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002715
2716 // compute this layer's dirty region
2717 if (layer->contentDirty) {
2718 // we need to invalidate the whole region
2719 dirty = visibleRegion;
2720 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002721 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002722 layer->contentDirty = false;
2723 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002724 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002725 * the exposed region consists of two components:
2726 * 1) what's VISIBLE now and was COVERED before
2727 * 2) what's EXPOSED now less what was EXPOSED before
2728 *
2729 * note that (1) is conservative, we start with the whole
2730 * visible region but only keep what used to be covered by
2731 * something -- which mean it may have been exposed.
2732 *
2733 * (2) handles areas that were not covered by anything but got
2734 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002735 */
Mathias Agopianab028732010-03-16 16:41:46 -07002736 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002737 const Region oldVisibleRegion = layer->visibleRegion;
2738 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002739 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2740 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002741 }
2742 dirty.subtractSelf(aboveOpaqueLayers);
2743
2744 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002745 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002746
Mathias Agopianab028732010-03-16 16:41:46 -07002747 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002748 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002749
Jesse Halla8026d22012-09-25 13:25:04 -07002750 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002751 layer->setVisibleRegion(visibleRegion);
2752 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002753 layer->setVisibleNonTransparentRegion(
2754 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002755 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002756
Mathias Agopian87baae12012-07-31 12:38:26 -07002757 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002758}
2759
Chia-I Wuab0c3192017-08-01 11:29:00 -07002760void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002761 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002762 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2763 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002764 }
2765 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002766}
2767
Dan Stoza6b9454d2014-11-07 16:00:59 -08002768bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002769{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002770 ALOGV("handlePageFlip");
2771
Brian Andersond6927fb2016-07-23 23:37:30 -07002772 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002773
Mathias Agopian4fec8732012-06-29 14:12:52 -07002774 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002775 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002776 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002777
2778 // Store the set of layers that need updates. This set must not change as
2779 // buffers are being latched, as this could result in a deadlock.
2780 // Example: Two producers share the same command stream and:
2781 // 1.) Layer 0 is latched
2782 // 2.) Layer 0 gets a new frame
2783 // 2.) Layer 1 gets a new frame
2784 // 3.) Layer 1 is latched.
2785 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2786 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002787 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002788 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002789 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07002790 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002791 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002792 } else {
2793 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002794 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002795 } else {
2796 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002797 }
Robert Carr2047fae2016-11-28 14:09:09 -08002798 });
2799
Dan Stoza9e56aa02015-11-02 13:00:03 -08002800 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002801 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002802 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002803 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002804 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002805 newDataLatched = true;
2806 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002807 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002808
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002809 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002810
2811 // If we will need to wake up at some time in the future to deal with a
2812 // queued frame that shouldn't be displayed during this vsync period, wake
2813 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002814 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002815 signalLayerUpdate();
2816 }
2817
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002818 // enter boot animation on first buffer latch
2819 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2820 ALOGI("Enter boot animation");
2821 mBootStage = BootStage::BOOTANIMATION;
2822 }
2823
Dan Stoza6b9454d2014-11-07 16:00:59 -08002824 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002825 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002826}
2827
Mathias Agopianad456f92011-01-13 17:53:01 -08002828void SurfaceFlinger::invalidateHwcGeometry()
2829{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002830 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002831}
2832
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002833void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2834 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002835 // We only need to actually compose the display if:
2836 // 1) It is being handled by hardware composer, which may need this to
2837 // keep its virtual display state machine in sync, or
2838 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002839 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002840 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002841 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002842 return;
2843 }
2844
Dan Stoza9e56aa02015-11-02 13:00:03 -08002845 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002846 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002847
2848 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002849 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002850}
2851
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002852bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002853 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002854
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002855 const Region bounds(display->bounds());
2856 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002857 const auto displayId = display->getId();
2858 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002859 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002860
Chia-I Wu8e50e692018-05-04 10:12:37 -07002861 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002862 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002863
Dan Stoza9e56aa02015-11-02 13:00:03 -08002864 if (hasClientComposition) {
2865 ALOGV("hasClientComposition");
2866
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002867 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002868 if (display->hasWideColorGamut()) {
2869 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002870 }
2871 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002872 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002873 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002874
Dominik Laskowski7e045462018-05-30 13:02:02 -07002875 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002876 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2877 HWC2::Capability::SkipClientColorTransform);
2878
Chia-I Wud49d6692018-06-27 07:17:41 +08002879 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002880 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2881 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08002882 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002883 }
2884
Chia-I Wud49d6692018-06-27 07:17:41 +08002885 // The current enhanced saturation matrix is designed to enhance Display P3,
2886 // thus we only apply this matrix when the render intent is not colorimetric
2887 // and the output color space is Display P3.
2888 needsEnhancedColorMatrix =
2889 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2890 outputDataspace == Dataspace::DISPLAY_P3);
2891 if (needsEnhancedColorMatrix) {
2892 colorMatrix *= mEnhancedSaturationMatrix;
2893 }
2894
2895 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002896
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002897 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002898 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002899 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002900 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002901
2902 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002903 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
2904 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
2905 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07002906 }
2907 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002908 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002909
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002910 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002911 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002912 // when using overlays, we assume a fully transparent framebuffer
2913 // NOTE: we could reduce how much we need to clear, for instance
2914 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002915 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002916 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002917 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002918 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002919 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002920 // we're left with the letterbox region
2921 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002922 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07002923
2924 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002925 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07002926
Mathias Agopianb9494d52012-04-18 02:28:45 -07002927 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002928 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002929 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002930 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002931 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002932 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002933
Yiwei Zhange4e26c02018-08-22 13:59:12 -07002934 const Rect& bounds = display->getBounds();
2935 const Rect& scissor = display->getScissor();
2936 if (scissor != bounds) {
2937 // scissor doesn't match the screen's dimensions, so we
2938 // need to clear everything outside of it and enable
2939 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002940
Yiwei Zhange4e26c02018-08-22 13:59:12 -07002941 // enable scissor for this frame
2942 const uint32_t height = display->getHeight();
2943 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
2944 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002945 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002946 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002947
Mathias Agopian85d751c2012-08-29 16:59:24 -07002948 /*
2949 * and then, render the layers targeted at the framebuffer
2950 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002951
Dan Stoza9e56aa02015-11-02 13:00:03 -08002952 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07002953 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002954 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002955 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002956 const Region clip(bounds.intersect(
2957 displayTransform.transform(layer->visibleRegion)));
2958 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002959 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002960 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002961 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002962 case HWC2::Composition::Cursor:
2963 case HWC2::Composition::Device:
2964 case HWC2::Composition::Sideband:
2965 case HWC2::Composition::SolidColor: {
2966 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002967 if (layer->getClearClientTarget(displayId) && !firstLayer &&
Rajavenu Kyatham2eae6d32018-04-10 12:34:05 +05302968 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
2969 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002970 // never clear the very first layer since we're
2971 // guaranteed the FB is already cleared
2972 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002973 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002974 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002975 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002976 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002977 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002978 break;
2979 }
2980 default:
2981 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002982 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002983 } else {
2984 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002985 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002986 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002987 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002988
Chia-I Wud49d6692018-06-27 07:17:41 +08002989 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07002990 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002991 }
2992
Mathias Agopianf45c5102012-10-24 16:29:17 -07002993 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002994 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002995 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002996}
2997
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002998void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
2999 const Region& region) const {
3000 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003001 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003002 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003003}
3004
Dan Stoza7d89d062015-04-30 13:29:25 -07003005status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003006 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003007 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003008 const sp<Layer>& lbc,
3009 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003010{
Dan Stoza7d89d062015-04-30 13:29:25 -07003011 // add this layer to the current state list
3012 {
3013 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003014 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003015 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3016 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003017 return NO_MEMORY;
3018 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003019 if (parent == nullptr) {
3020 mCurrentState.layersSortedByZ.add(lbc);
3021 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003022 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003023 ALOGE("addClientLayer called with a removed parent");
3024 return NAME_NOT_FOUND;
3025 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003026 parent->addChild(lbc);
3027 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003028
Yiwei Zhang243b3782018-05-15 17:40:04 -07003029 if (gbc != nullptr) {
3030 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3031 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3032 mMaxGraphicBufferProducerListSize,
3033 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3034 mGraphicBufferProducerList.size(),
3035 mMaxGraphicBufferProducerListSize, mNumLayers);
3036 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003037 mLayersAdded = true;
3038 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003039 }
3040
Mathias Agopian96f08192010-06-02 23:28:45 -07003041 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003042 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003043
Dan Stoza7d89d062015-04-30 13:29:25 -07003044 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003045}
3046
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003047status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003048 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003049 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3050}
Robert Carr7f9b8992017-03-10 11:08:39 -08003051
chaviwca27f252018-02-06 16:46:39 -08003052status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3053 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003054 if (layer->isPendingRemoval()) {
3055 return NO_ERROR;
3056 }
3057
Robert Carr1f0a16a2016-10-24 16:27:39 -07003058 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003059 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003060 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003061 if (topLevelOnly) {
3062 return NO_ERROR;
3063 }
3064
Chia-I Wu98f1c102017-05-30 14:54:08 -07003065 sp<Layer> ancestor = p;
3066 while (ancestor->getParent() != nullptr) {
3067 ancestor = ancestor->getParent();
3068 }
3069 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3070 ALOGE("removeLayer called with a layer whose parent has been removed");
3071 return NAME_NOT_FOUND;
3072 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003073
3074 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003075 } else {
3076 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003077 }
3078
Robert Carr136e2f62017-02-08 17:54:29 -08003079 // As a matter of normal operation, the LayerCleaner will produce a second
3080 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3081 // so we will succeed in promoting it, but it's already been removed
3082 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3083 // otherwise something has gone wrong and we are leaking the layer.
3084 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003085 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3086 layer->getName().string(),
3087 (p != nullptr) ? p->getName().string() : "no-parent");
3088 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003089 } else if (index < 0) {
3090 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003091 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003092
Chia-I Wuc6657022017-08-15 11:18:17 -07003093 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003094 mLayersPendingRemoval.add(layer);
3095 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003096 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003097 setTransactionFlags(eTransactionNeeded);
3098 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003099}
3100
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003101uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003102 return android_atomic_release_load(&mTransactionFlags);
3103}
3104
Mathias Agopian3f844832013-08-07 21:24:32 -07003105uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003106 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3107}
3108
Mathias Agopian3f844832013-08-07 21:24:32 -07003109uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003110 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3111}
3112
3113uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3114 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003115 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003116 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003117 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003118 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003119 }
3120 return old;
3121}
3122
chaviwca27f252018-02-06 16:46:39 -08003123bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3124 for (const ComposerState& state : states) {
3125 // Here we need to check that the interface we're given is indeed
3126 // one of our own. A malicious client could give us a nullptr
3127 // IInterface, or one of its own or even one of our own but a
3128 // different type. All these situations would cause us to crash.
3129 if (state.client == nullptr) {
3130 return true;
3131 }
3132
3133 sp<IBinder> binder = IInterface::asBinder(state.client);
3134 if (binder == nullptr) {
3135 return true;
3136 }
3137
3138 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3139 return true;
3140 }
3141 }
3142 return false;
3143}
3144
Mathias Agopian8b33f032012-07-24 20:43:54 -07003145void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003146 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003147 const Vector<DisplayState>& displays,
3148 uint32_t flags)
3149{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003150 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003151 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003152 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003153
chaviwca27f252018-02-06 16:46:39 -08003154 if (containsAnyInvalidClientState(states)) {
3155 return;
3156 }
3157
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003158 if (flags & eAnimation) {
3159 // For window updates that are part of an animation we must wait for
3160 // previous animation "frames" to be handled.
3161 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003162 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003163 if (CC_UNLIKELY(err != NO_ERROR)) {
3164 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003165 // caller after a few seconds.
3166 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3167 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003168 mAnimTransactionPending = false;
3169 break;
3170 }
3171 }
3172 }
3173
chaviwca27f252018-02-06 16:46:39 -08003174 for (const DisplayState& display : displays) {
3175 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003176 }
3177
chaviwca27f252018-02-06 16:46:39 -08003178 for (const ComposerState& state : states) {
3179 transactionFlags |= setClientStateLocked(state);
3180 }
3181
3182 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3183 // as destroyed should only occur after setting all other states. This is to allow for a
3184 // child re-parent to happen before marking its original parent as destroyed (which would
3185 // then mark the child as destroyed).
3186 for (const ComposerState& state : states) {
3187 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003188 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003189
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003190 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3191 // anyway. This can be used as a flush mechanism for previous async transactions.
3192 // Empty animation transaction can be used to simulate back-pressure, so also force a
3193 // transaction for empty animation transactions.
3194 if (transactionFlags == 0 &&
3195 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003196 transactionFlags = eTransactionNeeded;
3197 }
3198
Mathias Agopian386aa982011-11-07 21:58:03 -08003199 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003200 if (mInterceptor->isEnabled()) {
3201 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003202 }
Irvel468051e2016-06-13 16:44:44 -07003203
Mathias Agopian386aa982011-11-07 21:58:03 -08003204 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003205 const auto start = (flags & eEarlyWakeup)
3206 ? VSyncModulator::TransactionStart::EARLY
3207 : VSyncModulator::TransactionStart::NORMAL;
3208 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003209
3210 // if this is a synchronous transaction, wait for it to take effect
3211 // before returning.
3212 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003213 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003214 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003215 if (flags & eAnimation) {
3216 mAnimTransactionPending = true;
3217 }
3218 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003219 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3220 if (CC_UNLIKELY(err != NO_ERROR)) {
3221 // just in case something goes wrong in SF, return to the
3222 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003223 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3224 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003225 break;
3226 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003227 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003228 }
3229}
3230
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003231uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3232 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3233 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003234
Mathias Agopiane57f2922012-08-09 16:29:12 -07003235 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003236 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3237
3238 const uint32_t what = s.what;
3239 if (what & DisplayState::eSurfaceChanged) {
3240 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3241 state.surface = s.surface;
3242 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003243 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003244 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003245 if (what & DisplayState::eLayerStackChanged) {
3246 if (state.layerStack != s.layerStack) {
3247 state.layerStack = s.layerStack;
3248 flags |= eDisplayTransactionNeeded;
3249 }
3250 }
3251 if (what & DisplayState::eDisplayProjectionChanged) {
3252 if (state.orientation != s.orientation) {
3253 state.orientation = s.orientation;
3254 flags |= eDisplayTransactionNeeded;
3255 }
3256 if (state.frame != s.frame) {
3257 state.frame = s.frame;
3258 flags |= eDisplayTransactionNeeded;
3259 }
3260 if (state.viewport != s.viewport) {
3261 state.viewport = s.viewport;
3262 flags |= eDisplayTransactionNeeded;
3263 }
3264 }
3265 if (what & DisplayState::eDisplaySizeChanged) {
3266 if (state.width != s.width) {
3267 state.width = s.width;
3268 flags |= eDisplayTransactionNeeded;
3269 }
3270 if (state.height != s.height) {
3271 state.height = s.height;
3272 flags |= eDisplayTransactionNeeded;
3273 }
3274 }
3275
Mathias Agopiane57f2922012-08-09 16:29:12 -07003276 return flags;
3277}
3278
Robert Carrd4ae7f32018-06-07 16:10:57 -07003279bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3280 IPCThreadState* ipc = IPCThreadState::self();
3281 const int pid = ipc->getCallingPid();
3282 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003283 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003284 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003285 return false;
3286 }
3287 return true;
3288}
3289
chaviwca27f252018-02-06 16:46:39 -08003290uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3291 const layer_state_t& s = composerState.state;
3292 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3293
Mathias Agopian13127d82013-03-05 17:47:11 -08003294 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003295 if (layer == nullptr) {
3296 return 0;
3297 }
3298
3299 if (layer->isPendingRemoval()) {
3300 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3301 return 0;
3302 }
3303
3304 uint32_t flags = 0;
3305
3306 const uint32_t what = s.what;
3307 bool geometryAppliesWithResize =
3308 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003309
3310 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3311 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003312 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003313 layer->pushPendingState();
3314 }
3315
chaviw8b3871a2017-11-01 17:41:01 -07003316 if (what & layer_state_t::ePositionChanged) {
3317 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3318 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003319 }
chaviw8b3871a2017-11-01 17:41:01 -07003320 }
3321 if (what & layer_state_t::eLayerChanged) {
3322 // NOTE: index needs to be calculated before we update the state
3323 const auto& p = layer->getParent();
3324 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003325 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003326 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003327 mCurrentState.layersSortedByZ.removeAt(idx);
3328 mCurrentState.layersSortedByZ.add(layer);
3329 // we need traversal (state changed)
3330 // AND transaction (list changed)
3331 flags |= eTransactionNeeded|eTraversalNeeded;
3332 }
chaviw8b3871a2017-11-01 17:41:01 -07003333 } else {
3334 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003335 flags |= eTransactionNeeded|eTraversalNeeded;
3336 }
3337 }
chaviw8b3871a2017-11-01 17:41:01 -07003338 }
3339 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003340 // NOTE: index needs to be calculated before we update the state
3341 const auto& p = layer->getParent();
3342 if (p == nullptr) {
3343 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3344 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3345 mCurrentState.layersSortedByZ.removeAt(idx);
3346 mCurrentState.layersSortedByZ.add(layer);
3347 // we need traversal (state changed)
3348 // AND transaction (list changed)
3349 flags |= eTransactionNeeded|eTraversalNeeded;
3350 }
3351 } else {
3352 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3353 flags |= eTransactionNeeded|eTraversalNeeded;
3354 }
chaviw8b3871a2017-11-01 17:41:01 -07003355 }
3356 }
3357 if (what & layer_state_t::eSizeChanged) {
3358 if (layer->setSize(s.w, s.h)) {
3359 flags |= eTraversalNeeded;
3360 }
3361 }
3362 if (what & layer_state_t::eAlphaChanged) {
3363 if (layer->setAlpha(s.alpha))
3364 flags |= eTraversalNeeded;
3365 }
3366 if (what & layer_state_t::eColorChanged) {
3367 if (layer->setColor(s.color))
3368 flags |= eTraversalNeeded;
3369 }
3370 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003371 // TODO: b/109894387
3372 //
3373 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3374 // rotation. To see the problem observe that if we have a square parent, and a child
3375 // of the same size, then we rotate the child 45 degrees around it's center, the child
3376 // must now be cropped to a non rectangular 8 sided region.
3377 //
3378 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3379 // private API, and the WindowManager only uses rotation in one case, which is on a top
3380 // level layer in which cropping is not an issue.
3381 //
3382 // However given that abuse of rotation matrices could lead to surfaces extending outside
3383 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3384 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3385 // transformations.
3386 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003387 flags |= eTraversalNeeded;
3388 }
3389 if (what & layer_state_t::eTransparentRegionChanged) {
3390 if (layer->setTransparentRegionHint(s.transparentRegion))
3391 flags |= eTraversalNeeded;
3392 }
3393 if (what & layer_state_t::eFlagsChanged) {
3394 if (layer->setFlags(s.flags, s.mask))
3395 flags |= eTraversalNeeded;
3396 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003397 if (what & layer_state_t::eCropChanged_legacy) {
3398 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003399 flags |= eTraversalNeeded;
3400 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003401 if (what & layer_state_t::eFinalCropChanged_legacy) {
3402 if (layer->setFinalCrop_legacy(s.finalCrop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003403 flags |= eTraversalNeeded;
3404 }
3405 if (what & layer_state_t::eLayerStackChanged) {
3406 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3407 // We only allow setting layer stacks for top level layers,
3408 // everything else inherits layer stack from its parent.
3409 if (layer->hasParent()) {
3410 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3411 layer->getName().string());
3412 } else if (idx < 0) {
3413 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3414 "that also does not appear in the top level layer list. Something"
3415 " has gone wrong.", layer->getName().string());
3416 } else if (layer->setLayerStack(s.layerStack)) {
3417 mCurrentState.layersSortedByZ.removeAt(idx);
3418 mCurrentState.layersSortedByZ.add(layer);
3419 // we need traversal (state changed)
3420 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003421 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003422 }
3423 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003424 if (what & layer_state_t::eDeferTransaction_legacy) {
3425 if (s.barrierHandle_legacy != nullptr) {
3426 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3427 } else if (s.barrierGbp_legacy != nullptr) {
3428 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003429 if (authenticateSurfaceTextureLocked(gbp)) {
3430 const auto& otherLayer =
3431 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003432 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003433 } else {
3434 ALOGE("Attempt to defer transaction to to an"
3435 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003436 }
3437 }
chaviw8b3871a2017-11-01 17:41:01 -07003438 // We don't trigger a traversal here because if no other state is
3439 // changed, we don't want this to cause any more work
3440 }
3441 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003442 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003443 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003444 if (!hadParent) {
3445 mCurrentState.layersSortedByZ.remove(layer);
3446 }
chaviw8b3871a2017-11-01 17:41:01 -07003447 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003448 }
chaviw8b3871a2017-11-01 17:41:01 -07003449 }
3450 if (what & layer_state_t::eReparentChildren) {
3451 if (layer->reparentChildren(s.reparentHandle)) {
3452 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003453 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003454 }
chaviw8b3871a2017-11-01 17:41:01 -07003455 if (what & layer_state_t::eDetachChildren) {
3456 layer->detachChildren();
3457 }
3458 if (what & layer_state_t::eOverrideScalingModeChanged) {
3459 layer->setOverrideScalingMode(s.overrideScalingMode);
3460 // We don't trigger a traversal here because if no other state is
3461 // changed, we don't want this to cause any more work
3462 }
Marissa Wall61c58622018-07-18 10:12:20 -07003463 if (what & layer_state_t::eTransformChanged) {
3464 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3465 }
3466 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3467 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3468 flags |= eTraversalNeeded;
3469 }
3470 if (what & layer_state_t::eCropChanged) {
3471 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3472 }
3473 if (what & layer_state_t::eBufferChanged) {
3474 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3475 }
3476 if (what & layer_state_t::eAcquireFenceChanged) {
3477 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3478 }
3479 if (what & layer_state_t::eDataspaceChanged) {
3480 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3481 }
3482 if (what & layer_state_t::eHdrMetadataChanged) {
3483 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3484 }
3485 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3486 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3487 }
3488 if (what & layer_state_t::eApiChanged) {
3489 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3490 }
3491 if (what & layer_state_t::eSidebandStreamChanged) {
3492 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3493 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003494 return flags;
3495}
3496
chaviwca27f252018-02-06 16:46:39 -08003497void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3498 const layer_state_t& state = composerState.state;
3499 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3500
3501 sp<Layer> layer(client->getLayerUser(state.surface));
3502 if (layer == nullptr) {
3503 return;
3504 }
3505
3506 if (layer->isPendingRemoval()) {
3507 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3508 return;
3509 }
3510
3511 if (state.what & layer_state_t::eDestroySurface) {
3512 removeLayerLocked(mStateLock, layer);
3513 }
3514}
3515
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003516status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003517 const String8& name,
3518 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003519 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003520 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003521 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003522{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003523 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003524 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003525 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003526 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003527 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003528
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003529 status_t result = NO_ERROR;
3530
3531 sp<Layer> layer;
3532
Cody Northropbc755282017-03-31 12:00:08 -06003533 String8 uniqueName = getUniqueLayerName(name);
3534
Mathias Agopian3165cc22012-08-08 19:42:09 -07003535 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003536 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003537 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3538 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003539
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003540 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003541 case ISurfaceComposerClient::eFXSurfaceBufferState:
3542 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3543 break;
chaviw13fdc492017-06-27 12:40:18 -07003544 case ISurfaceComposerClient::eFXSurfaceColor:
3545 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003546 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003547 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003548 break;
3549 default:
3550 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003551 break;
3552 }
3553
Dan Stoza7d89d062015-04-30 13:29:25 -07003554 if (result != NO_ERROR) {
3555 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003556 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003557
Chia-I Wuab0c3192017-08-01 11:29:00 -07003558 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3559 // TODO b/64227542
3560 if (windowType == 441731) {
3561 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3562 layer->setPrimaryDisplayOnly();
3563 }
3564
Albert Chaulk479c60c2017-01-27 14:21:34 -05003565 layer->setInfo(windowType, ownerUid);
3566
Robert Carr1f0a16a2016-10-24 16:27:39 -07003567 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003568 if (result != NO_ERROR) {
3569 return result;
3570 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003571 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003572
3573 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003574 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003575}
3576
Cody Northropbc755282017-03-31 12:00:08 -06003577String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3578{
3579 bool matchFound = true;
3580 uint32_t dupeCounter = 0;
3581
3582 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3583 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3584
Dan Stoza436ccf32018-06-21 12:10:12 -07003585 // Grab the state lock since we're accessing mCurrentState
3586 Mutex::Autolock lock(mStateLock);
3587
Cody Northropbc755282017-03-31 12:00:08 -06003588 // Loop over layers until we're sure there is no matching name
3589 while (matchFound) {
3590 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003591 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003592 if (layer->getName() == uniqueName) {
3593 matchFound = true;
3594 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3595 }
3596 });
3597 }
3598
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003599 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3600 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003601
3602 return uniqueName;
3603}
3604
Marissa Wallfd668622018-05-10 10:21:13 -07003605status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3606 uint32_t w, uint32_t h, uint32_t flags,
3607 PixelFormat& format, sp<IBinder>* handle,
3608 sp<IGraphicBufferProducer>* gbp,
3609 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003610 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003611 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003612 case PIXEL_FORMAT_TRANSPARENT:
3613 case PIXEL_FORMAT_TRANSLUCENT:
3614 format = PIXEL_FORMAT_RGBA_8888;
3615 break;
3616 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003617 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003618 break;
3619 }
3620
Marissa Wallfd668622018-05-10 10:21:13 -07003621 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3622 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003623 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003624 *handle = layer->getHandle();
3625 *gbp = layer->getProducer();
3626 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003627 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003628
Marissa Wallfd668622018-05-10 10:21:13 -07003629 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003630 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003631}
3632
Marissa Wall61c58622018-07-18 10:12:20 -07003633status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3634 uint32_t w, uint32_t h, uint32_t flags,
3635 sp<IBinder>* handle, sp<Layer>* outLayer) {
3636 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3637 *handle = layer->getHandle();
3638 *outLayer = layer;
3639
3640 return NO_ERROR;
3641}
3642
chaviw13fdc492017-06-27 12:40:18 -07003643status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003644 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003645 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003646{
chaviw13fdc492017-06-27 12:40:18 -07003647 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003648 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003649 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003650}
3651
Mathias Agopianac9fa422013-02-11 16:40:36 -08003652status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003653{
Robert Carr9524cb32017-02-13 11:32:32 -08003654 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003655 status_t err = NO_ERROR;
3656 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003657 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003658 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003659 err = removeLayer(l);
3660 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3661 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003662 }
3663 return err;
3664}
3665
Mathias Agopian13127d82013-03-05 17:47:11 -08003666status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003667{
Mathias Agopian67106042013-03-14 19:18:13 -07003668 // called by ~LayerCleaner() when all references to the IBinder (handle)
3669 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003670 sp<Layer> l = layer.promote();
3671 if (l == nullptr) {
3672 // The layer has already been removed, carry on
3673 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003674 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003675 // If we have a parent, then we can continue to live as long as it does.
3676 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003677}
3678
Mathias Agopianb60314a2012-04-10 22:09:54 -07003679// ---------------------------------------------------------------------------
3680
Andy McFadden13a082e2012-08-24 10:16:42 -07003681void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003682 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3683 if (!displayToken) return;
3684
Jesse Hall01e29052013-02-19 16:13:35 -08003685 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003686 Vector<ComposerState> state;
3687 Vector<DisplayState> displays;
3688 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003689 d.what = DisplayState::eDisplayProjectionChanged |
3690 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003691 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003692 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003693 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003694 d.frame.makeInvalid();
3695 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003696 d.width = 0;
3697 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003698 displays.add(d);
3699 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003700
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003701 const auto display = getDisplayDevice(displayToken);
3702 if (!display) return;
3703
3704 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3705
3706 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003707 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003708 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003709
Brian Andersond0010582017-03-07 13:20:31 -08003710 // Use phase of 0 since phase is not known.
3711 // Use latency of 0, which will snap to the ideal latency.
3712 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003713}
3714
3715void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003716 // Async since we may be called from the main thread.
3717 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003718}
3719
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003720void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3721 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003722 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003723 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003724
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003725 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003726 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003727 return;
3728 }
3729
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003730 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003731 ALOGW("Trying to set power mode for virtual display");
3732 return;
3733 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003734
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003735 display->setPowerMode(mode);
3736
Lloyd Pique4dccc412018-01-22 17:21:36 -08003737 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003738 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003739 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003740 if (idx < 0) {
3741 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3742 return;
3743 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003744 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003745 }
3746
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003747 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003748 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003749 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003750 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003751 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003752 // FIXME: eventthread only knows about the main display right now
3753 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003754 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003755 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003756
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003757 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003758 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003759 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003760
3761 struct sched_param param = {0};
3762 param.sched_priority = 1;
3763 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3764 ALOGW("Couldn't set SCHED_FIFO on display on");
3765 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003766 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003767 // Turn off the display
3768 struct sched_param param = {0};
3769 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3770 ALOGW("Couldn't set SCHED_OTHER on display off");
3771 }
3772
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003773 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003774 disableHardwareVsync(true); // also cancels any in-progress resync
3775
Mathias Agopiancde87a32012-09-13 14:09:01 -07003776 // FIXME: eventthread only knows about the main display right now
3777 mEventThread->onScreenReleased();
3778 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003779
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003780 getHwComposer().setPowerMode(type, mode);
3781 mVisibleRegionsDirty = true;
3782 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003783 } else if (mode == HWC_POWER_MODE_DOZE ||
3784 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003785 // Update display while dozing
3786 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003787 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003788 // FIXME: eventthread only knows about the main display right now
3789 mEventThread->onScreenAcquired();
3790 resyncToHardwareVsync(true);
3791 }
3792 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3793 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003794 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003795 disableHardwareVsync(true); // also cancels any in-progress resync
3796 // FIXME: eventthread only knows about the main display right now
3797 mEventThread->onScreenReleased();
3798 }
3799 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003800 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003801 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003802 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003803 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003804
3805 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003806}
3807
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003808void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003809 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003810 const auto display = getDisplayDevice(displayToken);
3811 if (!display) {
3812 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3813 displayToken.get());
3814 } else if (display->isVirtual()) {
3815 ALOGW("Attempt to set power mode %d for virtual display", mode);
3816 } else {
3817 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003818 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003819 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003820}
3821
3822// ---------------------------------------------------------------------------
3823
Lloyd Pique755e3192018-01-31 16:46:15 -08003824status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3825 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003826 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003827
Mathias Agopianbd115332013-04-18 16:41:04 -07003828 IPCThreadState* ipc = IPCThreadState::self();
3829 const int pid = ipc->getCallingPid();
3830 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003831
Mathias Agopianbd115332013-04-18 16:41:04 -07003832 if ((uid != AID_SHELL) &&
3833 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003834 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003835 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003836 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003837 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003838 // (this would indicate SF is stuck, but we want to be able to
3839 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003840 status_t err = mStateLock.timedLock(s2ns(1));
3841 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003842 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003843 result.appendFormat(
3844 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3845 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003846 }
3847
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003848 bool dumpAll = true;
3849 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003850 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003851
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003852 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003853 if ((index < numArgs) &&
3854 (args[index] == String16("--list"))) {
3855 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003856 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003857 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003858 }
3859
3860 if ((index < numArgs) &&
3861 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003862 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003863 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003864 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003865 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003866
3867 if ((index < numArgs) &&
3868 (args[index] == String16("--latency-clear"))) {
3869 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003870 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003871 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003872 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003873
3874 if ((index < numArgs) &&
3875 (args[index] == String16("--dispsync"))) {
3876 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07003877 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07003878 dumpAll = false;
3879 }
Dan Stozab90cf072015-03-05 11:05:59 -08003880
3881 if ((index < numArgs) &&
3882 (args[index] == String16("--static-screen"))) {
3883 index++;
3884 dumpStaticScreenStats(result);
3885 dumpAll = false;
3886 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003887
3888 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003889 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003890 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003891 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003892 dumpAll = false;
3893 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003894
3895 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3896 index++;
3897 dumpWideColorInfo(result);
3898 dumpAll = false;
3899 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003900
3901 if ((index < numArgs) &&
3902 (args[index] == String16("--enable-layer-stats"))) {
3903 index++;
3904 mLayerStats.enable();
3905 dumpAll = false;
3906 }
3907
3908 if ((index < numArgs) &&
3909 (args[index] == String16("--disable-layer-stats"))) {
3910 index++;
3911 mLayerStats.disable();
3912 dumpAll = false;
3913 }
3914
3915 if ((index < numArgs) &&
3916 (args[index] == String16("--clear-layer-stats"))) {
3917 index++;
3918 mLayerStats.clear();
3919 dumpAll = false;
3920 }
3921
3922 if ((index < numArgs) &&
3923 (args[index] == String16("--dump-layer-stats"))) {
3924 index++;
3925 mLayerStats.dump(result);
3926 dumpAll = false;
3927 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003928
3929 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08003930 (args[index] == String16("--frame-composition"))) {
3931 index++;
3932 dumpFrameCompositionInfo(result);
3933 dumpAll = false;
3934 }
3935
3936 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003937 (args[index] == String16("--display-identification"))) {
3938 index++;
3939 dumpDisplayIdentificationData(result);
3940 dumpAll = false;
3941 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003942
3943 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3944 index++;
3945 mTimeStats.parseArgs(asProto, args, index, result);
3946 dumpAll = false;
3947 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003948 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003949
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003950 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003951 if (asProto) {
3952 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3953 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3954 } else {
3955 dumpAllLocked(args, index, result);
3956 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003957 }
3958
Mathias Agopian9795c422009-08-26 16:36:26 -07003959 if (locked) {
3960 mStateLock.unlock();
3961 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003962 }
3963 write(fd, result.string(), result.size());
3964 return NO_ERROR;
3965}
3966
Dan Stozac7014012014-02-14 15:03:43 -08003967void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3968 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003969{
Robert Carr2047fae2016-11-28 14:09:09 -08003970 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003971 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003972 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003973}
3974
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003975void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003976 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003977{
3978 String8 name;
3979 if (index < args.size()) {
3980 name = String8(args[index]);
3981 index++;
3982 }
3983
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003984 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
3985 getHwComposer().isConnected(displayId)) {
3986 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
3987 const nsecs_t period = activeConfig->getVsyncPeriod();
3988 result.appendFormat("%" PRId64 "\n", period);
3989 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003990
3991 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003992 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003993 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003994 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003995 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003996 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003997 }
Robert Carr2047fae2016-11-28 14:09:09 -08003998 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003999 }
4000}
4001
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004002void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004003 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004004{
4005 String8 name;
4006 if (index < args.size()) {
4007 name = String8(args[index]);
4008 index++;
4009 }
4010
Robert Carr2047fae2016-11-28 14:09:09 -08004011 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004012 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004013 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004014 }
Robert Carr2047fae2016-11-28 14:09:09 -08004015 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004016
Svetoslavd85084b2014-03-20 10:28:31 -07004017 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004018}
4019
Jamie Gennis6547ff42013-07-16 20:12:42 -07004020// This should only be called from the main thread. Otherwise it would need
4021// the lock and should use mCurrentState rather than mDrawingState.
4022void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004023 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004024 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004025 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004026
4027 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4028}
4029
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004030void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004031{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004032 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004033
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004034 if (isLayerTripleBufferingDisabled())
4035 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004036
4037 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004038 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004039 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004040 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004041 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4042 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004043 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004044}
4045
Dan Stozab90cf072015-03-05 11:05:59 -08004046void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4047{
4048 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004049 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4050 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004051 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004052 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004053 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4054 b + 1, bucketTimeSec, percent);
4055 }
David Sodman4a36e932017-11-07 14:29:47 -08004056 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004057 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004058 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004059 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004060 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004061}
4062
Dan Stozae77c7662016-05-13 11:37:28 -07004063void SurfaceFlinger::recordBufferingStats(const char* layerName,
4064 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004065 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4066 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004067 for (const auto& segment : history) {
4068 if (!segment.usedThirdBuffer) {
4069 stats.twoBufferTime += segment.totalTime;
4070 }
4071 if (segment.occupancyAverage < 1.0f) {
4072 stats.doubleBufferedTime += segment.totalTime;
4073 } else if (segment.occupancyAverage < 2.0f) {
4074 stats.tripleBufferedTime += segment.totalTime;
4075 }
4076 ++stats.numSegments;
4077 stats.totalTime += segment.totalTime;
4078 }
4079}
4080
Brian Andersond6927fb2016-07-23 23:37:30 -07004081void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4082 result.appendFormat("Layer frame timestamps:\n");
4083
4084 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4085 const size_t count = currentLayers.size();
4086 for (size_t i=0 ; i<count ; i++) {
4087 currentLayers[i]->dumpFrameEvents(result);
4088 }
4089}
4090
Dan Stozae77c7662016-05-13 11:37:28 -07004091void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4092 result.append("Buffering stats:\n");
4093 result.append(" [Layer name] <Active time> <Two buffer> "
4094 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004095 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004096 typedef std::tuple<std::string, float, float, float> BufferTuple;
4097 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004098 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004099 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004100 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004101 if (stats.numSegments == 0) {
4102 continue;
4103 }
4104 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4105 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4106 stats.totalTime;
4107 float doubleBufferRatio = static_cast<float>(
4108 stats.doubleBufferedTime) / stats.totalTime;
4109 float tripleBufferRatio = static_cast<float>(
4110 stats.tripleBufferedTime) / stats.totalTime;
4111 sorted.insert({activeTime, {name, twoBufferRatio,
4112 doubleBufferRatio, tripleBufferRatio}});
4113 }
4114 for (const auto& sortedPair : sorted) {
4115 float activeTime = sortedPair.first;
4116 const BufferTuple& values = sortedPair.second;
4117 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4118 std::get<0>(values).c_str(), activeTime,
4119 std::get<1>(values), std::get<2>(values),
4120 std::get<3>(values));
4121 }
4122 result.append("\n");
4123}
4124
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004125void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004126 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004127 const int32_t displayId = display->getId();
4128 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4129 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004130 continue;
4131 }
4132
Dominik Laskowski7e045462018-05-30 13:02:02 -07004133 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004134 uint8_t port;
4135 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004136 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004137 result.append("no identification data\n");
4138 continue;
4139 }
4140
4141 if (!isEdid(data)) {
4142 result.append("unknown identification data: ");
4143 for (uint8_t byte : data) {
4144 result.appendFormat("%x ", byte);
4145 }
4146 result.append("\n");
4147 continue;
4148 }
4149
4150 const auto edid = parseEdid(data);
4151 if (!edid) {
4152 result.append("invalid EDID: ");
4153 for (uint8_t byte : data) {
4154 result.appendFormat("%x ", byte);
4155 }
4156 result.append("\n");
4157 continue;
4158 }
4159
4160 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4161 result.append(edid->displayName.data(), edid->displayName.length());
4162 result.append("\"\n");
4163 }
4164 result.append("\n");
4165}
4166
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004167void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004168 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4169 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004170 result.appendFormat("DisplayColorSetting: %s\n",
4171 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004172
4173 // TODO: print out if wide-color mode is active or not
4174
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004175 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004176 const int32_t displayId = display->getId();
4177 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004178 continue;
4179 }
4180
Dominik Laskowski7e045462018-05-30 13:02:02 -07004181 result.appendFormat("Display %d color modes:\n", displayId);
4182 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004183 for (auto&& mode : modes) {
4184 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4185 }
4186
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004187 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004188 result.appendFormat(" Current color mode: %s (%d)\n",
4189 decodeColorMode(currentMode).c_str(), currentMode);
4190 }
4191 result.append("\n");
4192}
4193
David Sodman7e4ae112018-02-09 15:02:28 -08004194void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4195 std::string stringResult;
4196
4197 for (const auto& [token, display] : mDisplays) {
4198 const auto displayId = display->getId();
4199 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
4200 continue;
4201 }
4202
4203 const auto& compositionInfoIt = getBE().mEndOfFrameCompositionInfo.find(displayId);
4204 if (compositionInfoIt == getBE().mEndOfFrameCompositionInfo.end()) {
4205 break;
4206 }
4207 const auto& compositionInfoList = compositionInfoIt->second;
4208 stringResult += base::StringPrintf("Display: %d\n", displayId);
4209 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4210 for (const auto& compositionInfo : compositionInfoList) {
4211 compositionInfo.dump(stringResult, nullptr);
4212 stringResult += base::StringPrintf("\n");
4213 }
4214 }
4215
4216 result.append(stringResult.c_str());
4217}
4218
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004219LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004220 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004221 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4222 const State& state = useDrawing ? mDrawingState : mCurrentState;
4223 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004224 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004225 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004226 });
4227
4228 return layersProto;
4229}
4230
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004231LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004232 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004233
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004234 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004235 resolution->set_w(display.getWidth());
4236 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004237
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004238 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4239 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4240 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004241
Dominik Laskowski7e045462018-05-30 13:02:02 -07004242 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004243 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004244 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004245 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004246 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004247 }
4248 });
4249
4250 return layersProto;
4251}
4252
Mathias Agopian74d211a2013-04-22 16:55:35 +02004253void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4254 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004255{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004256 bool colorize = false;
4257 if (index < args.size()
4258 && (args[index] == String16("--color"))) {
4259 colorize = true;
4260 index++;
4261 }
4262
4263 Colorizer colorizer(colorize);
4264
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004265 // figure out if we're stuck somewhere
4266 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004267 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004268 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4269
4270 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004271 * Dump library configuration.
4272 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004273
4274 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004275 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004276 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004277 appendSfConfigString(result);
4278 appendUiConfigString(result);
4279 appendGuiConfigString(result);
4280 result.append("\n");
4281
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004282 result.append("\nDisplay identification data:\n");
4283 dumpDisplayIdentificationData(result);
4284
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004285 result.append("\nWide-Color information:\n");
4286 dumpWideColorInfo(result);
4287
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004288 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004289 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004290 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004291 result.append(SyncFeatures::getInstance().toString());
4292 result.append("\n");
4293
Andy McFadden41d67d72014-04-25 16:58:34 -07004294 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004295 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004296 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004297
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004298 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4299 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004300 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4301 getHwComposer().isConnected(displayId)) {
4302 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004303 result.appendFormat("Display %d: "
4304 "app phase %" PRId64 " ns, "
4305 "sf phase %" PRId64 " ns, "
4306 "early app phase %" PRId64 " ns, "
4307 "early sf phase %" PRId64 " ns, "
4308 "early app gl phase %" PRId64 " ns, "
4309 "early sf gl phase %" PRId64 " ns, "
4310 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4311 displayId,
4312 vsyncPhaseOffsetNs,
4313 sfVsyncPhaseOffsetNs,
4314 appEarlyOffset,
4315 sfEarlyOffset,
4316 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004317 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004318 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004319 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004320 result.append("\n");
4321
Dan Stozab90cf072015-03-05 11:05:59 -08004322 // Dump static screen stats
4323 result.append("\n");
4324 dumpStaticScreenStats(result);
4325 result.append("\n");
4326
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004327 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4328
Dan Stozae77c7662016-05-13 11:37:28 -07004329 dumpBufferingStats(result);
4330
Andy McFadden4803b742012-09-24 19:07:20 -07004331 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004332 * Dump the visible layer list
4333 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004334 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004335 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004336 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4337 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004338 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004339
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004340 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004341 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004342 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004343 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004344
David Sodman7e4ae112018-02-09 15:02:28 -08004345 result.append("\nFrame-Composition information:\n");
4346 dumpFrameCompositionInfo(result);
4347 result.append("\n");
4348
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004349 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004350 * Dump Display state
4351 */
4352
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004353 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004354 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004355 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004356 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004357 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004358 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004359 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004360
4361 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004362 * Dump SurfaceFlinger global state
4363 */
4364
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004365 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004366 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004367 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004368
Mathias Agopian888c8222012-08-04 21:10:38 -07004369 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004370 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004371
David Sodmanbc815282017-11-05 18:57:52 -08004372 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004373
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004374 if (display) {
4375 display->undefinedRegion.dump(result, "undefinedRegion");
4376 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4377 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004378 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004379 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004380 " gpu_to_cpu_unsupported : %d\n",
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004381 mTransactionFlags, !mGpuToCpuSupported);
4382
4383 if (display) {
4384 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4385 result.appendFormat(" refresh-rate : %f fps\n"
4386 " x-dpi : %f\n"
4387 " y-dpi : %f\n",
4388 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4389 activeConfig->getDpiY());
4390 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004391
Mathias Agopian74d211a2013-04-22 16:55:35 +02004392 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004393 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004394
4395 /*
4396 * VSYNC state
4397 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004398 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004399 result.append("\n");
4400
4401 /*
4402 * HWC layer minidump
4403 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004404 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004405 const int32_t displayId = display->getId();
4406 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004407 continue;
4408 }
4409
Dominik Laskowski7e045462018-05-30 13:02:02 -07004410 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004411 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004412 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004413 result.append("\n");
4414 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004415
4416 /*
4417 * Dump HWComposer state
4418 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004419 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004420 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004421 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004422 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004423 result.appendFormat(" h/w composer %s\n",
4424 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004425 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004426
4427 /*
4428 * Dump gralloc state
4429 */
4430 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4431 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004432
4433 /*
4434 * Dump VrFlinger state if in use.
4435 */
4436 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4437 result.append("VrFlinger state:\n");
4438 result.append(mVrFlinger->Dump().c_str());
4439 result.append("\n");
4440 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004441}
4442
Dominik Laskowski7e045462018-05-30 13:02:02 -07004443const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004444 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004445 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004446 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004447 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004448 }
4449 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004450
4451 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4452 static const Vector<sp<Layer>> empty;
4453 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004454}
4455
Keun young Park63f165f2012-08-31 10:53:36 -07004456bool SurfaceFlinger::startDdmConnection()
4457{
4458 void* libddmconnection_dso =
4459 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4460 if (!libddmconnection_dso) {
4461 return false;
4462 }
4463 void (*DdmConnection_start)(const char* name);
4464 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004465 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004466 if (!DdmConnection_start) {
4467 dlclose(libddmconnection_dso);
4468 return false;
4469 }
4470 (*DdmConnection_start)(getServiceName());
4471 return true;
4472}
4473
Chia-I Wu28f320b2018-05-03 11:02:56 -07004474void SurfaceFlinger::updateColorMatrixLocked() {
4475 mat4 colorMatrix;
4476 if (mGlobalSaturationFactor != 1.0f) {
4477 // Rec.709 luma coefficients
4478 float3 luminance{0.213f, 0.715f, 0.072f};
4479 luminance *= 1.0f - mGlobalSaturationFactor;
4480 mat4 saturationMatrix = mat4(
4481 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4482 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4483 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4484 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4485 );
4486 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4487 } else {
4488 colorMatrix = mClientColorMatrix * mDaltonizer();
4489 }
4490
4491 if (mCurrentState.colorMatrix != colorMatrix) {
4492 mCurrentState.colorMatrix = colorMatrix;
4493 mCurrentState.colorMatrixChanged = true;
4494 setTransactionFlags(eTransactionNeeded);
4495 }
4496}
4497
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004498status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004499#pragma clang diagnostic push
4500#pragma clang diagnostic error "-Wswitch-enum"
4501 switch (static_cast<ISurfaceComposerTag>(code)) {
4502 // These methods should at minimum make sure that the client requested
4503 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004504 case BOOT_FINISHED:
4505 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004506 case CREATE_CONNECTION:
4507 case CREATE_DISPLAY:
4508 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004509 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004510 case GET_ACTIVE_COLOR_MODE:
4511 case GET_ANIMATION_FRAME_STATS:
4512 case GET_HDR_CAPABILITIES:
4513 case SET_ACTIVE_CONFIG:
4514 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004515 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004516 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004517 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4518 IPCThreadState* ipc = IPCThreadState::self();
4519 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4520 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004521 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004522 }
Robert Carr1db73f62016-12-21 12:58:51 -08004523 return OK;
4524 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004525 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004526 IPCThreadState* ipc = IPCThreadState::self();
4527 const int pid = ipc->getCallingPid();
4528 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004529 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4530 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004531 return PERMISSION_DENIED;
4532 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004533 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004534 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004535 // Used by apps to hook Choreographer to SurfaceFlinger.
4536 case CREATE_DISPLAY_EVENT_CONNECTION:
4537 // The following calls are currently used by clients that do not
4538 // request necessary permissions. However, they do not expose any secret
4539 // information, so it is OK to pass them.
4540 case AUTHENTICATE_SURFACE:
4541 case GET_ACTIVE_CONFIG:
4542 case GET_BUILT_IN_DISPLAY:
4543 case GET_DISPLAY_COLOR_MODES:
4544 case GET_DISPLAY_CONFIGS:
4545 case GET_DISPLAY_STATS:
Yiwei Zhangcd3f9e92018-08-21 15:15:42 -07004546 case GET_DISPLAY_VIEWPORT:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004547 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4548 // Calling setTransactionState is safe, because you need to have been
4549 // granted a reference to Client* and Handle* to do anything with it.
4550 case SET_TRANSACTION_STATE:
4551 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4552 case CREATE_SCOPED_CONNECTION: {
4553 return OK;
4554 }
4555 case CAPTURE_LAYERS:
4556 case CAPTURE_SCREEN: {
4557 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004558 IPCThreadState* ipc = IPCThreadState::self();
4559 const int pid = ipc->getCallingPid();
4560 const int uid = ipc->getCallingUid();
4561 if ((uid != AID_GRAPHICS) &&
4562 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4563 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4564 return PERMISSION_DENIED;
4565 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004566 return OK;
4567 }
4568 // The following codes are deprecated and should never be allowed to access SF.
4569 case CONNECT_DISPLAY_UNUSED:
4570 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4571 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4572 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004573 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004574 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004575
4576 // These codes are used for the IBinder protocol to either interrogate the recipient
4577 // side of the transaction for its canonical interface descriptor or to dump its state.
4578 // We let them pass by default.
4579 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4580 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4581 code == IBinder::SYSPROPS_TRANSACTION) {
4582 return OK;
4583 }
4584 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4585 // in onTransact verifies that the user is root, and has access to use SF.
4586 if (code >= 1000 && code <= 1029) {
4587 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4588 return OK;
4589 }
4590 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4591 return PERMISSION_DENIED;
4592#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004593}
4594
Ana Krulec13be8ad2018-08-21 02:43:56 +00004595status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4596 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004597 status_t credentialCheck = CheckTransactCodeCredentials(code);
4598 if (credentialCheck != OK) {
4599 return credentialCheck;
4600 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004601
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004602 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4603 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004604 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004605 IPCThreadState* ipc = IPCThreadState::self();
4606 const int uid = ipc->getCallingUid();
4607 if (CC_UNLIKELY(uid != AID_SYSTEM
4608 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004609 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004610 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004611 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004612 return PERMISSION_DENIED;
4613 }
4614 int n;
4615 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004616 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004617 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004618 return NO_ERROR;
4619 case 1002: // SHOW_UPDATES
4620 n = data.readInt32();
4621 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004622 invalidateHwcGeometry();
4623 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004624 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004625 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004626 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004627 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004628 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004629 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004630 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004631 setTransactionFlags(
4632 eTransactionNeeded|
4633 eDisplayTransactionNeeded|
4634 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004635 return NO_ERROR;
4636 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004637 case 1006:{ // send empty update
4638 signalRefresh();
4639 return NO_ERROR;
4640 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004641 case 1008: // toggle use of hw composer
4642 n = data.readInt32();
4643 mDebugDisableHWC = n ? 1 : 0;
4644 invalidateHwcGeometry();
4645 repaintEverything();
4646 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004647 case 1009: // toggle use of transform hint
4648 n = data.readInt32();
4649 mDebugDisableTransformHint = n ? 1 : 0;
4650 invalidateHwcGeometry();
4651 repaintEverything();
4652 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004653 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004654 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004655 reply->writeInt32(0);
4656 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004657 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004658 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004659 return NO_ERROR;
4660 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004661 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004662 if (!display) {
4663 return NAME_NOT_FOUND;
4664 }
4665
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004666 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004667 return NO_ERROR;
4668 }
4669 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004670 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004671 // daltonize
4672 n = data.readInt32();
4673 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004674 case 1:
4675 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4676 break;
4677 case 2:
4678 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4679 break;
4680 case 3:
4681 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4682 break;
4683 default:
4684 mDaltonizer.setType(ColorBlindnessType::None);
4685 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004686 }
4687 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004688 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004689 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004690 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004691 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004692
4693 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004694 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004695 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004696 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004697 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004698 // apply a color matrix
4699 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004700 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004701 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004702 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004703 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004704 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004705 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004706 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004707 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004708 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004709 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004710
4711 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4712 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004713 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004714 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4715 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4716 }
4717
Chia-I Wu28f320b2018-05-03 11:02:56 -07004718 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004719 return NO_ERROR;
4720 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004721 // This is an experimental interface
4722 // Needs to be shifted to proper binder interface when we productize
4723 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004724 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07004725 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004726 return NO_ERROR;
4727 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004728 case 1017: {
4729 n = data.readInt32();
4730 mForceFullDamage = static_cast<bool>(n);
4731 return NO_ERROR;
4732 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004733 case 1018: { // Modify Choreographer's phase offset
4734 n = data.readInt32();
4735 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4736 return NO_ERROR;
4737 }
4738 case 1019: { // Modify SurfaceFlinger's phase offset
4739 n = data.readInt32();
4740 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4741 return NO_ERROR;
4742 }
Irvel468051e2016-06-13 16:44:44 -07004743 case 1020: { // Layer updates interceptor
4744 n = data.readInt32();
4745 if (n) {
4746 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004747 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004748 }
4749 else{
4750 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004751 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004752 }
4753 return NO_ERROR;
4754 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004755 case 1021: { // Disable HWC virtual displays
4756 n = data.readInt32();
4757 mUseHwcVirtualDisplays = !n;
4758 return NO_ERROR;
4759 }
Romain Guy0147a172017-06-01 13:53:56 -07004760 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004761 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004762 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004763
Chia-I Wu28f320b2018-05-03 11:02:56 -07004764 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004765 return NO_ERROR;
4766 }
Romain Guy54f154a2017-10-24 21:40:32 +01004767 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004768 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004769 invalidateHwcGeometry();
4770 repaintEverything();
4771 return NO_ERROR;
4772 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004773 // TODO(b/111505327): Find out whether the usage of 1024 can switch to 1030,
4774 // deprecate 1024 if they can.
4775 case 1024: { // Does device have wide color gamut display?
Romain Guy54f154a2017-10-24 21:40:32 +01004776 reply->writeBool(hasWideColorDisplay);
4777 return NO_ERROR;
4778 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004779 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004780 n = data.readInt32();
4781 if (n) {
4782 ALOGV("LayerTracing enabled");
4783 mTracing.enable();
4784 doTracing("tracing.enable");
4785 reply->writeInt32(NO_ERROR);
4786 } else {
4787 ALOGV("LayerTracing disabled");
4788 status_t err = mTracing.disable();
4789 reply->writeInt32(err);
4790 }
4791 return NO_ERROR;
4792 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004793 case 1026: { // Get layer tracing status
4794 reply->writeBool(mTracing.isEnabled());
4795 return NO_ERROR;
4796 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004797 // Is a DisplayColorSetting supported?
4798 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004799 const auto display = getDefaultDisplayDevice();
4800 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004801 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004802 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004803
4804 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4805 switch (setting) {
4806 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07004807 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004808 break;
4809 case DisplayColorSetting::UNMANAGED:
4810 reply->writeBool(true);
4811 break;
4812 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004813 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004814 break;
4815 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004816 reply->writeBool(
4817 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004818 break;
4819 }
4820 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004821 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004822 // Is VrFlinger active?
4823 case 1028: {
4824 Mutex::Autolock _l(mStateLock);
4825 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4826 return NO_ERROR;
4827 }
David Sodman6d46c1e2018-07-13 12:59:48 -07004828 case 1029: {
4829 // Code 1029 is an experimental feature that allows applications to
4830 // simulate a high frequency panel by setting a multiplier and divisor
4831 // on the VSYNC-sf clock. If either the multiplier or divisor are
4832 // 0, then the code will set both to 1 to return the VSYNC-sf clock
4833 // to it's normal frequency.
4834 int multiplier = data.readInt32();
4835 int divisor = data.readInt32();
4836
4837 if ((multiplier == 0) || (divisor == 0)) {
4838 multiplier = 1;
4839 divisor = 1;
4840 }
4841
4842 if ((multiplier == 1) && (divisor == 1)) {
4843 enableHardwareVsync();
4844 } else {
4845 disableHardwareVsync(true);
4846 }
4847 getBE().mHwc->getActiveConfig(DisplayDevice::DISPLAY_PRIMARY)
4848 ->scalePanelFrequency(multiplier, divisor);
4849 mPrimaryDispSync->scalePeriod(multiplier, divisor);
4850
4851 ATRACE_INT("PeriodMultiplier", multiplier);
4852 ATRACE_INT("PeriodDivisor", divisor);
4853 return NO_ERROR;
4854 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004855 // Is device color managed?
4856 case 1030: {
4857 reply->writeBool(useColorManagement);
4858 return NO_ERROR;
4859 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004860 }
4861 }
4862 return err;
4863}
4864
Steven Thomas6d8110b2017-08-31 18:24:21 -07004865void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004866 android_atomic_or(1, &mRepaintEverything);
4867 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004868}
4869
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004870// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4871class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004872public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004873 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4874 ~WindowDisconnector() {
4875 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004876 }
4877
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004878private:
4879 ANativeWindow* mWindow;
4880 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004881};
4882
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004883status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4884 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4885 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4886 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004887 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004888 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004889
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004890 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004891
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004892 const auto display = getDisplayDeviceLocked(displayToken);
4893 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004894
Yiwei Zhang06a58e22018-08-20 16:42:23 -07004895 const Rect& dispScissor = display->getScissor();
4896 if (!dispScissor.isEmpty()) {
4897 sourceCrop.set(dispScissor);
4898 // adb shell screencap will default reqWidth and reqHeight to zeros.
4899 if (reqWidth == 0 || reqHeight == 0) {
Yiwei Zhangec90e582018-08-21 22:11:37 -07004900 reqWidth = uint32_t(display->getViewport().width());
4901 reqHeight = uint32_t(display->getViewport().height());
Yiwei Zhang06a58e22018-08-20 16:42:23 -07004902 }
4903 }
4904
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004905 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004906
4907 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004908 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004909 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004910}
4911
4912status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004913 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004914 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004915 ATRACE_CALL();
4916
4917 class LayerRenderArea : public RenderArea {
4918 public:
Robert Carr578038f2018-03-09 12:25:24 -08004919 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4920 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004921 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004922 mLayer(layer),
4923 mCrop(crop),
4924 mFlinger(flinger),
4925 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07004926 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004927 Rect getBounds() const override {
4928 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07004929 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07004930 }
Marissa Wall61c58622018-07-18 10:12:20 -07004931 int getHeight() const override {
4932 return mLayer->getActiveHeight(mLayer->getDrawingState());
4933 }
4934 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07004935 bool isSecure() const override { return false; }
4936 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004937 Rect getSourceCrop() const override {
4938 if (mCrop.isEmpty()) {
4939 return getBounds();
4940 } else {
4941 return mCrop;
4942 }
4943 }
Robert Carr578038f2018-03-09 12:25:24 -08004944 class ReparentForDrawing {
4945 public:
4946 const sp<Layer>& oldParent;
4947 const sp<Layer>& newParent;
4948
4949 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4950 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004951 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004952 }
Robert Carr15eae092018-03-23 13:43:53 -07004953 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004954 };
4955
4956 void render(std::function<void()> drawLayers) override {
4957 if (!mChildrenOnly) {
4958 mTransform = mLayer->getTransform().inverse();
4959 drawLayers();
4960 } else {
4961 Rect bounds = getBounds();
4962 screenshotParentLayer =
4963 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4964 bounds.getWidth(), bounds.getHeight(), 0);
4965
4966 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4967 drawLayers();
4968 }
4969 }
chaviwa76b2712017-09-20 12:02:26 -07004970
chaviwa76b2712017-09-20 12:02:26 -07004971 private:
chaviw7206d492017-11-10 16:16:12 -08004972 const sp<Layer> mLayer;
4973 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004974
4975 // In the "childrenOnly" case we reparent the children to a screenshot
4976 // layer which has no properties set and which does not draw.
4977 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07004978 ui::Transform mTransform;
Robert Carr578038f2018-03-09 12:25:24 -08004979
4980 SurfaceFlinger* mFlinger;
4981 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004982 };
4983
4984 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4985 auto parent = layerHandle->owner.promote();
4986
chaviw7206d492017-11-10 16:16:12 -08004987 if (parent == nullptr || parent->isPendingRemoval()) {
4988 ALOGE("captureLayers called with a removed parent");
4989 return NAME_NOT_FOUND;
4990 }
4991
Robert Carr578038f2018-03-09 12:25:24 -08004992 const int uid = IPCThreadState::self()->getCallingUid();
4993 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4994 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4995 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4996 return PERMISSION_DENIED;
4997 }
4998
chaviw7206d492017-11-10 16:16:12 -08004999 Rect crop(sourceCrop);
5000 if (sourceCrop.width() <= 0) {
5001 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005002 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005003 }
5004
5005 if (sourceCrop.height() <= 0) {
5006 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005007 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005008 }
5009
5010 int32_t reqWidth = crop.width() * frameScale;
5011 int32_t reqHeight = crop.height() * frameScale;
5012
Robert Carr578038f2018-03-09 12:25:24 -08005013 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005014
Robert Carr578038f2018-03-09 12:25:24 -08005015 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005016 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5017 if (!layer->isVisible()) {
5018 return;
Robert Carr578038f2018-03-09 12:25:24 -08005019 } else if (childrenOnly && layer == parent.get()) {
5020 return;
chaviwa76b2712017-09-20 12:02:26 -07005021 }
5022 visitor(layer);
5023 });
5024 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005025 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005026}
5027
5028status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5029 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005030 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005031 bool useIdentityTransform) {
5032 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005033
Iris Chang7501ed62018-04-30 14:45:42 +08005034 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07005035
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005036 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5037 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5038 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5039 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005040
5041 // This mutex protects syncFd and captureResult for communication of the return values from the
5042 // main thread back to this Binder thread
5043 std::mutex captureMutex;
5044 std::condition_variable captureCondition;
5045 std::unique_lock<std::mutex> captureLock(captureMutex);
5046 int syncFd = -1;
5047 std::optional<status_t> captureResult;
5048
Robert Carr03480e22018-01-04 16:02:06 -08005049 const int uid = IPCThreadState::self()->getCallingUid();
5050 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5051
Dominik Laskowski8c001672018-05-30 16:52:06 -07005052 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005053 // If there is a refresh pending, bug out early and tell the binder thread to try again
5054 // after the refresh.
5055 if (mRefreshPending) {
5056 ATRACE_NAME("Skipping screenshot for now");
5057 std::unique_lock<std::mutex> captureLock(captureMutex);
5058 captureResult = std::make_optional<status_t>(EAGAIN);
5059 captureCondition.notify_one();
5060 return;
5061 }
5062
5063 status_t result = NO_ERROR;
5064 int fd = -1;
5065 {
5066 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005067 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005068 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5069 useIdentityTransform, forSystem, &fd);
5070 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005071 }
5072
5073 {
5074 std::unique_lock<std::mutex> captureLock(captureMutex);
5075 syncFd = fd;
5076 captureResult = std::make_optional<status_t>(result);
5077 captureCondition.notify_one();
5078 }
5079 });
5080
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005081 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005082 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005083 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005084 while (*captureResult == EAGAIN) {
5085 captureResult.reset();
5086 result = postMessageAsync(message);
5087 if (result != NO_ERROR) {
5088 return result;
5089 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005090 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005091 }
5092 result = *captureResult;
5093 }
5094
5095 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005096 sync_wait(syncFd, -1);
5097 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005098 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005099
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005100 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005101}
5102
chaviwa76b2712017-09-20 12:02:26 -07005103void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5104 TraverseLayersFunction traverseLayers, bool yswap,
5105 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005106 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005107
Lloyd Pique144e1162017-12-20 16:44:52 -08005108 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005109
5110 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005111 const auto raWidth = renderArea.getWidth();
5112 const auto raHeight = renderArea.getHeight();
5113
5114 const auto reqWidth = renderArea.getReqWidth();
5115 const auto reqHeight = renderArea.getReqHeight();
5116 Rect sourceCrop = renderArea.getSourceCrop();
5117
Iris Chang7501ed62018-04-30 14:45:42 +08005118 bool filtering = false;
5119 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5120 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5121 static_cast<int32_t>(reqHeight) != raWidth;
5122 } else {
5123 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5124 static_cast<int32_t>(reqHeight) != raHeight;
5125 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005126
Dan Stozac1879002014-05-22 15:59:05 -07005127 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005128 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005129 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005130 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005131 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
Peiyong Linefefaac2018-08-17 12:27:51 -07005132 ui::Transform tr;
Iris Chang7501ed62018-04-30 14:45:42 +08005133 uint32_t flags = 0x00;
5134 switch (mPrimaryDisplayOrientation) {
5135 case DisplayState::eOrientation90:
Peiyong Linefefaac2018-08-17 12:27:51 -07005136 flags = ui::Transform::ROT_90;
Iris Chang7501ed62018-04-30 14:45:42 +08005137 break;
5138 case DisplayState::eOrientation180:
Peiyong Linefefaac2018-08-17 12:27:51 -07005139 flags = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005140 break;
5141 case DisplayState::eOrientation270:
Peiyong Linefefaac2018-08-17 12:27:51 -07005142 flags = ui::Transform::ROT_270;
Iris Chang7501ed62018-04-30 14:45:42 +08005143 break;
5144 }
5145 tr.set(flags, raWidth, raHeight);
5146 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005147 }
5148
5149 // ensure that sourceCrop is inside screen
5150 if (sourceCrop.left < 0) {
5151 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5152 }
chaviwa76b2712017-09-20 12:02:26 -07005153 if (sourceCrop.right > raWidth) {
5154 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005155 }
5156 if (sourceCrop.top < 0) {
5157 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5158 }
chaviwa76b2712017-09-20 12:02:26 -07005159 if (sourceCrop.bottom > raHeight) {
5160 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005161 }
5162
Chia-I Wu36574d92018-05-16 10:54:36 -07005163 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5164 engine.setOutputDataSpace(Dataspace::SRGB);
5165 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005166
Mathias Agopian180f10d2013-04-10 22:55:41 -07005167 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005168 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005169
Peiyong Linefefaac2018-08-17 12:27:51 -07005170 ui::Transform::orientation_flags rotation = renderArea.getRotationFlags();
Iris Chang7501ed62018-04-30 14:45:42 +08005171 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5172 // convert hw orientation into flag presentation
5173 // here inverse transform needed
5174 uint8_t hw_rot_90 = 0x00;
5175 uint8_t hw_flip_hv = 0x00;
5176 switch (mPrimaryDisplayOrientation) {
5177 case DisplayState::eOrientation90:
Peiyong Linefefaac2018-08-17 12:27:51 -07005178 hw_rot_90 = ui::Transform::ROT_90;
5179 hw_flip_hv = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005180 break;
5181 case DisplayState::eOrientation180:
Peiyong Linefefaac2018-08-17 12:27:51 -07005182 hw_flip_hv = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005183 break;
5184 case DisplayState::eOrientation270:
Peiyong Linefefaac2018-08-17 12:27:51 -07005185 hw_rot_90 = ui::Transform::ROT_90;
Iris Chang7501ed62018-04-30 14:45:42 +08005186 break;
5187 }
5188
5189 // transform flags operation
5190 // 1) flip H V if both have ROT_90 flag
5191 // 2) XOR these flags
Peiyong Linefefaac2018-08-17 12:27:51 -07005192 uint8_t rotation_rot_90 = rotation & ui::Transform::ROT_90;
5193 uint8_t rotation_flip_hv = rotation & ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005194 if (rotation_rot_90 & hw_rot_90) {
Peiyong Linefefaac2018-08-17 12:27:51 -07005195 rotation_flip_hv = (~rotation_flip_hv) & ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005196 }
Peiyong Linefefaac2018-08-17 12:27:51 -07005197 rotation = static_cast<ui::Transform::orientation_flags>
Iris Chang7501ed62018-04-30 14:45:42 +08005198 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5199 }
5200
Mathias Agopian180f10d2013-04-10 22:55:41 -07005201 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005202 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005203 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005204 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005205
chaviw50da5042018-04-09 13:49:37 -07005206 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005207 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005208 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005209
chaviwa76b2712017-09-20 12:02:26 -07005210 traverseLayers([&](Layer* layer) {
5211 if (filtering) layer->setFiltering(true);
David Sodmanca10ed22018-04-16 14:10:25 -07005212 layer->drawNow(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005213 if (filtering) layer->setFiltering(false);
5214 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005215}
5216
chaviwa76b2712017-09-20 12:02:26 -07005217status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5218 TraverseLayersFunction traverseLayers,
5219 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005220 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005221 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005222 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005223 ATRACE_CALL();
5224
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005225 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005226
5227 traverseLayers([&](Layer* layer) {
5228 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5229 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005230
Robert Carr03480e22018-01-04 16:02:06 -08005231 // We allow the system server to take screenshots of secure layers for
5232 // use in situations like the Screen-rotation animation and place
5233 // the impetus on WindowManager to not persist them.
5234 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005235 ALOGW("FB is protected: PERMISSION_DENIED");
5236 return PERMISSION_DENIED;
5237 }
5238
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005239 // this binds the given EGLImage as a framebuffer for the
5240 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005241 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005242 if (bufferBond.getStatus() != NO_ERROR) {
5243 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005244 return INVALID_OPERATION;
5245 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005246
Dan Stozaabcda352017-06-01 14:37:39 -07005247 // this will in fact render into our dequeued buffer
5248 // via an FBO, which means we didn't have to create
5249 // an EGLSurface and therefore we're not
5250 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005251 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005252
Dan Stozaabcda352017-06-01 14:37:39 -07005253 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005254 getRenderEngine().finish();
5255 *outSyncFd = -1;
5256
chaviwa76b2712017-09-20 12:02:26 -07005257 const auto reqWidth = renderArea.getReqWidth();
5258 const auto reqHeight = renderArea.getReqHeight();
5259
Dan Stozaabcda352017-06-01 14:37:39 -07005260 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5261 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005262 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005263 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005264 } else {
5265 base::unique_fd syncFd = getRenderEngine().flush();
5266 if (syncFd < 0) {
5267 getRenderEngine().finish();
5268 }
5269 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005270 }
5271
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005272 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005273}
5274
Mathias Agopiand5556842013-09-19 17:08:37 -07005275void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005276 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005277 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005278 for (size_t y = 0; y < h; y++) {
5279 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5280 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005281 if (p[x] != 0xFF000000) return;
5282 }
5283 }
chaviwa76b2712017-09-20 12:02:26 -07005284 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005285
Robert Carr2047fae2016-11-28 14:09:09 -08005286 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005287 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005288 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005289 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5290 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5291 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5292 static_cast<float>(state.color.a));
5293 i++;
5294 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005295 }
5296}
5297
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005298// ---------------------------------------------------------------------------
5299
Dan Stoza412903f2017-04-27 13:42:17 -07005300void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5301 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005302}
5303
Dan Stoza412903f2017-04-27 13:42:17 -07005304void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5305 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005306}
5307
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005308void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5309 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005310 const LayerVector::Visitor& visitor) {
5311 // We loop through the first level of layers without traversing,
5312 // as we need to interpret min/max layer Z in the top level Z space.
5313 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005314 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005315 continue;
5316 }
5317 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005318 // relative layers are traversed in Layer::traverseInZOrder
5319 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005320 continue;
5321 }
5322 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005323 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005324 return;
5325 }
chaviwa76b2712017-09-20 12:02:26 -07005326 if (!layer->isVisible()) {
5327 return;
5328 }
5329 visitor(layer);
5330 });
5331 }
5332}
5333
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005334}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005335
Lloyd Pique074e8122018-07-26 12:57:23 -07005336
Mathias Agopian3f844832013-08-07 21:24:32 -07005337#if defined(__gl_h_)
5338#error "don't include gl/gl.h in this file"
5339#endif
5340
5341#if defined(__gl2_h_)
5342#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005343#endif