blob: 563ca5a1c3380b794ccc00988f0b130ce79e1c2d [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 {
Hernan Liatis57568932018-08-16 17:07:08 -0700782 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700783 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700784 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800785 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700786 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700787 }
788 return density;
789 }
790 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700791 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700792 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700793 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700794 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 Sodman10a41ff2018-08-05 12:14:17 -07001464
David Sodmanfa9b2af2017-12-24 13:28:59 -08001465 for (const auto& [token, display] : mDisplays) {
David Sodman10a41ff2018-08-05 12:14:17 -07001466 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001467 beginFrame(display);
David Sodman10a41ff2018-08-05 12:14:17 -07001468 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
1469 setUpHWComposer(compositionInfo);
1470 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001471 prepareFrame(display);
1472 doDebugFlashRegions(display, repaintEverything);
1473 doComposition(display, repaintEverything);
1474 }
1475
Adrian Roos1e1a1282017-11-01 19:05:31 +01001476 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001477 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001478
1479 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001480 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001481
Dan Stozabfbffeb2016-07-21 14:49:33 -07001482 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001483 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001484 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001485 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001486 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001487
Jorim Jaggi90535212018-05-23 23:44:06 +02001488 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001489
David Sodman7e4ae112018-02-09 15:02:28 -08001490 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001491 for (const auto& [token, display] : mDisplays) {
1492 const auto displayId = display->getId();
David Sodman7e4ae112018-02-09 15:02:28 -08001493 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[displayId]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001494 compositionInfo.hwc.hwcLayer = nullptr;
1495 }
David Sodmanba340492018-08-05 21:51:33 -07001496 }
David Sodman7e4ae112018-02-09 15:02:28 -08001497
1498 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001499}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001500
David Sodmanfa9b2af2017-12-24 13:28:59 -08001501
1502bool SurfaceFlinger::handleMessageInvalidate() {
1503 ATRACE_CALL();
1504 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001505}
1506
David Sodman79bba0e2018-08-05 18:07:49 -07001507void SurfaceFlinger::calculateWorkingSet() {
1508 ATRACE_CALL();
1509 ALOGV(__FUNCTION__);
1510
David Sodman79bba0e2018-08-05 18:07:49 -07001511 // build the h/w work list
1512 if (CC_UNLIKELY(mGeometryInvalid)) {
1513 mGeometryInvalid = false;
1514 for (const auto& [token, display] : mDisplays) {
1515 const auto displayId = display->getId();
1516 if (displayId >= 0) {
1517 const Vector<sp<Layer>>& currentLayers(
1518 display->getVisibleLayersSortedByZ());
1519 for (size_t i = 0; i < currentLayers.size(); i++) {
1520 const auto& layer = currentLayers[i];
1521
1522 if (!layer->hasHwcLayer(displayId)) {
1523 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1524 layer->forceClientComposition(displayId);
1525 continue;
1526 }
1527 }
1528
1529 layer->setGeometry(display, i);
1530 if (mDebugDisableHWC || mDebugRegion) {
1531 layer->forceClientComposition(displayId);
1532 }
1533 }
1534 }
1535 }
1536 }
1537
1538 // Set the per-frame data
1539 for (const auto& [token, display] : mDisplays) {
1540 const auto displayId = display->getId();
1541 if (displayId < 0) {
1542 continue;
1543 }
1544
1545 if (mDrawingState.colorMatrixChanged) {
1546 display->setColorTransform(mDrawingState.colorMatrix);
1547 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1548 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1549 "display %d: %d", displayId, result);
1550 }
1551 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1552 if (layer->isHdrY410()) {
1553 layer->forceClientComposition(displayId);
1554 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1555 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1556 !display->hasHDR10Support()) {
1557 layer->forceClientComposition(displayId);
1558 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1559 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1560 !display->hasHLGSupport()) {
1561 layer->forceClientComposition(displayId);
1562 }
1563
1564 if (layer->getForceClientComposition(displayId)) {
1565 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1566 layer->setCompositionType(displayId, HWC2::Composition::Client);
1567 continue;
1568 }
1569
1570 layer->setPerFrameData(display);
1571 }
1572
Peiyong Lin13effd12018-07-24 17:01:47 -07001573 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001574 ColorMode colorMode;
1575 Dataspace dataSpace;
1576 RenderIntent renderIntent;
1577 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1578 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1579 }
1580 }
1581
1582 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001583
1584 for (const auto& [token, display] : mDisplays) {
David Sodman15fb96e2018-01-07 10:23:24 -08001585 const auto displayId = display->getId();
1586 getBE().mCompositionInfo[displayId].clear();
David Sodmanba340492018-08-05 21:51:33 -07001587 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1588 auto displayId = display->getId();
1589 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1590 if (!layer->setHwcLayer(displayId)) {
1591 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1592 }
David Sodman15fb96e2018-01-07 10:23:24 -08001593 layer->getBE().compositionInfo.hwc.displayId = displayId;
1594 getBE().mCompositionInfo[displayId].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001595 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1596 }
1597 }
David Sodman79bba0e2018-08-05 18:07:49 -07001598}
1599
David Sodmanfa9b2af2017-12-24 13:28:59 -08001600void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001601{
David Sodmanfb95bcc2017-12-22 15:45:30 -08001602 const auto displayId = display->getId();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001603 // is debugging enabled
1604 if (CC_LIKELY(!mDebugRegion))
1605 return;
1606
David Sodmanfa9b2af2017-12-24 13:28:59 -08001607 if (display->isPoweredOn()) {
1608 // transform the dirty region into this screen's coordinate space
1609 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1610 if (!dirtyRegion.isEmpty()) {
1611 // redraw the whole screen
1612 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001613
David Sodmanfa9b2af2017-12-24 13:28:59 -08001614 // and draw the dirty region
1615 const int32_t height = display->getHeight();
1616 auto& engine(getRenderEngine());
1617 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001618
David Sodmanfa9b2af2017-12-24 13:28:59 -08001619 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001620 }
1621 }
1622
David Sodmanfa9b2af2017-12-24 13:28:59 -08001623 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001624
1625 if (mDebugRegion > 1) {
1626 usleep(mDebugRegion * 1000);
1627 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001628
David Sodmanfa9b2af2017-12-24 13:28:59 -08001629 if (display->isPoweredOn()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08001630 status_t result = display->prepareFrame(
1631 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001632 ALOGE_IF(result != NO_ERROR,
1633 "prepareFrame for display %d failed:"
1634 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001635 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001636 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001637}
1638
Adrian Roos1e1a1282017-11-01 19:05:31 +01001639void SurfaceFlinger::doTracing(const char* where) {
1640 ATRACE_CALL();
1641 ATRACE_NAME(where);
1642 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001643 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001644 }
1645}
1646
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001647void SurfaceFlinger::logLayerStats() {
1648 ATRACE_CALL();
1649 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001650 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001651 if (display->isPrimary()) {
1652 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001653 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001654 }
1655 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001656
1657 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001658 }
1659}
1660
David Sodman2b406362017-12-15 13:33:47 -08001661void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001662{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001663 ATRACE_CALL();
1664 ALOGV("preComposition");
1665
David Sodman2b406362017-12-15 13:33:47 -08001666 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1667
Mathias Agopiancd60f992012-08-16 16:28:27 -07001668 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001669 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001670 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001671 needExtraInvalidate = true;
1672 }
Robert Carr2047fae2016-11-28 14:09:09 -08001673 });
1674
Mathias Agopiancd60f992012-08-16 16:28:27 -07001675 if (needExtraInvalidate) {
1676 signalLayerUpdate();
1677 }
1678}
1679
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001680void SurfaceFlinger::updateCompositorTiming(
1681 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1682 std::shared_ptr<FenceTime>& presentFenceTime) {
1683 // Update queue of past composite+present times and determine the
1684 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001685 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001686 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001687 while (!getBE().mCompositePresentTimes.empty()) {
1688 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001689 // Cached values should have been updated before calling this method,
1690 // which helps avoid duplicate syscalls.
1691 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1692 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1693 break;
1694 }
1695 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001696 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001697 }
1698
1699 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001700 while (getBE().mCompositePresentTimes.size() > 16) {
1701 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001702 }
1703
Brian Andersond0010582017-03-07 13:20:31 -08001704 setCompositorTimingSnapped(
1705 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1706}
1707
1708void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1709 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001710 // Integer division and modulo round toward 0 not -inf, so we need to
1711 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001712 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001713 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1714 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1715
Brian Andersond0010582017-03-07 13:20:31 -08001716 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1717 if (idealLatency <= 0) {
1718 idealLatency = vsyncInterval;
1719 }
1720
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001721 // Snap the latency to a value that removes scheduling jitter from the
1722 // composition and present times, which often have >1ms of jitter.
1723 // Reducing jitter is important if an app attempts to extrapolate
1724 // something (such as user input) to an accurate diasplay time.
1725 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1726 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001727 nsecs_t bias = vsyncInterval / 2;
1728 int64_t extraVsyncs =
1729 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1730 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1731 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001732
David Sodman99974d22017-11-28 12:04:33 -08001733 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1734 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1735 getBE().mCompositorTiming.interval = vsyncInterval;
1736 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001737}
1738
David Sodman2b406362017-12-15 13:33:47 -08001739void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001740{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001741 ATRACE_CALL();
1742 ALOGV("postComposition");
1743
Brian Anderson3546a3f2016-07-14 11:51:14 -07001744 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001745 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001746 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001747 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001748 }
1749
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001750 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001751 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001752
David Sodman73beded2017-11-15 11:56:06 -08001753 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001754 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001755 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001756 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001757 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001758 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001759 } else {
1760 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1761 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001762
David Sodman73beded2017-11-15 11:56:06 -08001763 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001764 mPreviousPresentFence =
1765 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1766 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001767 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001768
Lloyd Pique41be5d22018-06-21 13:11:48 -07001769 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1770 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001771
David Sodman2b406362017-12-15 13:33:47 -08001772 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001773 // when we started doing work for this frame, but that should be okay
1774 // since updateCompositorTiming has snapping logic.
1775 updateCompositorTiming(
David Sodman2b406362017-12-15 13:33:47 -08001776 vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001777 CompositorTiming compositorTiming;
1778 {
David Sodman99974d22017-11-28 12:04:33 -08001779 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1780 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001781 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001782
Robert Carr2047fae2016-11-28 14:09:09 -08001783 mDrawingState.traverseInZOrder([&](Layer* layer) {
1784 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001785 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001786 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001787 recordBufferingStats(layer->getName().string(),
1788 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001789 }
Robert Carr2047fae2016-11-28 14:09:09 -08001790 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001791
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001792 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001793 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001794 enableHardwareVsync();
1795 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001796 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001797 }
1798 }
1799
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001800 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001801 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001802 enableHardwareVsync();
1803 }
1804 }
1805
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001806 if (mAnimCompositionPending) {
1807 mAnimCompositionPending = false;
1808
Brian Anderson4e606e32017-03-16 15:34:57 -07001809 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001810 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001811 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001812 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001813 // The HWC doesn't support present fences, so use the refresh
1814 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001815 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001816 mAnimFrameTracker.setActualPresentTime(presentTime);
1817 }
1818 mAnimFrameTracker.advanceFrame();
1819 }
Dan Stozab90cf072015-03-05 11:05:59 -08001820
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001821 mTimeStats.incrementTotalFrames();
1822 if (mHadClientComposition) {
1823 mTimeStats.incrementClientCompositionFrames();
1824 }
1825
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001826 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001827 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001828 return;
1829 }
1830
1831 nsecs_t currentTime = systemTime();
1832 if (mHasPoweredOff) {
1833 mHasPoweredOff = false;
1834 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001835 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001836 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001837 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1838 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001839 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001840 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001841 }
David Sodman4a36e932017-11-07 14:29:47 -08001842 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001843 }
David Sodman4a36e932017-11-07 14:29:47 -08001844 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001845
1846 {
1847 std::lock_guard lock(mTexturePoolMutex);
1848 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1849 if (refillCount > 0) {
1850 const size_t offset = mTexturePool.size();
1851 mTexturePool.resize(mTexturePoolSize);
1852 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1853 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1854 }
1855 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001856}
1857
1858void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001859 ATRACE_CALL();
1860 ALOGV("rebuildLayerStacks");
1861
Mathias Agopiancd60f992012-08-16 16:28:27 -07001862 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001863 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001864 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001865 mVisibleRegionsDirty = false;
1866 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001867
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001868 for (const auto& pair : mDisplays) {
1869 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001870 Region opaqueRegion;
1871 Region dirtyRegion;
1872 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001873 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001874 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001875 const Rect bounds = display->getBounds();
1876 if (display->isPoweredOn()) {
1877 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001878
Jeff Sharkey76488112017-02-27 14:15:18 -07001879 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001880 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001881 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001882 Region drawRegion(tr.transform(
1883 layer->visibleNonTransparentRegion));
1884 drawRegion.andSelf(bounds);
1885 if (!drawRegion.isEmpty()) {
1886 layersSortedByZ.add(layer);
1887 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001888 // Clear out the HWC layer if this layer was
1889 // previously visible, but no longer is
1890 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001891 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001892 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001893 // WM changes display->layerStack upon sleep/awake.
1894 // Here we make sure we delete the HWC layers even if
1895 // WM changed their layer stack.
1896 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001897 }
1898
1899 // If a layer is not going to get a release fence because
1900 // it is invisible, but it is also going to release its
1901 // old buffer, add it to the list of layers needing
1902 // fences.
1903 if (hwcLayerDestroyed) {
1904 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1905 mLayersWithQueuedFrames.cend(), layer);
1906 if (found != mLayersWithQueuedFrames.cend()) {
1907 layersNeedingFences.add(layer);
1908 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001909 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001910 });
1911 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001912 display->setVisibleLayersSortedByZ(layersSortedByZ);
1913 display->setLayersNeedingFences(layersNeedingFences);
1914 display->undefinedRegion.set(bounds);
1915 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1916 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001917 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001918 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001919}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001920
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001921// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001922// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001923// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001924// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001925// The returned HDR data space is one of
1926// - Dataspace::UNKNOWN
1927// - Dataspace::BT2020_HLG
1928// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001929Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1930 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001931 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001932 *outHdrDataSpace = Dataspace::UNKNOWN;
1933
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001934 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001935 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001936 case Dataspace::V0_SCRGB:
1937 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001938 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001939 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001940 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001941 case Dataspace::BT2020_PQ:
1942 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001943 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001944 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001945 case Dataspace::BT2020_HLG:
1946 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001947 // When there's mixed PQ content and HLG content, we set the HDR
1948 // data space to be BT2020_PQ and convert HLG to PQ.
1949 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1950 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001951 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001952 break;
1953 default:
1954 break;
1955 }
Romain Guy54f154a2017-10-24 21:40:32 +01001956 }
1957
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001958 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001959}
1960
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001961// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001962void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1963 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001964 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1965 *outMode = ColorMode::NATIVE;
1966 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001967 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001968 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001969 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001970
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001971 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001972 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001973
Peiyong Lindfde5112018-06-05 10:58:41 -07001974 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001975 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001976 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001977 if (isHdr) {
1978 bestDataSpace = hdrDataSpace;
1979 }
1980
Chia-I Wu0d711262018-05-21 15:19:35 -07001981 RenderIntent intent;
1982 switch (mDisplayColorSetting) {
1983 case DisplayColorSetting::MANAGED:
1984 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001985 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001986 break;
1987 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001988 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001989 break;
1990 default: // vendor display color setting
1991 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1992 break;
1993 }
Chia-I Wube02ec02018-05-18 10:59:36 -07001994
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001995 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001996}
1997
David Sodman10a41ff2018-08-05 12:14:17 -07001998void SurfaceFlinger::configureSidebandComposition(const CompositionInfo& compositionInfo) const
1999{
2000 HWC2::Error error;
2001 LOG_ALWAYS_FATAL_IF(compositionInfo.hwc.sidebandStream == nullptr,
2002 "CompositionType is sideband, but sideband stream is nullptr");
2003 error = (compositionInfo.hwc.hwcLayer)
2004 ->setSidebandStream(compositionInfo.hwc.sidebandStream->handle());
2005 if (error != HWC2::Error::None) {
2006 ALOGE("[SF] Failed to set sideband stream %p: %s (%d)",
2007 compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
2008 static_cast<int32_t>(error));
2009 }
2010}
2011
2012void SurfaceFlinger::configureHwcCommonData(const CompositionInfo& compositionInfo) const
2013{
2014 HWC2::Error error;
2015
2016 if (!compositionInfo.hwc.skipGeometry) {
2017 error = (compositionInfo.hwc.hwcLayer)->setBlendMode(compositionInfo.hwc.blendMode);
2018 ALOGE_IF(error != HWC2::Error::None,
2019 "[SF] Failed to set blend mode %s:"
2020 " %s (%d)",
2021 to_string(compositionInfo.hwc.blendMode).c_str(), to_string(error).c_str(),
2022 static_cast<int32_t>(error));
2023
2024 error = (compositionInfo.hwc.hwcLayer)->setDisplayFrame(compositionInfo.hwc.displayFrame);
2025 ALOGE_IF(error != HWC2::Error::None,
2026 "[SF] Failed to set the display frame [%d, %d, %d, %d] %s (%d)",
2027 compositionInfo.hwc.displayFrame.left,
2028 compositionInfo.hwc.displayFrame.right,
2029 compositionInfo.hwc.displayFrame.top,
2030 compositionInfo.hwc.displayFrame.bottom,
2031 to_string(error).c_str(), static_cast<int32_t>(error));
2032
2033 error = (compositionInfo.hwc.hwcLayer)->setSourceCrop(compositionInfo.hwc.sourceCrop);
2034 ALOGE_IF(error != HWC2::Error::None,
2035 "[SF] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: %s (%d)",
2036 compositionInfo.hwc.sourceCrop.left,
2037 compositionInfo.hwc.sourceCrop.right,
2038 compositionInfo.hwc.sourceCrop.top,
2039 compositionInfo.hwc.sourceCrop.bottom,
2040 to_string(error).c_str(), static_cast<int32_t>(error));
2041
2042 error = (compositionInfo.hwc.hwcLayer)->setPlaneAlpha(compositionInfo.hwc.alpha);
2043 ALOGE_IF(error != HWC2::Error::None,
2044 "[SF] Failed to set plane alpha %.3f: "
2045 "%s (%d)",
2046 compositionInfo.hwc.alpha,
2047 to_string(error).c_str(), static_cast<int32_t>(error));
2048
2049
2050 error = (compositionInfo.hwc.hwcLayer)->setZOrder(compositionInfo.hwc.z);
2051 ALOGE_IF(error != HWC2::Error::None,
2052 "[SF] Failed to set Z %u: %s (%d)",
2053 compositionInfo.hwc.z,
2054 to_string(error).c_str(), static_cast<int32_t>(error));
2055
2056 error = (compositionInfo.hwc.hwcLayer)
2057 ->setInfo(compositionInfo.hwc.type, compositionInfo.hwc.appId);
2058 ALOGE_IF(error != HWC2::Error::None,
2059 "[SF] Failed to set info (%d)",
2060 static_cast<int32_t>(error));
2061
2062 error = (compositionInfo.hwc.hwcLayer)->setTransform(compositionInfo.hwc.transform);
2063 ALOGE_IF(error != HWC2::Error::None,
2064 "[SF] Failed to set transform %s: "
2065 "%s (%d)",
2066 to_string(compositionInfo.hwc.transform).c_str(), to_string(error).c_str(),
2067 static_cast<int32_t>(error));
2068 }
2069
2070 error = (compositionInfo.hwc.hwcLayer)->setCompositionType(compositionInfo.compositionType);
2071 ALOGE_IF(error != HWC2::Error::None,
2072 "[SF] Failed to set composition type: %s (%d)",
2073 to_string(error).c_str(), static_cast<int32_t>(error));
2074
2075 error = (compositionInfo.hwc.hwcLayer)->setDataspace(compositionInfo.hwc.dataspace);
2076 ALOGE_IF(error != HWC2::Error::None,
2077 "[SF] Failed to set dataspace: %s (%d)",
2078 to_string(error).c_str(), static_cast<int32_t>(error));
2079
2080 error = (compositionInfo.hwc.hwcLayer)->setPerFrameMetadata(
2081 compositionInfo.hwc.supportedPerFrameMetadata, compositionInfo.hwc.hdrMetadata);
2082 ALOGE_IF(error != HWC2::Error::None && error != HWC2::Error::Unsupported,
2083 "[SF] Failed to set hdrMetadata: %s (%d)",
2084 to_string(error).c_str(), static_cast<int32_t>(error));
2085
2086 if (compositionInfo.compositionType == HWC2::Composition::SolidColor) {
2087 error = (compositionInfo.hwc.hwcLayer)->setColor(compositionInfo.hwc.color);
2088 ALOGE_IF(error != HWC2::Error::None,
2089 "[SF] Failed to set color: %s (%d)",
2090 to_string(error).c_str(), static_cast<int32_t>(error));
2091 }
2092
2093 error = (compositionInfo.hwc.hwcLayer)->setVisibleRegion(compositionInfo.hwc.visibleRegion);
2094 ALOGE_IF(error != HWC2::Error::None,
2095 "[SF] Failed to set visible region: %s (%d)",
2096 to_string(error).c_str(), static_cast<int32_t>(error));
2097
2098 error = (compositionInfo.hwc.hwcLayer)->setSurfaceDamage(compositionInfo.hwc.surfaceDamage);
2099 ALOGE_IF(error != HWC2::Error::None,
2100 "[SF] Failed to set surface damage: %s (%d)",
2101 to_string(error).c_str(), static_cast<int32_t>(error));
2102}
2103
2104void SurfaceFlinger::configureDeviceComposition(const CompositionInfo& compositionInfo) const
2105{
2106 HWC2::Error error;
2107
2108 if (compositionInfo.hwc.fence) {
2109 error = (compositionInfo.hwc.hwcLayer)->setBuffer(compositionInfo.mBufferSlot,
2110 compositionInfo.mBuffer, compositionInfo.hwc.fence);
2111 ALOGE_IF(error != HWC2::Error::None,
2112 "[SF] Failed to set buffer: %s (%d)",
2113 to_string(error).c_str(), static_cast<int32_t>(error));
2114 }
2115}
2116
David Sodmanfa9b2af2017-12-24 13:28:59 -08002117void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002118{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002119 bool dirty = !display->getDirtyRegion(false).isEmpty();
2120 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2121 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002122
David Sodmanfa9b2af2017-12-24 13:28:59 -08002123 // If nothing has changed (!dirty), don't recompose.
2124 // If something changed, but we don't currently have any visible layers,
2125 // and didn't when we last did a composition, then skip it this time.
2126 // The second rule does two things:
2127 // - When all layers are removed from a display, we'll emit one black
2128 // frame, then nothing more until we get new layers.
2129 // - When a display is created with a private layer stack, we won't
2130 // emit any black frames until a layer is added to the layer stack.
2131 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002132
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002133 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2134 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002135 mustRecompose ? "doing" : "skipping",
2136 dirty ? "+" : "-",
2137 empty ? "+" : "-",
2138 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002139
David Sodmanfa9b2af2017-12-24 13:28:59 -08002140 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002141
David Sodmanfa9b2af2017-12-24 13:28:59 -08002142 if (mustRecompose) {
2143 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002144 }
2145}
2146
David Sodmanfa9b2af2017-12-24 13:28:59 -08002147void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002148{
David Sodmanfb95bcc2017-12-22 15:45:30 -08002149 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002150 if (!display->isPoweredOn()) {
2151 return;
David Sodman2b406362017-12-15 13:33:47 -08002152 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002153
David Sodmanfb95bcc2017-12-22 15:45:30 -08002154 status_t result = display->prepareFrame(
2155 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08002156 ALOGE_IF(result != NO_ERROR,
2157 "prepareFrame for display %d failed:"
2158 " %d (%s)",
2159 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002160}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002161
David Sodman10a41ff2018-08-05 12:14:17 -07002162void SurfaceFlinger::setUpHWComposer(const CompositionInfo& compositionInfo) {
2163 ATRACE_CALL();
2164 ALOGV("setUpHWComposer");
2165
2166 switch (compositionInfo.compositionType)
2167 {
2168 case HWC2::Composition::Invalid:
2169 case HWC2::Composition::Client:
2170 break;
2171
2172 case HWC2::Composition::Sideband:
2173 configureHwcCommonData(compositionInfo);
2174 configureSidebandComposition(compositionInfo);
2175 break;
2176
2177 case HWC2::Composition::SolidColor:
2178 configureHwcCommonData(compositionInfo);
2179 break;
2180
2181 case HWC2::Composition::Device:
2182 case HWC2::Composition::Cursor:
2183 configureHwcCommonData(compositionInfo);
2184 configureDeviceComposition(compositionInfo);
2185 break;
2186 }
2187}
2188
David Sodmanfa9b2af2017-12-24 13:28:59 -08002189void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002190 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002191 ALOGV("doComposition");
2192
David Sodmanfa9b2af2017-12-24 13:28:59 -08002193 if (display->isPoweredOn()) {
2194 // transform the dirty region into this screen's coordinate space
2195 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002196
David Sodmanfa9b2af2017-12-24 13:28:59 -08002197 // repaint the framebuffer (if needed)
2198 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002199
David Sodmanfa9b2af2017-12-24 13:28:59 -08002200 display->dirtyRegion.clear();
2201 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002202 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002203 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002204}
2205
David Sodmanfa9b2af2017-12-24 13:28:59 -08002206void SurfaceFlinger::postFrame()
2207{
2208 // |mStateLock| not needed as we are on the main thread
2209 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2210 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2211 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2212 logFrameStats();
2213 }
2214 }
2215}
2216
2217void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002218{
Mathias Agopian841cde52012-03-01 15:44:37 -08002219 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002220 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002221
David Sodmanfa9b2af2017-12-24 13:28:59 -08002222 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002223
David Sodmanfa9b2af2017-12-24 13:28:59 -08002224 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002225 const auto displayId = display->getId();
2226 if (displayId >= 0) {
2227 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002228 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002229 display->onSwapBuffersCompleted();
2230 display->makeCurrent();
David Sodman10a41ff2018-08-05 12:14:17 -07002231 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002232 sp<Fence> releaseFence = Fence::NO_FENCE;
Chia-I Wu7b549592017-11-15 09:14:57 -08002233 // The layer buffer from the previous frame (if any) is released
2234 // by HWC only when the release fence from this frame (if any) is
2235 // signaled. Always get the release fence from HWC first.
David Sodman10a41ff2018-08-05 12:14:17 -07002236 auto hwcLayer = compositionInfo.hwc.hwcLayer;
2237 if ((displayId >= 0) && hwcLayer) {
2238 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer.get());
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002239 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002240
2241 // If the layer was client composited in the previous frame, we
2242 // need to merge with the previous client target acquire fence.
2243 // Since we do not track that, always merge with the current
2244 // client target acquire fence when it is available, even though
2245 // this is suboptimal.
David Sodman10a41ff2018-08-05 12:14:17 -07002246 if (compositionInfo.compositionType == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002247 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002248 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002249 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002250
David Sodman10a41ff2018-08-05 12:14:17 -07002251 if (compositionInfo.layer) {
2252 compositionInfo.layer->onLayerDisplayed(releaseFence);
2253 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002254 }
Chia-I Wu83806892017-11-16 10:50:20 -08002255
2256 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002257 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002258 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002259 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002260 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002261 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002262 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002263 }
2264 }
2265
Dominik Laskowski7e045462018-05-30 13:02:02 -07002266 if (displayId >= 0) {
2267 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002268 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002269 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002270}
2271
Mathias Agopian87baae12012-07-31 12:38:26 -07002272void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002273{
Mathias Agopian841cde52012-03-01 15:44:37 -08002274 ATRACE_CALL();
2275
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002276 // here we keep a copy of the drawing state (that is the state that's
2277 // going to be overwritten by handleTransactionLocked()) outside of
2278 // mStateLock so that the side-effects of the State assignment
2279 // don't happen with mStateLock held (which can cause deadlocks).
2280 State drawingState(mDrawingState);
2281
Mathias Agopianca4d3602011-05-19 15:38:14 -07002282 Mutex::Autolock _l(mStateLock);
2283 const nsecs_t now = systemTime();
2284 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002285
Mathias Agopianca4d3602011-05-19 15:38:14 -07002286 // Here we're guaranteed that some transaction flags are set
2287 // so we can call handleTransactionLocked() unconditionally.
2288 // We call getTransactionFlags(), which will also clear the flags,
2289 // with mStateLock held to guarantee that mCurrentState won't change
2290 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002291
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002292 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002293 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002294 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002295
Mathias Agopianca4d3602011-05-19 15:38:14 -07002296 mLastTransactionTime = systemTime() - now;
2297 mDebugInTransaction = 0;
2298 invalidateHwcGeometry();
2299 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002300}
2301
Dominik Laskowski7e045462018-05-30 13:02:02 -07002302DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002303 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002304 // Figure out whether the event is for the primary display or an
2305 // external display by matching the Hwc display id against one for a
2306 // connected display. If we did not find a match, we then check what
2307 // displays are not already connected to determine the type. If we don't
2308 // have a connected primary display, we assume the new display is meant to
2309 // be the primary display, and then if we don't have an external display,
2310 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002311 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2312 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002313 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002314 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002315 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002316 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002317 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002318 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002319 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002320 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002321 return DisplayDevice::DISPLAY_EXTERNAL;
2322 }
2323
2324 return DisplayDevice::DISPLAY_ID_INVALID;
2325}
2326
Lloyd Piqueba04e622017-12-14 17:11:26 -08002327void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2328 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002329 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002330 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002331 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002332 continue;
2333 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002334
2335 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2336 ALOGE("External displays are not supported by the vr hardware composer.");
2337 continue;
2338 }
2339
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002340 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002341 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002342 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002343 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002344 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002345
2346 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002347 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002348 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002349 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002350 DisplayDeviceState info;
2351 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002352 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2353 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002354 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002355 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002356 mInterceptor->saveDisplayCreation(info);
2357 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002358 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002359 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002360
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002361 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002362 if (idx >= 0) {
2363 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002364 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002365 mCurrentState.displays.removeItemsAt(idx);
2366 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002367 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002368 }
2369
2370 processDisplayChangesLocked();
2371 }
2372
2373 mPendingHotplugEvents.clear();
2374}
2375
Lloyd Pique99d3da52018-01-22 17:48:03 -08002376sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002377 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002378 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002379 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002380 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002381 HdrCapabilities hdrCapabilities;
2382 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002383
Peiyong Lin13effd12018-07-24 17:01:47 -07002384 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002385 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002386 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002387 if (isWideColorMode(colorMode)) {
2388 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002389 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002390
Dominik Laskowski7e045462018-05-30 13:02:02 -07002391 std::vector<RenderIntent> renderIntents =
2392 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002393 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002394 }
tangrobin6753a022018-08-10 10:58:54 +08002395 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002396
tangrobin6753a022018-08-10 10:58:54 +08002397 if (displayId >= 0) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002398 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2399 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2400 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002401
2402 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2403 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2404
2405 /*
2406 * Create our display's surface
2407 */
2408 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2409 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002410 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002411 renderSurface->setNativeWindow(nativeWindow.get());
2412 const int displayWidth = renderSurface->queryWidth();
2413 const int displayHeight = renderSurface->queryHeight();
2414
2415 // Make sure that composition can never be stalled by a virtual display
2416 // consumer that isn't processing buffers fast enough. We have to do this
2417 // in two places:
2418 // * Here, in case the display is composed entirely by HWC.
2419 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2420 // window's swap interval in eglMakeCurrent, so they'll override the
2421 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002422 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002423 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2424 }
2425
2426 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002427 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002428
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002429 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002430 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2431 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2432 displayHeight, hasWideColorGamut, hdrCapabilities,
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002433 supportedPerFrameMetadata, hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002434
2435 if (maxFrameBufferAcquiredBuffers >= 3) {
2436 nativeWindowSurface->preallocateBuffers();
2437 }
2438
2439 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002440 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2441 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002442 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002443 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002444 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002445 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002446 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002447 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002448 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002449 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002450 display->setLayerStack(state.layerStack);
2451 display->setProjection(state.orientation, state.viewport, state.frame);
2452 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002453
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002454 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002455}
2456
Lloyd Pique347200f2017-12-14 17:00:15 -08002457void SurfaceFlinger::processDisplayChangesLocked() {
2458 // here we take advantage of Vector's copy-on-write semantics to
2459 // improve performance by skipping the transaction entirely when
2460 // know that the lists are identical
2461 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2462 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2463 if (!curr.isIdenticalTo(draw)) {
2464 mVisibleRegionsDirty = true;
2465 const size_t cc = curr.size();
2466 size_t dc = draw.size();
2467
2468 // find the displays that were removed
2469 // (ie: in drawing state but not in current state)
2470 // also handle displays that changed
2471 // (ie: displays that are in both lists)
2472 for (size_t i = 0; i < dc;) {
2473 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2474 if (j < 0) {
2475 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002476 // Call makeCurrent() on the primary display so we can
2477 // be sure that nothing associated with this display
2478 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002479 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2480 defaultDisplay->makeCurrent();
2481 }
2482 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2483 display->disconnect(getHwComposer());
2484 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002485 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2486 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2487 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2488 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2489 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002490 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002491 } else {
2492 // this display is in both lists. see if something changed.
2493 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002494 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002495 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2496 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2497 if (state_binder != draw_binder) {
2498 // changing the surface is like destroying and
2499 // recreating the DisplayDevice, so we just remove it
2500 // from the drawing state, so that it get re-added
2501 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002502 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2503 display->disconnect(getHwComposer());
2504 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002505 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002506 mDrawingState.displays.removeItemsAt(i);
2507 dc--;
2508 // at this point we must loop to the next item
2509 continue;
2510 }
2511
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002512 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002513 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002514 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002515 }
2516 if ((state.orientation != draw[i].orientation) ||
2517 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002518 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002519 }
2520 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002521 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002522 }
2523 }
2524 }
2525 ++i;
2526 }
2527
2528 // find displays that were added
2529 // (ie: in current state but not in drawing state)
2530 for (size_t i = 0; i < cc; i++) {
2531 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2532 const DisplayDeviceState& state(curr[i]);
2533
2534 sp<DisplaySurface> dispSurface;
2535 sp<IGraphicBufferProducer> producer;
2536 sp<IGraphicBufferProducer> bqProducer;
2537 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002538 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002539
Dominik Laskowski7e045462018-05-30 13:02:02 -07002540 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002541 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002542 // Virtual displays without a surface are dormant:
2543 // they have external state (layer stack, projection,
2544 // etc.) but no internal state (i.e. a DisplayDevice).
2545 if (state.surface != nullptr) {
2546 // Allow VR composer to use virtual displays.
2547 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2548 int width = 0;
2549 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2550 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2551 int height = 0;
2552 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2553 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2554 int intFormat = 0;
2555 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2556 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002557 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002558
Dominik Laskowski7e045462018-05-30 13:02:02 -07002559 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2560 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002561 }
2562
2563 // TODO: Plumb requested format back up to consumer
2564
2565 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002566 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002567 bqProducer, bqConsumer,
2568 state.displayName);
2569
2570 dispSurface = vds;
2571 producer = vds;
2572 }
2573 } else {
2574 ALOGE_IF(state.surface != nullptr,
2575 "adding a supported display, but rendering "
2576 "surface is provided (%p), ignoring it",
2577 state.surface.get());
2578
Dominik Laskowski7e045462018-05-30 13:02:02 -07002579 displayId = state.type;
2580 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002581 producer = bqProducer;
2582 }
2583
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002584 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002585 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002586 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002587 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002588 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002589 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002590 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2591 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2592 true);
2593 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2594 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2595 true);
2596 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002597 }
2598 }
2599 }
2600 }
2601 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002602
2603 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002604}
2605
Mathias Agopian87baae12012-07-31 12:38:26 -07002606void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002607{
Dan Stoza7dde5992015-05-22 09:51:44 -07002608 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002609 mCurrentState.traverseInZOrder([](Layer* layer) {
2610 layer->notifyAvailableFrames();
2611 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002612
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002613 /*
2614 * Traversal of the children
2615 * (perform the transaction for each of them if needed)
2616 */
2617
Mathias Agopian3559b072012-08-15 13:46:03 -07002618 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002619 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002620 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002621 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002622
2623 const uint32_t flags = layer->doTransaction(0);
2624 if (flags & Layer::eVisibleRegion)
2625 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002626 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002627 }
2628
2629 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002630 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002631 */
2632
Mathias Agopiane57f2922012-08-09 16:29:12 -07002633 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002634 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002635 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002636 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002637
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002638 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002639 // The transform hint might have changed for some layers
2640 // (either because a display has changed, or because a layer
2641 // as changed).
2642 //
2643 // Walk through all the layers in currentLayers,
2644 // and update their transform hint.
2645 //
2646 // If a layer is visible only on a single display, then that
2647 // display is used to calculate the hint, otherwise we use the
2648 // default display.
2649 //
2650 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2651 // the hint is set before we acquire a buffer from the surface texture.
2652 //
2653 // NOTE: layer transactions have taken place already, so we use their
2654 // drawing state. However, SurfaceFlinger's own transaction has not
2655 // happened yet, so we must use the current state layer list
2656 // (soon to become the drawing state list).
2657 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002658 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002659 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002660 bool first = true;
2661 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002662 // NOTE: we rely on the fact that layers are sorted by
2663 // layerStack first (so we don't have to traverse the list
2664 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002665 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002666 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002667 currentlayerStack = layerStack;
2668 // figure out if this layerstack is mirrored
2669 // (more than one display) if so, pick the default display,
2670 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002671 hintDisplay = nullptr;
2672 for (const auto& [token, display] : mDisplays) {
2673 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2674 if (hintDisplay) {
2675 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002676 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002677 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002678 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002679 }
2680 }
2681 }
2682 }
Chet Haase91d25932013-04-11 15:24:55 -07002683
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002684 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002685 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2686 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002687
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002688 // could be null when this layer is using a layerStack
2689 // that is not visible on any display. Also can occur at
2690 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002691 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002692 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002693
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002694 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002695 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002696 if (hintDisplay) {
2697 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002698 }
Robert Carr2047fae2016-11-28 14:09:09 -08002699
2700 first = false;
2701 });
Mathias Agopian84300952012-11-21 16:02:13 -08002702 }
2703
2704
Mathias Agopian3559b072012-08-15 13:46:03 -07002705 /*
2706 * Perform our own transaction if needed
2707 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002708
2709 if (mLayersAdded) {
2710 mLayersAdded = false;
2711 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002712 mVisibleRegionsDirty = true;
2713 }
2714
2715 // some layers might have been removed, so
2716 // we need to update the regions they're exposing.
2717 if (mLayersRemoved) {
2718 mLayersRemoved = false;
2719 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002720 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002721 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002722 // this layer is not visible anymore
2723 // TODO: we could traverse the tree from front to back and
2724 // compute the actual visible region
2725 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002726 Region visibleReg;
2727 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002728 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002729 }
Robert Carr2047fae2016-11-28 14:09:09 -08002730 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002731 }
2732
2733 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002734
2735 updateCursorAsync();
2736}
2737
2738void SurfaceFlinger::updateCursorAsync()
2739{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002740 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002741 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002742 continue;
2743 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002744
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002745 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2746 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002747 }
2748 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002749}
2750
2751void SurfaceFlinger::commitTransaction()
2752{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002753 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002754 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002755 for (const auto& l : mLayersPendingRemoval) {
2756 recordBufferingStats(l->getName().string(),
2757 l->getOccupancyHistory(true));
2758 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002759 }
2760 mLayersPendingRemoval.clear();
2761 }
2762
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002763 // If this transaction is part of a window animation then the next frame
2764 // we composite should be considered an animation as well.
2765 mAnimCompositionPending = mAnimTransactionPending;
2766
Mathias Agopian4fec8732012-06-29 14:12:52 -07002767 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002768 // clear the "changed" flags in current state
2769 mCurrentState.colorMatrixChanged = false;
2770
Robert Carr1f0a16a2016-10-24 16:27:39 -07002771 mDrawingState.traverseInZOrder([](Layer* layer) {
2772 layer->commitChildList();
2773 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002774 mTransactionPending = false;
2775 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002776 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002777}
2778
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002779void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2780 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002781 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002782 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002783
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002784 Region aboveOpaqueLayers;
2785 Region aboveCoveredLayers;
2786 Region dirty;
2787
Mathias Agopian87baae12012-07-31 12:38:26 -07002788 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002789
Robert Carr2047fae2016-11-28 14:09:09 -08002790 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002791 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002792 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002793
Jesse Hall01e29052013-02-19 16:13:35 -08002794 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002795 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002796 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002797 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002798
Mathias Agopianab028732010-03-16 16:41:46 -07002799 /*
2800 * opaqueRegion: area of a surface that is fully opaque.
2801 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002802 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002803
2804 /*
2805 * visibleRegion: area of a surface that is visible on screen
2806 * and not fully transparent. This is essentially the layer's
2807 * footprint minus the opaque regions above it.
2808 * Areas covered by a translucent surface are considered visible.
2809 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002810 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002811
2812 /*
2813 * coveredRegion: area of a surface that is covered by all
2814 * visible regions above it (which includes the translucent areas).
2815 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002816 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002817
Jesse Halla8026d22012-09-25 13:25:04 -07002818 /*
2819 * transparentRegion: area of a surface that is hinted to be completely
2820 * transparent. This is only used to tell when the layer has no visible
2821 * non-transparent regions and can be removed from the layer list. It
2822 * does not affect the visibleRegion of this layer or any layers
2823 * beneath it. The hint may not be correct if apps don't respect the
2824 * SurfaceView restrictions (which, sadly, some don't).
2825 */
2826 Region transparentRegion;
2827
Mathias Agopianab028732010-03-16 16:41:46 -07002828
2829 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002830 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002831 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002832 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002833 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002834 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002835 if (!visibleRegion.isEmpty()) {
2836 // Remove the transparent area from the visible region
2837 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002838 if (tr.preserveRects()) {
2839 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002840 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002841 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002842 // transformation too complex, can't do the
2843 // transparent region optimization.
2844 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002845 }
Mathias Agopianab028732010-03-16 16:41:46 -07002846 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002847
Mathias Agopianab028732010-03-16 16:41:46 -07002848 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002849 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002850 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002851 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002852 // the opaque region is the layer's footprint
2853 opaqueRegion = visibleRegion;
2854 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002855 }
2856 }
2857
Robert Carre5f4f692018-01-12 13:12:28 -08002858 if (visibleRegion.isEmpty()) {
2859 layer->clearVisibilityRegions();
2860 return;
2861 }
2862
Mathias Agopianab028732010-03-16 16:41:46 -07002863 // Clip the covered region to the visible region
2864 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2865
2866 // Update aboveCoveredLayers for next (lower) layer
2867 aboveCoveredLayers.orSelf(visibleRegion);
2868
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002869 // subtract the opaque region covered by the layers above us
2870 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002871
2872 // compute this layer's dirty region
2873 if (layer->contentDirty) {
2874 // we need to invalidate the whole region
2875 dirty = visibleRegion;
2876 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002877 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002878 layer->contentDirty = false;
2879 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002880 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002881 * the exposed region consists of two components:
2882 * 1) what's VISIBLE now and was COVERED before
2883 * 2) what's EXPOSED now less what was EXPOSED before
2884 *
2885 * note that (1) is conservative, we start with the whole
2886 * visible region but only keep what used to be covered by
2887 * something -- which mean it may have been exposed.
2888 *
2889 * (2) handles areas that were not covered by anything but got
2890 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002891 */
Mathias Agopianab028732010-03-16 16:41:46 -07002892 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002893 const Region oldVisibleRegion = layer->visibleRegion;
2894 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002895 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2896 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002897 }
2898 dirty.subtractSelf(aboveOpaqueLayers);
2899
2900 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002901 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002902
Mathias Agopianab028732010-03-16 16:41:46 -07002903 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002904 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002905
Jesse Halla8026d22012-09-25 13:25:04 -07002906 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002907 layer->setVisibleRegion(visibleRegion);
2908 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002909 layer->setVisibleNonTransparentRegion(
2910 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002911 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002912
Mathias Agopian87baae12012-07-31 12:38:26 -07002913 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002914}
2915
Chia-I Wuab0c3192017-08-01 11:29:00 -07002916void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002917 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002918 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2919 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002920 }
2921 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002922}
2923
Dan Stoza6b9454d2014-11-07 16:00:59 -08002924bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002925{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002926 ALOGV("handlePageFlip");
2927
Brian Andersond6927fb2016-07-23 23:37:30 -07002928 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002929
Mathias Agopian4fec8732012-06-29 14:12:52 -07002930 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002931 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002932 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002933
2934 // Store the set of layers that need updates. This set must not change as
2935 // buffers are being latched, as this could result in a deadlock.
2936 // Example: Two producers share the same command stream and:
2937 // 1.) Layer 0 is latched
2938 // 2.) Layer 0 gets a new frame
2939 // 2.) Layer 1 gets a new frame
2940 // 3.) Layer 1 is latched.
2941 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2942 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002943 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002944 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002945 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07002946 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002947 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002948 } else {
2949 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002950 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002951 } else {
2952 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002953 }
Robert Carr2047fae2016-11-28 14:09:09 -08002954 });
2955
Dan Stoza9e56aa02015-11-02 13:00:03 -08002956 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002957 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002958 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002959 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002960 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002961 newDataLatched = true;
2962 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002963 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002964
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002965 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002966
2967 // If we will need to wake up at some time in the future to deal with a
2968 // queued frame that shouldn't be displayed during this vsync period, wake
2969 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002970 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002971 signalLayerUpdate();
2972 }
2973
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002974 // enter boot animation on first buffer latch
2975 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2976 ALOGI("Enter boot animation");
2977 mBootStage = BootStage::BOOTANIMATION;
2978 }
2979
Dan Stoza6b9454d2014-11-07 16:00:59 -08002980 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002981 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002982}
2983
Mathias Agopianad456f92011-01-13 17:53:01 -08002984void SurfaceFlinger::invalidateHwcGeometry()
2985{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002986 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002987}
2988
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002989void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2990 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002991 // We only need to actually compose the display if:
2992 // 1) It is being handled by hardware composer, which may need this to
2993 // keep its virtual display state machine in sync, or
2994 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002995 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002996 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002997 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002998 return;
2999 }
3000
Dan Stoza9e56aa02015-11-02 13:00:03 -08003001 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003002 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003003
3004 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003005 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003006}
3007
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003008bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003009 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003010
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003011 const Region bounds(display->bounds());
3012 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003013 const auto displayId = display->getId();
3014 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003015 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003016
Chia-I Wu8e50e692018-05-04 10:12:37 -07003017 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003018 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003019
Dan Stoza9e56aa02015-11-02 13:00:03 -08003020 if (hasClientComposition) {
3021 ALOGV("hasClientComposition");
3022
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003023 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003024 if (display->hasWideColorGamut()) {
3025 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003026 }
3027 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003028 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003029 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003030
Dominik Laskowski7e045462018-05-30 13:02:02 -07003031 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003032 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3033 HWC2::Capability::SkipClientColorTransform);
3034
Chia-I Wud49d6692018-06-27 07:17:41 +08003035 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003036 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3037 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003038 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003039 }
3040
Chia-I Wud49d6692018-06-27 07:17:41 +08003041 // The current enhanced saturation matrix is designed to enhance Display P3,
3042 // thus we only apply this matrix when the render intent is not colorimetric
3043 // and the output color space is Display P3.
3044 needsEnhancedColorMatrix =
3045 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3046 outputDataspace == Dataspace::DISPLAY_P3);
3047 if (needsEnhancedColorMatrix) {
3048 colorMatrix *= mEnhancedSaturationMatrix;
3049 }
3050
3051 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003052
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003053 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003054 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003055 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003056 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003057
3058 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003059 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3060 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3061 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003062 }
3063 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003064 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003065
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003066 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003067 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003068 // when using overlays, we assume a fully transparent framebuffer
3069 // NOTE: we could reduce how much we need to clear, for instance
3070 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003071 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003072 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003073 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003074 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003075 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003076 // we're left with the letterbox region
3077 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003078 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003079
3080 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003081 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003082
Mathias Agopianb9494d52012-04-18 02:28:45 -07003083 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003084 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003085 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003086 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003087 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003088 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003089
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003090 const Rect& bounds = display->getBounds();
3091 const Rect& scissor = display->getScissor();
3092 if (scissor != bounds) {
3093 // scissor doesn't match the screen's dimensions, so we
3094 // need to clear everything outside of it and enable
3095 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003096
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003097 // enable scissor for this frame
3098 const uint32_t height = display->getHeight();
3099 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
3100 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003101 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003102 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003103
Mathias Agopian85d751c2012-08-29 16:59:24 -07003104 /*
3105 * and then, render the layers targeted at the framebuffer
3106 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003107
Dan Stoza9e56aa02015-11-02 13:00:03 -08003108 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003109 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003110 bool firstLayer = true;
David Sodmanfb95bcc2017-12-22 15:45:30 -08003111 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
3112 const Region bounds(display->bounds());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003113 const Region clip(bounds.intersect(
David Sodmanfb95bcc2017-12-22 15:45:30 -08003114 displayTransform.transform(compositionInfo.layer->mLayer->visibleRegion)));
3115 ALOGV("Layer: %s", compositionInfo.layerName.c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003116 if (!clip.isEmpty()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08003117 switch (compositionInfo.compositionType) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003118 case HWC2::Composition::Cursor:
3119 case HWC2::Composition::Device:
3120 case HWC2::Composition::Sideband:
3121 case HWC2::Composition::SolidColor: {
David Sodmanfb95bcc2017-12-22 15:45:30 -08003122 const Layer::State& state(compositionInfo.layer->mLayer->getDrawingState());
3123 const bool opaque = compositionInfo.layer->mLayer->isOpaque(state);
3124 if (compositionInfo.hwc.clearClientTarget && !firstLayer &&
3125 opaque && (state.color.a == 1.0f) && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003126 // never clear the very first layer since we're
3127 // guaranteed the FB is already cleared
David Sodman10a41ff2018-08-05 12:14:17 -07003128 compositionInfo.layer->clear(getRenderEngine());
Mathias Agopiancd60f992012-08-16 16:28:27 -07003129 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003130 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003131 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003132 case HWC2::Composition::Client: {
David Sodmanfb95bcc2017-12-22 15:45:30 -08003133 compositionInfo.layer->mLayer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003134 break;
3135 }
3136 default:
3137 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003138 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003139 } else {
3140 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003141 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003142 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003143 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003144
Chia-I Wud49d6692018-06-27 07:17:41 +08003145 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003146 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003147 }
3148
Mathias Agopianf45c5102012-10-24 16:29:17 -07003149 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003150 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003151 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003152}
3153
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003154void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
3155 const Region& region) const {
3156 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003157 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003158 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003159}
3160
Dan Stoza7d89d062015-04-30 13:29:25 -07003161status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003162 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003163 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003164 const sp<Layer>& lbc,
3165 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003166{
Dan Stoza7d89d062015-04-30 13:29:25 -07003167 // add this layer to the current state list
3168 {
3169 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003170 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003171 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3172 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003173 return NO_MEMORY;
3174 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003175 if (parent == nullptr) {
3176 mCurrentState.layersSortedByZ.add(lbc);
3177 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003178 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003179 ALOGE("addClientLayer called with a removed parent");
3180 return NAME_NOT_FOUND;
3181 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003182 parent->addChild(lbc);
3183 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003184
Yiwei Zhang243b3782018-05-15 17:40:04 -07003185 if (gbc != nullptr) {
3186 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3187 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3188 mMaxGraphicBufferProducerListSize,
3189 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3190 mGraphicBufferProducerList.size(),
3191 mMaxGraphicBufferProducerListSize, mNumLayers);
3192 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003193 mLayersAdded = true;
3194 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003195 }
3196
Mathias Agopian96f08192010-06-02 23:28:45 -07003197 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003198 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003199
Dan Stoza7d89d062015-04-30 13:29:25 -07003200 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003201}
3202
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003203status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003204 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003205 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3206}
Robert Carr7f9b8992017-03-10 11:08:39 -08003207
chaviwca27f252018-02-06 16:46:39 -08003208status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3209 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003210 if (layer->isPendingRemoval()) {
3211 return NO_ERROR;
3212 }
3213
Robert Carr1f0a16a2016-10-24 16:27:39 -07003214 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003215 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003216 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003217 if (topLevelOnly) {
3218 return NO_ERROR;
3219 }
3220
Chia-I Wu98f1c102017-05-30 14:54:08 -07003221 sp<Layer> ancestor = p;
3222 while (ancestor->getParent() != nullptr) {
3223 ancestor = ancestor->getParent();
3224 }
3225 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3226 ALOGE("removeLayer called with a layer whose parent has been removed");
3227 return NAME_NOT_FOUND;
3228 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003229
3230 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003231 } else {
3232 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003233 }
3234
Robert Carr136e2f62017-02-08 17:54:29 -08003235 // As a matter of normal operation, the LayerCleaner will produce a second
3236 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3237 // so we will succeed in promoting it, but it's already been removed
3238 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3239 // otherwise something has gone wrong and we are leaking the layer.
3240 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003241 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3242 layer->getName().string(),
3243 (p != nullptr) ? p->getName().string() : "no-parent");
3244 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003245 } else if (index < 0) {
3246 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003247 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003248
Chia-I Wuc6657022017-08-15 11:18:17 -07003249 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003250 mLayersPendingRemoval.add(layer);
3251 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003252 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003253 setTransactionFlags(eTransactionNeeded);
3254 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003255}
3256
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003257uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003258 return android_atomic_release_load(&mTransactionFlags);
3259}
3260
Mathias Agopian3f844832013-08-07 21:24:32 -07003261uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003262 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3263}
3264
Mathias Agopian3f844832013-08-07 21:24:32 -07003265uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003266 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3267}
3268
3269uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3270 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003271 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003272 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003273 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003274 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003275 }
3276 return old;
3277}
3278
chaviwca27f252018-02-06 16:46:39 -08003279bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3280 for (const ComposerState& state : states) {
3281 // Here we need to check that the interface we're given is indeed
3282 // one of our own. A malicious client could give us a nullptr
3283 // IInterface, or one of its own or even one of our own but a
3284 // different type. All these situations would cause us to crash.
3285 if (state.client == nullptr) {
3286 return true;
3287 }
3288
3289 sp<IBinder> binder = IInterface::asBinder(state.client);
3290 if (binder == nullptr) {
3291 return true;
3292 }
3293
3294 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3295 return true;
3296 }
3297 }
3298 return false;
3299}
3300
Mathias Agopian8b33f032012-07-24 20:43:54 -07003301void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003302 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003303 const Vector<DisplayState>& displays,
3304 uint32_t flags)
3305{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003306 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003307 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003308 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003309
chaviwca27f252018-02-06 16:46:39 -08003310 if (containsAnyInvalidClientState(states)) {
3311 return;
3312 }
3313
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003314 if (flags & eAnimation) {
3315 // For window updates that are part of an animation we must wait for
3316 // previous animation "frames" to be handled.
3317 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003318 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003319 if (CC_UNLIKELY(err != NO_ERROR)) {
3320 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003321 // caller after a few seconds.
3322 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3323 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003324 mAnimTransactionPending = false;
3325 break;
3326 }
3327 }
3328 }
3329
chaviwca27f252018-02-06 16:46:39 -08003330 for (const DisplayState& display : displays) {
3331 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003332 }
3333
chaviwca27f252018-02-06 16:46:39 -08003334 for (const ComposerState& state : states) {
3335 transactionFlags |= setClientStateLocked(state);
3336 }
3337
3338 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3339 // as destroyed should only occur after setting all other states. This is to allow for a
3340 // child re-parent to happen before marking its original parent as destroyed (which would
3341 // then mark the child as destroyed).
3342 for (const ComposerState& state : states) {
3343 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003344 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003345
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003346 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3347 // anyway. This can be used as a flush mechanism for previous async transactions.
3348 // Empty animation transaction can be used to simulate back-pressure, so also force a
3349 // transaction for empty animation transactions.
3350 if (transactionFlags == 0 &&
3351 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003352 transactionFlags = eTransactionNeeded;
3353 }
3354
Mathias Agopian386aa982011-11-07 21:58:03 -08003355 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003356 if (mInterceptor->isEnabled()) {
3357 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003358 }
Irvel468051e2016-06-13 16:44:44 -07003359
Mathias Agopian386aa982011-11-07 21:58:03 -08003360 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003361 const auto start = (flags & eEarlyWakeup)
3362 ? VSyncModulator::TransactionStart::EARLY
3363 : VSyncModulator::TransactionStart::NORMAL;
3364 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003365
3366 // if this is a synchronous transaction, wait for it to take effect
3367 // before returning.
3368 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003369 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003370 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003371 if (flags & eAnimation) {
3372 mAnimTransactionPending = true;
3373 }
3374 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003375 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3376 if (CC_UNLIKELY(err != NO_ERROR)) {
3377 // just in case something goes wrong in SF, return to the
3378 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003379 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3380 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003381 break;
3382 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003383 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003384 }
3385}
3386
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003387uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3388 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3389 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003390
Mathias Agopiane57f2922012-08-09 16:29:12 -07003391 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003392 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3393
3394 const uint32_t what = s.what;
3395 if (what & DisplayState::eSurfaceChanged) {
3396 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3397 state.surface = s.surface;
3398 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003399 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003400 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003401 if (what & DisplayState::eLayerStackChanged) {
3402 if (state.layerStack != s.layerStack) {
3403 state.layerStack = s.layerStack;
3404 flags |= eDisplayTransactionNeeded;
3405 }
3406 }
3407 if (what & DisplayState::eDisplayProjectionChanged) {
3408 if (state.orientation != s.orientation) {
3409 state.orientation = s.orientation;
3410 flags |= eDisplayTransactionNeeded;
3411 }
3412 if (state.frame != s.frame) {
3413 state.frame = s.frame;
3414 flags |= eDisplayTransactionNeeded;
3415 }
3416 if (state.viewport != s.viewport) {
3417 state.viewport = s.viewport;
3418 flags |= eDisplayTransactionNeeded;
3419 }
3420 }
3421 if (what & DisplayState::eDisplaySizeChanged) {
3422 if (state.width != s.width) {
3423 state.width = s.width;
3424 flags |= eDisplayTransactionNeeded;
3425 }
3426 if (state.height != s.height) {
3427 state.height = s.height;
3428 flags |= eDisplayTransactionNeeded;
3429 }
3430 }
3431
Mathias Agopiane57f2922012-08-09 16:29:12 -07003432 return flags;
3433}
3434
Robert Carrd4ae7f32018-06-07 16:10:57 -07003435bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3436 IPCThreadState* ipc = IPCThreadState::self();
3437 const int pid = ipc->getCallingPid();
3438 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003439 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003440 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003441 return false;
3442 }
3443 return true;
3444}
3445
chaviwca27f252018-02-06 16:46:39 -08003446uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3447 const layer_state_t& s = composerState.state;
3448 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3449
Mathias Agopian13127d82013-03-05 17:47:11 -08003450 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003451 if (layer == nullptr) {
3452 return 0;
3453 }
3454
3455 if (layer->isPendingRemoval()) {
3456 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3457 return 0;
3458 }
3459
3460 uint32_t flags = 0;
3461
3462 const uint32_t what = s.what;
3463 bool geometryAppliesWithResize =
3464 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003465
3466 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3467 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003468 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003469 layer->pushPendingState();
3470 }
3471
chaviw8b3871a2017-11-01 17:41:01 -07003472 if (what & layer_state_t::ePositionChanged) {
3473 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3474 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003475 }
chaviw8b3871a2017-11-01 17:41:01 -07003476 }
3477 if (what & layer_state_t::eLayerChanged) {
3478 // NOTE: index needs to be calculated before we update the state
3479 const auto& p = layer->getParent();
3480 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003481 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003482 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003483 mCurrentState.layersSortedByZ.removeAt(idx);
3484 mCurrentState.layersSortedByZ.add(layer);
3485 // we need traversal (state changed)
3486 // AND transaction (list changed)
3487 flags |= eTransactionNeeded|eTraversalNeeded;
3488 }
chaviw8b3871a2017-11-01 17:41:01 -07003489 } else {
3490 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003491 flags |= eTransactionNeeded|eTraversalNeeded;
3492 }
3493 }
chaviw8b3871a2017-11-01 17:41:01 -07003494 }
3495 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003496 // NOTE: index needs to be calculated before we update the state
3497 const auto& p = layer->getParent();
3498 if (p == nullptr) {
3499 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3500 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3501 mCurrentState.layersSortedByZ.removeAt(idx);
3502 mCurrentState.layersSortedByZ.add(layer);
3503 // we need traversal (state changed)
3504 // AND transaction (list changed)
3505 flags |= eTransactionNeeded|eTraversalNeeded;
3506 }
3507 } else {
3508 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3509 flags |= eTransactionNeeded|eTraversalNeeded;
3510 }
chaviw8b3871a2017-11-01 17:41:01 -07003511 }
3512 }
3513 if (what & layer_state_t::eSizeChanged) {
3514 if (layer->setSize(s.w, s.h)) {
3515 flags |= eTraversalNeeded;
3516 }
3517 }
3518 if (what & layer_state_t::eAlphaChanged) {
3519 if (layer->setAlpha(s.alpha))
3520 flags |= eTraversalNeeded;
3521 }
3522 if (what & layer_state_t::eColorChanged) {
3523 if (layer->setColor(s.color))
3524 flags |= eTraversalNeeded;
3525 }
3526 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003527 // TODO: b/109894387
3528 //
3529 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3530 // rotation. To see the problem observe that if we have a square parent, and a child
3531 // of the same size, then we rotate the child 45 degrees around it's center, the child
3532 // must now be cropped to a non rectangular 8 sided region.
3533 //
3534 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3535 // private API, and the WindowManager only uses rotation in one case, which is on a top
3536 // level layer in which cropping is not an issue.
3537 //
3538 // However given that abuse of rotation matrices could lead to surfaces extending outside
3539 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3540 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3541 // transformations.
3542 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003543 flags |= eTraversalNeeded;
3544 }
3545 if (what & layer_state_t::eTransparentRegionChanged) {
3546 if (layer->setTransparentRegionHint(s.transparentRegion))
3547 flags |= eTraversalNeeded;
3548 }
3549 if (what & layer_state_t::eFlagsChanged) {
3550 if (layer->setFlags(s.flags, s.mask))
3551 flags |= eTraversalNeeded;
3552 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003553 if (what & layer_state_t::eCropChanged_legacy) {
3554 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003555 flags |= eTraversalNeeded;
3556 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003557 if (what & layer_state_t::eFinalCropChanged_legacy) {
3558 if (layer->setFinalCrop_legacy(s.finalCrop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003559 flags |= eTraversalNeeded;
3560 }
3561 if (what & layer_state_t::eLayerStackChanged) {
3562 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3563 // We only allow setting layer stacks for top level layers,
3564 // everything else inherits layer stack from its parent.
3565 if (layer->hasParent()) {
3566 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3567 layer->getName().string());
3568 } else if (idx < 0) {
3569 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3570 "that also does not appear in the top level layer list. Something"
3571 " has gone wrong.", layer->getName().string());
3572 } else if (layer->setLayerStack(s.layerStack)) {
3573 mCurrentState.layersSortedByZ.removeAt(idx);
3574 mCurrentState.layersSortedByZ.add(layer);
3575 // we need traversal (state changed)
3576 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003577 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003578 }
3579 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003580 if (what & layer_state_t::eDeferTransaction_legacy) {
3581 if (s.barrierHandle_legacy != nullptr) {
3582 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3583 } else if (s.barrierGbp_legacy != nullptr) {
3584 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003585 if (authenticateSurfaceTextureLocked(gbp)) {
3586 const auto& otherLayer =
3587 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003588 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003589 } else {
3590 ALOGE("Attempt to defer transaction to to an"
3591 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003592 }
3593 }
chaviw8b3871a2017-11-01 17:41:01 -07003594 // We don't trigger a traversal here because if no other state is
3595 // changed, we don't want this to cause any more work
3596 }
3597 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003598 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003599 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003600 if (!hadParent) {
3601 mCurrentState.layersSortedByZ.remove(layer);
3602 }
chaviw8b3871a2017-11-01 17:41:01 -07003603 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003604 }
chaviw8b3871a2017-11-01 17:41:01 -07003605 }
3606 if (what & layer_state_t::eReparentChildren) {
3607 if (layer->reparentChildren(s.reparentHandle)) {
3608 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003609 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003610 }
chaviw8b3871a2017-11-01 17:41:01 -07003611 if (what & layer_state_t::eDetachChildren) {
3612 layer->detachChildren();
3613 }
3614 if (what & layer_state_t::eOverrideScalingModeChanged) {
3615 layer->setOverrideScalingMode(s.overrideScalingMode);
3616 // We don't trigger a traversal here because if no other state is
3617 // changed, we don't want this to cause any more work
3618 }
Marissa Wall61c58622018-07-18 10:12:20 -07003619 if (what & layer_state_t::eTransformChanged) {
3620 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3621 }
3622 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3623 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3624 flags |= eTraversalNeeded;
3625 }
3626 if (what & layer_state_t::eCropChanged) {
3627 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3628 }
3629 if (what & layer_state_t::eBufferChanged) {
3630 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3631 }
3632 if (what & layer_state_t::eAcquireFenceChanged) {
3633 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3634 }
3635 if (what & layer_state_t::eDataspaceChanged) {
3636 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3637 }
3638 if (what & layer_state_t::eHdrMetadataChanged) {
3639 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3640 }
3641 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3642 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3643 }
3644 if (what & layer_state_t::eApiChanged) {
3645 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3646 }
3647 if (what & layer_state_t::eSidebandStreamChanged) {
3648 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3649 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003650 return flags;
3651}
3652
chaviwca27f252018-02-06 16:46:39 -08003653void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3654 const layer_state_t& state = composerState.state;
3655 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3656
3657 sp<Layer> layer(client->getLayerUser(state.surface));
3658 if (layer == nullptr) {
3659 return;
3660 }
3661
3662 if (layer->isPendingRemoval()) {
3663 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3664 return;
3665 }
3666
3667 if (state.what & layer_state_t::eDestroySurface) {
3668 removeLayerLocked(mStateLock, layer);
3669 }
3670}
3671
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003672status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003673 const String8& name,
3674 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003675 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003676 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003677 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003678{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003679 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003680 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003681 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003682 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003683 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003684
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003685 status_t result = NO_ERROR;
3686
3687 sp<Layer> layer;
3688
Cody Northropbc755282017-03-31 12:00:08 -06003689 String8 uniqueName = getUniqueLayerName(name);
3690
Mathias Agopian3165cc22012-08-08 19:42:09 -07003691 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003692 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003693 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3694 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003695
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003696 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003697 case ISurfaceComposerClient::eFXSurfaceBufferState:
3698 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3699 break;
chaviw13fdc492017-06-27 12:40:18 -07003700 case ISurfaceComposerClient::eFXSurfaceColor:
3701 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003702 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003703 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003704 break;
3705 default:
3706 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003707 break;
3708 }
3709
Dan Stoza7d89d062015-04-30 13:29:25 -07003710 if (result != NO_ERROR) {
3711 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003712 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003713
Chia-I Wuab0c3192017-08-01 11:29:00 -07003714 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3715 // TODO b/64227542
3716 if (windowType == 441731) {
3717 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3718 layer->setPrimaryDisplayOnly();
3719 }
3720
Albert Chaulk479c60c2017-01-27 14:21:34 -05003721 layer->setInfo(windowType, ownerUid);
3722
Robert Carr1f0a16a2016-10-24 16:27:39 -07003723 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003724 if (result != NO_ERROR) {
3725 return result;
3726 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003727 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003728
3729 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003730 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003731}
3732
Cody Northropbc755282017-03-31 12:00:08 -06003733String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3734{
3735 bool matchFound = true;
3736 uint32_t dupeCounter = 0;
3737
3738 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3739 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3740
Dan Stoza436ccf32018-06-21 12:10:12 -07003741 // Grab the state lock since we're accessing mCurrentState
3742 Mutex::Autolock lock(mStateLock);
3743
Cody Northropbc755282017-03-31 12:00:08 -06003744 // Loop over layers until we're sure there is no matching name
3745 while (matchFound) {
3746 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003747 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003748 if (layer->getName() == uniqueName) {
3749 matchFound = true;
3750 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3751 }
3752 });
3753 }
3754
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003755 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3756 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003757
3758 return uniqueName;
3759}
3760
Marissa Wallfd668622018-05-10 10:21:13 -07003761status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3762 uint32_t w, uint32_t h, uint32_t flags,
3763 PixelFormat& format, sp<IBinder>* handle,
3764 sp<IGraphicBufferProducer>* gbp,
3765 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003766 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003767 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003768 case PIXEL_FORMAT_TRANSPARENT:
3769 case PIXEL_FORMAT_TRANSLUCENT:
3770 format = PIXEL_FORMAT_RGBA_8888;
3771 break;
3772 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003773 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003774 break;
3775 }
3776
Marissa Wallfd668622018-05-10 10:21:13 -07003777 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3778 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003779 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003780 *handle = layer->getHandle();
3781 *gbp = layer->getProducer();
3782 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003783 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003784
Marissa Wallfd668622018-05-10 10:21:13 -07003785 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003786 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003787}
3788
Marissa Wall61c58622018-07-18 10:12:20 -07003789status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3790 uint32_t w, uint32_t h, uint32_t flags,
3791 sp<IBinder>* handle, sp<Layer>* outLayer) {
3792 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3793 *handle = layer->getHandle();
3794 *outLayer = layer;
3795
3796 return NO_ERROR;
3797}
3798
chaviw13fdc492017-06-27 12:40:18 -07003799status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003800 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003801 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003802{
chaviw13fdc492017-06-27 12:40:18 -07003803 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003804 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003805 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003806}
3807
Mathias Agopianac9fa422013-02-11 16:40:36 -08003808status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003809{
Robert Carr9524cb32017-02-13 11:32:32 -08003810 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003811 status_t err = NO_ERROR;
3812 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003813 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003814 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003815 err = removeLayer(l);
3816 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3817 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003818 }
3819 return err;
3820}
3821
Mathias Agopian13127d82013-03-05 17:47:11 -08003822status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003823{
Mathias Agopian67106042013-03-14 19:18:13 -07003824 // called by ~LayerCleaner() when all references to the IBinder (handle)
3825 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003826 sp<Layer> l = layer.promote();
3827 if (l == nullptr) {
3828 // The layer has already been removed, carry on
3829 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003830 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003831 // If we have a parent, then we can continue to live as long as it does.
3832 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003833}
3834
Mathias Agopianb60314a2012-04-10 22:09:54 -07003835// ---------------------------------------------------------------------------
3836
Andy McFadden13a082e2012-08-24 10:16:42 -07003837void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003838 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3839 if (!displayToken) return;
3840
Jesse Hall01e29052013-02-19 16:13:35 -08003841 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003842 Vector<ComposerState> state;
3843 Vector<DisplayState> displays;
3844 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003845 d.what = DisplayState::eDisplayProjectionChanged |
3846 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003847 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003848 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003849 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003850 d.frame.makeInvalid();
3851 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003852 d.width = 0;
3853 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003854 displays.add(d);
3855 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003856
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003857 const auto display = getDisplayDevice(displayToken);
3858 if (!display) return;
3859
3860 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3861
3862 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003863 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003864 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003865
Brian Andersond0010582017-03-07 13:20:31 -08003866 // Use phase of 0 since phase is not known.
3867 // Use latency of 0, which will snap to the ideal latency.
3868 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003869}
3870
3871void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003872 // Async since we may be called from the main thread.
3873 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003874}
3875
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003876void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3877 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003878 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003879 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003880
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003881 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003882 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003883 return;
3884 }
3885
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003886 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003887 ALOGW("Trying to set power mode for virtual display");
3888 return;
3889 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003890
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003891 display->setPowerMode(mode);
3892
Lloyd Pique4dccc412018-01-22 17:21:36 -08003893 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003894 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003895 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003896 if (idx < 0) {
3897 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3898 return;
3899 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003900 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003901 }
3902
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003903 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003904 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003905 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003906 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003907 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003908 // FIXME: eventthread only knows about the main display right now
3909 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003910 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003911 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003912
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003913 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003914 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003915 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003916
3917 struct sched_param param = {0};
3918 param.sched_priority = 1;
3919 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3920 ALOGW("Couldn't set SCHED_FIFO on display on");
3921 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003922 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003923 // Turn off the display
3924 struct sched_param param = {0};
3925 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3926 ALOGW("Couldn't set SCHED_OTHER on display off");
3927 }
3928
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003929 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003930 disableHardwareVsync(true); // also cancels any in-progress resync
3931
Mathias Agopiancde87a32012-09-13 14:09:01 -07003932 // FIXME: eventthread only knows about the main display right now
3933 mEventThread->onScreenReleased();
3934 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003935
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003936 getHwComposer().setPowerMode(type, mode);
3937 mVisibleRegionsDirty = true;
3938 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003939 } else if (mode == HWC_POWER_MODE_DOZE ||
3940 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003941 // Update display while dozing
3942 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003943 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003944 // FIXME: eventthread only knows about the main display right now
3945 mEventThread->onScreenAcquired();
3946 resyncToHardwareVsync(true);
3947 }
3948 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3949 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003950 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003951 disableHardwareVsync(true); // also cancels any in-progress resync
3952 // FIXME: eventthread only knows about the main display right now
3953 mEventThread->onScreenReleased();
3954 }
3955 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003956 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003957 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003958 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003959 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003960
3961 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003962}
3963
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003964void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003965 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003966 const auto display = getDisplayDevice(displayToken);
3967 if (!display) {
3968 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3969 displayToken.get());
3970 } else if (display->isVirtual()) {
3971 ALOGW("Attempt to set power mode %d for virtual display", mode);
3972 } else {
3973 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003974 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003975 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003976}
3977
3978// ---------------------------------------------------------------------------
3979
Lloyd Pique755e3192018-01-31 16:46:15 -08003980status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3981 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003982 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003983
Mathias Agopianbd115332013-04-18 16:41:04 -07003984 IPCThreadState* ipc = IPCThreadState::self();
3985 const int pid = ipc->getCallingPid();
3986 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003987
Mathias Agopianbd115332013-04-18 16:41:04 -07003988 if ((uid != AID_SHELL) &&
3989 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003990 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003991 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003992 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003993 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003994 // (this would indicate SF is stuck, but we want to be able to
3995 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003996 status_t err = mStateLock.timedLock(s2ns(1));
3997 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003998 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003999 result.appendFormat(
4000 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4001 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004002 }
4003
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004004 bool dumpAll = true;
4005 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004006 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004007
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004008 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004009 if ((index < numArgs) &&
4010 (args[index] == String16("--list"))) {
4011 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004012 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004013 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004014 }
4015
4016 if ((index < numArgs) &&
4017 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004018 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004019 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004020 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004021 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004022
4023 if ((index < numArgs) &&
4024 (args[index] == String16("--latency-clear"))) {
4025 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004026 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004027 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004028 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004029
4030 if ((index < numArgs) &&
4031 (args[index] == String16("--dispsync"))) {
4032 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004033 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004034 dumpAll = false;
4035 }
Dan Stozab90cf072015-03-05 11:05:59 -08004036
4037 if ((index < numArgs) &&
4038 (args[index] == String16("--static-screen"))) {
4039 index++;
4040 dumpStaticScreenStats(result);
4041 dumpAll = false;
4042 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004043
4044 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004045 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004046 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004047 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004048 dumpAll = false;
4049 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004050
4051 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4052 index++;
4053 dumpWideColorInfo(result);
4054 dumpAll = false;
4055 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004056
4057 if ((index < numArgs) &&
4058 (args[index] == String16("--enable-layer-stats"))) {
4059 index++;
4060 mLayerStats.enable();
4061 dumpAll = false;
4062 }
4063
4064 if ((index < numArgs) &&
4065 (args[index] == String16("--disable-layer-stats"))) {
4066 index++;
4067 mLayerStats.disable();
4068 dumpAll = false;
4069 }
4070
4071 if ((index < numArgs) &&
4072 (args[index] == String16("--clear-layer-stats"))) {
4073 index++;
4074 mLayerStats.clear();
4075 dumpAll = false;
4076 }
4077
4078 if ((index < numArgs) &&
4079 (args[index] == String16("--dump-layer-stats"))) {
4080 index++;
4081 mLayerStats.dump(result);
4082 dumpAll = false;
4083 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004084
4085 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004086 (args[index] == String16("--frame-composition"))) {
4087 index++;
4088 dumpFrameCompositionInfo(result);
4089 dumpAll = false;
4090 }
4091
4092 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004093 (args[index] == String16("--display-identification"))) {
4094 index++;
4095 dumpDisplayIdentificationData(result);
4096 dumpAll = false;
4097 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004098
4099 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4100 index++;
4101 mTimeStats.parseArgs(asProto, args, index, result);
4102 dumpAll = false;
4103 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004104 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004105
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004106 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004107 if (asProto) {
4108 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4109 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4110 } else {
4111 dumpAllLocked(args, index, result);
4112 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004113 }
4114
Mathias Agopian9795c422009-08-26 16:36:26 -07004115 if (locked) {
4116 mStateLock.unlock();
4117 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004118 }
4119 write(fd, result.string(), result.size());
4120 return NO_ERROR;
4121}
4122
Dan Stozac7014012014-02-14 15:03:43 -08004123void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4124 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004125{
Robert Carr2047fae2016-11-28 14:09:09 -08004126 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004127 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004128 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004129}
4130
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004131void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004132 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004133{
4134 String8 name;
4135 if (index < args.size()) {
4136 name = String8(args[index]);
4137 index++;
4138 }
4139
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004140 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4141 getHwComposer().isConnected(displayId)) {
4142 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4143 const nsecs_t period = activeConfig->getVsyncPeriod();
4144 result.appendFormat("%" PRId64 "\n", period);
4145 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004146
4147 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004148 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004149 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004150 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004151 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004152 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004153 }
Robert Carr2047fae2016-11-28 14:09:09 -08004154 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004155 }
4156}
4157
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004158void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004159 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004160{
4161 String8 name;
4162 if (index < args.size()) {
4163 name = String8(args[index]);
4164 index++;
4165 }
4166
Robert Carr2047fae2016-11-28 14:09:09 -08004167 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004168 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004169 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004170 }
Robert Carr2047fae2016-11-28 14:09:09 -08004171 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004172
Svetoslavd85084b2014-03-20 10:28:31 -07004173 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004174}
4175
Jamie Gennis6547ff42013-07-16 20:12:42 -07004176// This should only be called from the main thread. Otherwise it would need
4177// the lock and should use mCurrentState rather than mDrawingState.
4178void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004179 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004180 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004181 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004182
4183 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4184}
4185
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004186void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004187{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004188 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004189
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004190 if (isLayerTripleBufferingDisabled())
4191 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004192
4193 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004194 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004195 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004196 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004197 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4198 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004199 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004200}
4201
Dan Stozab90cf072015-03-05 11:05:59 -08004202void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4203{
4204 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004205 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4206 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004207 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004208 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004209 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4210 b + 1, bucketTimeSec, percent);
4211 }
David Sodman4a36e932017-11-07 14:29:47 -08004212 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004213 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004214 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004215 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004216 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004217}
4218
Dan Stozae77c7662016-05-13 11:37:28 -07004219void SurfaceFlinger::recordBufferingStats(const char* layerName,
4220 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004221 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4222 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004223 for (const auto& segment : history) {
4224 if (!segment.usedThirdBuffer) {
4225 stats.twoBufferTime += segment.totalTime;
4226 }
4227 if (segment.occupancyAverage < 1.0f) {
4228 stats.doubleBufferedTime += segment.totalTime;
4229 } else if (segment.occupancyAverage < 2.0f) {
4230 stats.tripleBufferedTime += segment.totalTime;
4231 }
4232 ++stats.numSegments;
4233 stats.totalTime += segment.totalTime;
4234 }
4235}
4236
Brian Andersond6927fb2016-07-23 23:37:30 -07004237void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4238 result.appendFormat("Layer frame timestamps:\n");
4239
4240 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4241 const size_t count = currentLayers.size();
4242 for (size_t i=0 ; i<count ; i++) {
4243 currentLayers[i]->dumpFrameEvents(result);
4244 }
4245}
4246
Dan Stozae77c7662016-05-13 11:37:28 -07004247void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4248 result.append("Buffering stats:\n");
4249 result.append(" [Layer name] <Active time> <Two buffer> "
4250 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004251 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004252 typedef std::tuple<std::string, float, float, float> BufferTuple;
4253 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004254 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004255 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004256 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004257 if (stats.numSegments == 0) {
4258 continue;
4259 }
4260 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4261 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4262 stats.totalTime;
4263 float doubleBufferRatio = static_cast<float>(
4264 stats.doubleBufferedTime) / stats.totalTime;
4265 float tripleBufferRatio = static_cast<float>(
4266 stats.tripleBufferedTime) / stats.totalTime;
4267 sorted.insert({activeTime, {name, twoBufferRatio,
4268 doubleBufferRatio, tripleBufferRatio}});
4269 }
4270 for (const auto& sortedPair : sorted) {
4271 float activeTime = sortedPair.first;
4272 const BufferTuple& values = sortedPair.second;
4273 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4274 std::get<0>(values).c_str(), activeTime,
4275 std::get<1>(values), std::get<2>(values),
4276 std::get<3>(values));
4277 }
4278 result.append("\n");
4279}
4280
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004281void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004282 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004283 const int32_t displayId = display->getId();
4284 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4285 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004286 continue;
4287 }
4288
Dominik Laskowski7e045462018-05-30 13:02:02 -07004289 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004290 uint8_t port;
4291 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004292 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004293 result.append("no identification data\n");
4294 continue;
4295 }
4296
4297 if (!isEdid(data)) {
4298 result.append("unknown identification data: ");
4299 for (uint8_t byte : data) {
4300 result.appendFormat("%x ", byte);
4301 }
4302 result.append("\n");
4303 continue;
4304 }
4305
4306 const auto edid = parseEdid(data);
4307 if (!edid) {
4308 result.append("invalid EDID: ");
4309 for (uint8_t byte : data) {
4310 result.appendFormat("%x ", byte);
4311 }
4312 result.append("\n");
4313 continue;
4314 }
4315
4316 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4317 result.append(edid->displayName.data(), edid->displayName.length());
4318 result.append("\"\n");
4319 }
4320 result.append("\n");
4321}
4322
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004323void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004324 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4325 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004326 result.appendFormat("DisplayColorSetting: %s\n",
4327 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004328
4329 // TODO: print out if wide-color mode is active or not
4330
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004331 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004332 const int32_t displayId = display->getId();
4333 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004334 continue;
4335 }
4336
Dominik Laskowski7e045462018-05-30 13:02:02 -07004337 result.appendFormat("Display %d color modes:\n", displayId);
4338 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004339 for (auto&& mode : modes) {
4340 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4341 }
4342
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004343 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004344 result.appendFormat(" Current color mode: %s (%d)\n",
4345 decodeColorMode(currentMode).c_str(), currentMode);
4346 }
4347 result.append("\n");
4348}
4349
David Sodman7e4ae112018-02-09 15:02:28 -08004350void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4351 std::string stringResult;
4352
4353 for (const auto& [token, display] : mDisplays) {
4354 const auto displayId = display->getId();
4355 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
4356 continue;
4357 }
4358
4359 const auto& compositionInfoIt = getBE().mEndOfFrameCompositionInfo.find(displayId);
4360 if (compositionInfoIt == getBE().mEndOfFrameCompositionInfo.end()) {
4361 break;
4362 }
4363 const auto& compositionInfoList = compositionInfoIt->second;
4364 stringResult += base::StringPrintf("Display: %d\n", displayId);
4365 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4366 for (const auto& compositionInfo : compositionInfoList) {
4367 compositionInfo.dump(stringResult, nullptr);
4368 stringResult += base::StringPrintf("\n");
4369 }
4370 }
4371
4372 result.append(stringResult.c_str());
4373}
4374
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004375LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004376 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004377 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4378 const State& state = useDrawing ? mDrawingState : mCurrentState;
4379 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004380 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004381 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004382 });
4383
4384 return layersProto;
4385}
4386
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004387LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004388 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004389
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004390 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004391 resolution->set_w(display.getWidth());
4392 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004393
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004394 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4395 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4396 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004397
Dominik Laskowski7e045462018-05-30 13:02:02 -07004398 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004399 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004400 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004401 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004402 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004403 }
4404 });
4405
4406 return layersProto;
4407}
4408
Mathias Agopian74d211a2013-04-22 16:55:35 +02004409void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4410 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004411{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004412 bool colorize = false;
4413 if (index < args.size()
4414 && (args[index] == String16("--color"))) {
4415 colorize = true;
4416 index++;
4417 }
4418
4419 Colorizer colorizer(colorize);
4420
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004421 // figure out if we're stuck somewhere
4422 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004423 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004424 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4425
4426 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004427 * Dump library configuration.
4428 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004429
4430 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004431 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004432 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004433 appendSfConfigString(result);
4434 appendUiConfigString(result);
4435 appendGuiConfigString(result);
4436 result.append("\n");
4437
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004438 result.append("\nDisplay identification data:\n");
4439 dumpDisplayIdentificationData(result);
4440
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004441 result.append("\nWide-Color information:\n");
4442 dumpWideColorInfo(result);
4443
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004444 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004445 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004446 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004447 result.append(SyncFeatures::getInstance().toString());
4448 result.append("\n");
4449
Andy McFadden41d67d72014-04-25 16:58:34 -07004450 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004451 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004452 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004453
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004454 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4455 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004456 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4457 getHwComposer().isConnected(displayId)) {
4458 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004459 result.appendFormat("Display %d: "
4460 "app phase %" PRId64 " ns, "
4461 "sf phase %" PRId64 " ns, "
4462 "early app phase %" PRId64 " ns, "
4463 "early sf phase %" PRId64 " ns, "
4464 "early app gl phase %" PRId64 " ns, "
4465 "early sf gl phase %" PRId64 " ns, "
4466 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4467 displayId,
4468 vsyncPhaseOffsetNs,
4469 sfVsyncPhaseOffsetNs,
4470 appEarlyOffset,
4471 sfEarlyOffset,
4472 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004473 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004474 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004475 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004476 result.append("\n");
4477
Dan Stozab90cf072015-03-05 11:05:59 -08004478 // Dump static screen stats
4479 result.append("\n");
4480 dumpStaticScreenStats(result);
4481 result.append("\n");
4482
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004483 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4484
Dan Stozae77c7662016-05-13 11:37:28 -07004485 dumpBufferingStats(result);
4486
Andy McFadden4803b742012-09-24 19:07:20 -07004487 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004488 * Dump the visible layer list
4489 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004490 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004491 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004492 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4493 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004494 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004495
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004496 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004497 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004498 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004499 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004500
David Sodman7e4ae112018-02-09 15:02:28 -08004501 result.append("\nFrame-Composition information:\n");
4502 dumpFrameCompositionInfo(result);
4503 result.append("\n");
4504
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004505 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004506 * Dump Display state
4507 */
4508
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004509 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004510 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004511 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004512 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004513 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004514 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004515 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004516
4517 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004518 * Dump SurfaceFlinger global state
4519 */
4520
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004521 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004522 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004523 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004524
Mathias Agopian888c8222012-08-04 21:10:38 -07004525 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004526 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004527
David Sodmanbc815282017-11-05 18:57:52 -08004528 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004529
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004530 if (display) {
4531 display->undefinedRegion.dump(result, "undefinedRegion");
4532 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4533 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004534 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004535 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004536 " gpu_to_cpu_unsupported : %d\n",
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004537 mTransactionFlags, !mGpuToCpuSupported);
4538
4539 if (display) {
4540 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4541 result.appendFormat(" refresh-rate : %f fps\n"
4542 " x-dpi : %f\n"
4543 " y-dpi : %f\n",
4544 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4545 activeConfig->getDpiY());
4546 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004547
Mathias Agopian74d211a2013-04-22 16:55:35 +02004548 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004549 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004550
4551 /*
4552 * VSYNC state
4553 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004554 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004555 result.append("\n");
4556
4557 /*
4558 * HWC layer minidump
4559 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004560 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004561 const int32_t displayId = display->getId();
4562 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004563 continue;
4564 }
4565
Dominik Laskowski7e045462018-05-30 13:02:02 -07004566 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004567 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004568 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004569 result.append("\n");
4570 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004571
4572 /*
4573 * Dump HWComposer state
4574 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004575 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004576 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004577 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004578 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004579 result.appendFormat(" h/w composer %s\n",
4580 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004581 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004582
4583 /*
4584 * Dump gralloc state
4585 */
4586 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4587 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004588
4589 /*
4590 * Dump VrFlinger state if in use.
4591 */
4592 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4593 result.append("VrFlinger state:\n");
4594 result.append(mVrFlinger->Dump().c_str());
4595 result.append("\n");
4596 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004597}
4598
Dominik Laskowski7e045462018-05-30 13:02:02 -07004599const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004600 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004601 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004602 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004603 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004604 }
4605 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004606
4607 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4608 static const Vector<sp<Layer>> empty;
4609 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004610}
4611
Keun young Park63f165f2012-08-31 10:53:36 -07004612bool SurfaceFlinger::startDdmConnection()
4613{
4614 void* libddmconnection_dso =
4615 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4616 if (!libddmconnection_dso) {
4617 return false;
4618 }
4619 void (*DdmConnection_start)(const char* name);
4620 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004621 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004622 if (!DdmConnection_start) {
4623 dlclose(libddmconnection_dso);
4624 return false;
4625 }
4626 (*DdmConnection_start)(getServiceName());
4627 return true;
4628}
4629
Chia-I Wu28f320b2018-05-03 11:02:56 -07004630void SurfaceFlinger::updateColorMatrixLocked() {
4631 mat4 colorMatrix;
4632 if (mGlobalSaturationFactor != 1.0f) {
4633 // Rec.709 luma coefficients
4634 float3 luminance{0.213f, 0.715f, 0.072f};
4635 luminance *= 1.0f - mGlobalSaturationFactor;
4636 mat4 saturationMatrix = mat4(
4637 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4638 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4639 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4640 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4641 );
4642 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4643 } else {
4644 colorMatrix = mClientColorMatrix * mDaltonizer();
4645 }
4646
4647 if (mCurrentState.colorMatrix != colorMatrix) {
4648 mCurrentState.colorMatrix = colorMatrix;
4649 mCurrentState.colorMatrixChanged = true;
4650 setTransactionFlags(eTransactionNeeded);
4651 }
4652}
4653
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004654status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004655#pragma clang diagnostic push
4656#pragma clang diagnostic error "-Wswitch-enum"
4657 switch (static_cast<ISurfaceComposerTag>(code)) {
4658 // These methods should at minimum make sure that the client requested
4659 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004660 case BOOT_FINISHED:
4661 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004662 case CREATE_CONNECTION:
4663 case CREATE_DISPLAY:
4664 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004665 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004666 case GET_ACTIVE_COLOR_MODE:
4667 case GET_ANIMATION_FRAME_STATS:
4668 case GET_HDR_CAPABILITIES:
4669 case SET_ACTIVE_CONFIG:
4670 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004671 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004672 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004673 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4674 IPCThreadState* ipc = IPCThreadState::self();
4675 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4676 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004677 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004678 }
Robert Carr1db73f62016-12-21 12:58:51 -08004679 return OK;
4680 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004681 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004682 IPCThreadState* ipc = IPCThreadState::self();
4683 const int pid = ipc->getCallingPid();
4684 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004685 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4686 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004687 return PERMISSION_DENIED;
4688 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004689 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004690 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004691 // Used by apps to hook Choreographer to SurfaceFlinger.
4692 case CREATE_DISPLAY_EVENT_CONNECTION:
4693 // The following calls are currently used by clients that do not
4694 // request necessary permissions. However, they do not expose any secret
4695 // information, so it is OK to pass them.
4696 case AUTHENTICATE_SURFACE:
4697 case GET_ACTIVE_CONFIG:
4698 case GET_BUILT_IN_DISPLAY:
4699 case GET_DISPLAY_COLOR_MODES:
4700 case GET_DISPLAY_CONFIGS:
4701 case GET_DISPLAY_STATS:
Yiwei Zhangcd3f9e92018-08-21 15:15:42 -07004702 case GET_DISPLAY_VIEWPORT:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004703 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4704 // Calling setTransactionState is safe, because you need to have been
4705 // granted a reference to Client* and Handle* to do anything with it.
4706 case SET_TRANSACTION_STATE:
4707 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4708 case CREATE_SCOPED_CONNECTION: {
4709 return OK;
4710 }
4711 case CAPTURE_LAYERS:
4712 case CAPTURE_SCREEN: {
4713 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004714 IPCThreadState* ipc = IPCThreadState::self();
4715 const int pid = ipc->getCallingPid();
4716 const int uid = ipc->getCallingUid();
4717 if ((uid != AID_GRAPHICS) &&
4718 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4719 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4720 return PERMISSION_DENIED;
4721 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004722 return OK;
4723 }
4724 // The following codes are deprecated and should never be allowed to access SF.
4725 case CONNECT_DISPLAY_UNUSED:
4726 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4727 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4728 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004729 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004730 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004731
4732 // These codes are used for the IBinder protocol to either interrogate the recipient
4733 // side of the transaction for its canonical interface descriptor or to dump its state.
4734 // We let them pass by default.
4735 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4736 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4737 code == IBinder::SYSPROPS_TRANSACTION) {
4738 return OK;
4739 }
4740 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4741 // in onTransact verifies that the user is root, and has access to use SF.
4742 if (code >= 1000 && code <= 1029) {
4743 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4744 return OK;
4745 }
4746 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4747 return PERMISSION_DENIED;
4748#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004749}
4750
Ana Krulec13be8ad2018-08-21 02:43:56 +00004751status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4752 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004753 status_t credentialCheck = CheckTransactCodeCredentials(code);
4754 if (credentialCheck != OK) {
4755 return credentialCheck;
4756 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004757
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004758 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4759 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004760 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004761 IPCThreadState* ipc = IPCThreadState::self();
4762 const int uid = ipc->getCallingUid();
4763 if (CC_UNLIKELY(uid != AID_SYSTEM
4764 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004765 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004766 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004767 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004768 return PERMISSION_DENIED;
4769 }
4770 int n;
4771 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004772 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004773 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004774 return NO_ERROR;
4775 case 1002: // SHOW_UPDATES
4776 n = data.readInt32();
4777 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004778 invalidateHwcGeometry();
4779 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004780 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004781 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004782 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004783 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004784 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004785 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004786 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004787 setTransactionFlags(
4788 eTransactionNeeded|
4789 eDisplayTransactionNeeded|
4790 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004791 return NO_ERROR;
4792 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004793 case 1006:{ // send empty update
4794 signalRefresh();
4795 return NO_ERROR;
4796 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004797 case 1008: // toggle use of hw composer
4798 n = data.readInt32();
4799 mDebugDisableHWC = n ? 1 : 0;
4800 invalidateHwcGeometry();
4801 repaintEverything();
4802 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004803 case 1009: // toggle use of transform hint
4804 n = data.readInt32();
4805 mDebugDisableTransformHint = n ? 1 : 0;
4806 invalidateHwcGeometry();
4807 repaintEverything();
4808 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004809 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004810 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004811 reply->writeInt32(0);
4812 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004813 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004814 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004815 return NO_ERROR;
4816 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004817 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004818 if (!display) {
4819 return NAME_NOT_FOUND;
4820 }
4821
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004822 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004823 return NO_ERROR;
4824 }
4825 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004826 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004827 // daltonize
4828 n = data.readInt32();
4829 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004830 case 1:
4831 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4832 break;
4833 case 2:
4834 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4835 break;
4836 case 3:
4837 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4838 break;
4839 default:
4840 mDaltonizer.setType(ColorBlindnessType::None);
4841 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004842 }
4843 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004844 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004845 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004846 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004847 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004848
4849 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004850 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004851 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004852 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004853 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004854 // apply a color matrix
4855 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004856 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004857 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004858 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004859 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004860 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004861 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004862 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004863 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004864 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004865 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004866
4867 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4868 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004869 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004870 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4871 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4872 }
4873
Chia-I Wu28f320b2018-05-03 11:02:56 -07004874 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004875 return NO_ERROR;
4876 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004877 // This is an experimental interface
4878 // Needs to be shifted to proper binder interface when we productize
4879 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004880 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07004881 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004882 return NO_ERROR;
4883 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004884 case 1017: {
4885 n = data.readInt32();
4886 mForceFullDamage = static_cast<bool>(n);
4887 return NO_ERROR;
4888 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004889 case 1018: { // Modify Choreographer's phase offset
4890 n = data.readInt32();
4891 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4892 return NO_ERROR;
4893 }
4894 case 1019: { // Modify SurfaceFlinger's phase offset
4895 n = data.readInt32();
4896 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4897 return NO_ERROR;
4898 }
Irvel468051e2016-06-13 16:44:44 -07004899 case 1020: { // Layer updates interceptor
4900 n = data.readInt32();
4901 if (n) {
4902 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004903 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004904 }
4905 else{
4906 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004907 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004908 }
4909 return NO_ERROR;
4910 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004911 case 1021: { // Disable HWC virtual displays
4912 n = data.readInt32();
4913 mUseHwcVirtualDisplays = !n;
4914 return NO_ERROR;
4915 }
Romain Guy0147a172017-06-01 13:53:56 -07004916 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004917 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004918 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004919
Chia-I Wu28f320b2018-05-03 11:02:56 -07004920 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004921 return NO_ERROR;
4922 }
Romain Guy54f154a2017-10-24 21:40:32 +01004923 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004924 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004925 invalidateHwcGeometry();
4926 repaintEverything();
4927 return NO_ERROR;
4928 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004929 // TODO(b/111505327): Find out whether the usage of 1024 can switch to 1030,
4930 // deprecate 1024 if they can.
4931 case 1024: { // Does device have wide color gamut display?
Romain Guy54f154a2017-10-24 21:40:32 +01004932 reply->writeBool(hasWideColorDisplay);
4933 return NO_ERROR;
4934 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004935 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004936 n = data.readInt32();
4937 if (n) {
4938 ALOGV("LayerTracing enabled");
4939 mTracing.enable();
4940 doTracing("tracing.enable");
4941 reply->writeInt32(NO_ERROR);
4942 } else {
4943 ALOGV("LayerTracing disabled");
4944 status_t err = mTracing.disable();
4945 reply->writeInt32(err);
4946 }
4947 return NO_ERROR;
4948 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004949 case 1026: { // Get layer tracing status
4950 reply->writeBool(mTracing.isEnabled());
4951 return NO_ERROR;
4952 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004953 // Is a DisplayColorSetting supported?
4954 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004955 const auto display = getDefaultDisplayDevice();
4956 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004957 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004958 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004959
4960 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4961 switch (setting) {
4962 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07004963 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004964 break;
4965 case DisplayColorSetting::UNMANAGED:
4966 reply->writeBool(true);
4967 break;
4968 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004969 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004970 break;
4971 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004972 reply->writeBool(
4973 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004974 break;
4975 }
4976 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004977 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004978 // Is VrFlinger active?
4979 case 1028: {
4980 Mutex::Autolock _l(mStateLock);
4981 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4982 return NO_ERROR;
4983 }
David Sodman6d46c1e2018-07-13 12:59:48 -07004984 case 1029: {
4985 // Code 1029 is an experimental feature that allows applications to
4986 // simulate a high frequency panel by setting a multiplier and divisor
4987 // on the VSYNC-sf clock. If either the multiplier or divisor are
David Sodman44b5de02018-08-21 16:28:53 -07004988 // 0, then the code simply return the current multiplier and divisor.
4989 HWC2::Device::FrequencyScaler frequencyScaler;
4990 frequencyScaler.multiplier = data.readInt32();
4991 frequencyScaler.divisor = data.readInt32();
David Sodman6d46c1e2018-07-13 12:59:48 -07004992
David Sodman44b5de02018-08-21 16:28:53 -07004993 if ((frequencyScaler.multiplier == 0) || (frequencyScaler.divisor == 0)) {
4994 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
4995 reply->writeInt32(frequencyScaler.multiplier);
4996 reply->writeInt32(frequencyScaler.divisor);
4997 return NO_ERROR;
David Sodman6d46c1e2018-07-13 12:59:48 -07004998 }
4999
David Sodman44b5de02018-08-21 16:28:53 -07005000 if ((frequencyScaler.multiplier == 1) && (frequencyScaler.divisor == 1)) {
David Sodman6d46c1e2018-07-13 12:59:48 -07005001 enableHardwareVsync();
5002 } else {
5003 disableHardwareVsync(true);
5004 }
David Sodman44b5de02018-08-21 16:28:53 -07005005 mPrimaryDispSync->scalePeriod(frequencyScaler);
5006 getBE().mHwc->setDisplayFrequencyScaleParameters(frequencyScaler);
David Sodman6d46c1e2018-07-13 12:59:48 -07005007
David Sodman44b5de02018-08-21 16:28:53 -07005008 ATRACE_INT("PeriodMultiplier", frequencyScaler.multiplier);
5009 ATRACE_INT("PeriodDivisor", frequencyScaler.divisor);
5010
5011 const hwc2_display_t hwcDisplayId = getBE().mHwc->getActiveConfig(
5012 DisplayDevice::DISPLAY_PRIMARY)->getDisplayId();
5013
5014 onHotplugReceived(getBE().mComposerSequenceId,
5015 hwcDisplayId, HWC2::Connection::Disconnected);
5016 onHotplugReceived(getBE().mComposerSequenceId,
5017 hwcDisplayId, HWC2::Connection::Connected);
5018 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5019 reply->writeInt32(frequencyScaler.multiplier);
5020 reply->writeInt32(frequencyScaler.divisor);
5021
David Sodman6d46c1e2018-07-13 12:59:48 -07005022 return NO_ERROR;
5023 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005024 // Is device color managed?
5025 case 1030: {
5026 reply->writeBool(useColorManagement);
5027 return NO_ERROR;
5028 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005029 }
5030 }
5031 return err;
5032}
5033
Steven Thomas6d8110b2017-08-31 18:24:21 -07005034void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07005035 android_atomic_or(1, &mRepaintEverything);
5036 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005037}
5038
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005039// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5040class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005041public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005042 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5043 ~WindowDisconnector() {
5044 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005045 }
5046
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005047private:
5048 ANativeWindow* mWindow;
5049 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005050};
5051
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005052status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
5053 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
5054 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
5055 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005056 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005057 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005058
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005059 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005060
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005061 const auto display = getDisplayDeviceLocked(displayToken);
5062 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005063
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005064 const Rect& dispScissor = display->getScissor();
5065 if (!dispScissor.isEmpty()) {
5066 sourceCrop.set(dispScissor);
5067 // adb shell screencap will default reqWidth and reqHeight to zeros.
5068 if (reqWidth == 0 || reqHeight == 0) {
Yiwei Zhangec90e582018-08-21 22:11:37 -07005069 reqWidth = uint32_t(display->getViewport().width());
5070 reqHeight = uint32_t(display->getViewport().height());
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005071 }
5072 }
5073
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005074 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07005075
5076 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005077 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005078 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005079}
5080
5081status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08005082 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005083 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005084 ATRACE_CALL();
5085
5086 class LayerRenderArea : public RenderArea {
5087 public:
Robert Carr578038f2018-03-09 12:25:24 -08005088 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
5089 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07005090 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08005091 mLayer(layer),
5092 mCrop(crop),
5093 mFlinger(flinger),
5094 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005095 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005096 Rect getBounds() const override {
5097 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005098 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005099 }
Marissa Wall61c58622018-07-18 10:12:20 -07005100 int getHeight() const override {
5101 return mLayer->getActiveHeight(mLayer->getDrawingState());
5102 }
5103 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005104 bool isSecure() const override { return false; }
5105 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005106 Rect getSourceCrop() const override {
5107 if (mCrop.isEmpty()) {
5108 return getBounds();
5109 } else {
5110 return mCrop;
5111 }
5112 }
Robert Carr578038f2018-03-09 12:25:24 -08005113 class ReparentForDrawing {
5114 public:
5115 const sp<Layer>& oldParent;
5116 const sp<Layer>& newParent;
5117
5118 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5119 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005120 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005121 }
Robert Carr15eae092018-03-23 13:43:53 -07005122 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005123 };
5124
5125 void render(std::function<void()> drawLayers) override {
5126 if (!mChildrenOnly) {
5127 mTransform = mLayer->getTransform().inverse();
5128 drawLayers();
5129 } else {
5130 Rect bounds = getBounds();
5131 screenshotParentLayer =
5132 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
5133 bounds.getWidth(), bounds.getHeight(), 0);
5134
5135 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5136 drawLayers();
5137 }
5138 }
chaviwa76b2712017-09-20 12:02:26 -07005139
chaviwa76b2712017-09-20 12:02:26 -07005140 private:
chaviw7206d492017-11-10 16:16:12 -08005141 const sp<Layer> mLayer;
5142 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005143
5144 // In the "childrenOnly" case we reparent the children to a screenshot
5145 // layer which has no properties set and which does not draw.
5146 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005147 ui::Transform mTransform;
Robert Carr578038f2018-03-09 12:25:24 -08005148
5149 SurfaceFlinger* mFlinger;
5150 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005151 };
5152
5153 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5154 auto parent = layerHandle->owner.promote();
5155
chaviw7206d492017-11-10 16:16:12 -08005156 if (parent == nullptr || parent->isPendingRemoval()) {
5157 ALOGE("captureLayers called with a removed parent");
5158 return NAME_NOT_FOUND;
5159 }
5160
Robert Carr578038f2018-03-09 12:25:24 -08005161 const int uid = IPCThreadState::self()->getCallingUid();
5162 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5163 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5164 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5165 return PERMISSION_DENIED;
5166 }
5167
chaviw7206d492017-11-10 16:16:12 -08005168 Rect crop(sourceCrop);
5169 if (sourceCrop.width() <= 0) {
5170 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005171 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005172 }
5173
5174 if (sourceCrop.height() <= 0) {
5175 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005176 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005177 }
5178
5179 int32_t reqWidth = crop.width() * frameScale;
5180 int32_t reqHeight = crop.height() * frameScale;
5181
Robert Carr578038f2018-03-09 12:25:24 -08005182 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005183
Robert Carr578038f2018-03-09 12:25:24 -08005184 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005185 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5186 if (!layer->isVisible()) {
5187 return;
Robert Carr578038f2018-03-09 12:25:24 -08005188 } else if (childrenOnly && layer == parent.get()) {
5189 return;
chaviwa76b2712017-09-20 12:02:26 -07005190 }
5191 visitor(layer);
5192 });
5193 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005194 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005195}
5196
5197status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5198 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005199 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005200 bool useIdentityTransform) {
5201 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005202
Iris Chang7501ed62018-04-30 14:45:42 +08005203 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07005204
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005205 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5206 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5207 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5208 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005209
5210 // This mutex protects syncFd and captureResult for communication of the return values from the
5211 // main thread back to this Binder thread
5212 std::mutex captureMutex;
5213 std::condition_variable captureCondition;
5214 std::unique_lock<std::mutex> captureLock(captureMutex);
5215 int syncFd = -1;
5216 std::optional<status_t> captureResult;
5217
Robert Carr03480e22018-01-04 16:02:06 -08005218 const int uid = IPCThreadState::self()->getCallingUid();
5219 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5220
Dominik Laskowski8c001672018-05-30 16:52:06 -07005221 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005222 // If there is a refresh pending, bug out early and tell the binder thread to try again
5223 // after the refresh.
5224 if (mRefreshPending) {
5225 ATRACE_NAME("Skipping screenshot for now");
5226 std::unique_lock<std::mutex> captureLock(captureMutex);
5227 captureResult = std::make_optional<status_t>(EAGAIN);
5228 captureCondition.notify_one();
5229 return;
5230 }
5231
5232 status_t result = NO_ERROR;
5233 int fd = -1;
5234 {
5235 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005236 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005237 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5238 useIdentityTransform, forSystem, &fd);
5239 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005240 }
5241
5242 {
5243 std::unique_lock<std::mutex> captureLock(captureMutex);
5244 syncFd = fd;
5245 captureResult = std::make_optional<status_t>(result);
5246 captureCondition.notify_one();
5247 }
5248 });
5249
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005250 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005251 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005252 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005253 while (*captureResult == EAGAIN) {
5254 captureResult.reset();
5255 result = postMessageAsync(message);
5256 if (result != NO_ERROR) {
5257 return result;
5258 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005259 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005260 }
5261 result = *captureResult;
5262 }
5263
5264 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005265 sync_wait(syncFd, -1);
5266 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005267 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005268
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005269 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005270}
5271
chaviwa76b2712017-09-20 12:02:26 -07005272void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5273 TraverseLayersFunction traverseLayers, bool yswap,
5274 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005275 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005276
Lloyd Pique144e1162017-12-20 16:44:52 -08005277 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005278
5279 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005280 const auto raWidth = renderArea.getWidth();
5281 const auto raHeight = renderArea.getHeight();
5282
5283 const auto reqWidth = renderArea.getReqWidth();
5284 const auto reqHeight = renderArea.getReqHeight();
5285 Rect sourceCrop = renderArea.getSourceCrop();
5286
Iris Chang7501ed62018-04-30 14:45:42 +08005287 bool filtering = false;
5288 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5289 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5290 static_cast<int32_t>(reqHeight) != raWidth;
5291 } else {
5292 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5293 static_cast<int32_t>(reqHeight) != raHeight;
5294 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005295
Dan Stozac1879002014-05-22 15:59:05 -07005296 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005297 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005298 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005299 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005300 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
Peiyong Linefefaac2018-08-17 12:27:51 -07005301 ui::Transform tr;
Iris Chang7501ed62018-04-30 14:45:42 +08005302 uint32_t flags = 0x00;
5303 switch (mPrimaryDisplayOrientation) {
5304 case DisplayState::eOrientation90:
Peiyong Linefefaac2018-08-17 12:27:51 -07005305 flags = ui::Transform::ROT_90;
Iris Chang7501ed62018-04-30 14:45:42 +08005306 break;
5307 case DisplayState::eOrientation180:
Peiyong Linefefaac2018-08-17 12:27:51 -07005308 flags = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005309 break;
5310 case DisplayState::eOrientation270:
Peiyong Linefefaac2018-08-17 12:27:51 -07005311 flags = ui::Transform::ROT_270;
Iris Chang7501ed62018-04-30 14:45:42 +08005312 break;
5313 }
5314 tr.set(flags, raWidth, raHeight);
5315 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005316 }
5317
5318 // ensure that sourceCrop is inside screen
5319 if (sourceCrop.left < 0) {
5320 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5321 }
chaviwa76b2712017-09-20 12:02:26 -07005322 if (sourceCrop.right > raWidth) {
5323 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005324 }
5325 if (sourceCrop.top < 0) {
5326 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5327 }
chaviwa76b2712017-09-20 12:02:26 -07005328 if (sourceCrop.bottom > raHeight) {
5329 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005330 }
5331
Chia-I Wu36574d92018-05-16 10:54:36 -07005332 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5333 engine.setOutputDataSpace(Dataspace::SRGB);
5334 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005335
Mathias Agopian180f10d2013-04-10 22:55:41 -07005336 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005337 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005338
Peiyong Linefefaac2018-08-17 12:27:51 -07005339 ui::Transform::orientation_flags rotation = renderArea.getRotationFlags();
Iris Chang7501ed62018-04-30 14:45:42 +08005340 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5341 // convert hw orientation into flag presentation
5342 // here inverse transform needed
5343 uint8_t hw_rot_90 = 0x00;
5344 uint8_t hw_flip_hv = 0x00;
5345 switch (mPrimaryDisplayOrientation) {
5346 case DisplayState::eOrientation90:
Peiyong Linefefaac2018-08-17 12:27:51 -07005347 hw_rot_90 = ui::Transform::ROT_90;
5348 hw_flip_hv = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005349 break;
5350 case DisplayState::eOrientation180:
Peiyong Linefefaac2018-08-17 12:27:51 -07005351 hw_flip_hv = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005352 break;
5353 case DisplayState::eOrientation270:
Peiyong Linefefaac2018-08-17 12:27:51 -07005354 hw_rot_90 = ui::Transform::ROT_90;
Iris Chang7501ed62018-04-30 14:45:42 +08005355 break;
5356 }
5357
5358 // transform flags operation
5359 // 1) flip H V if both have ROT_90 flag
5360 // 2) XOR these flags
Peiyong Linefefaac2018-08-17 12:27:51 -07005361 uint8_t rotation_rot_90 = rotation & ui::Transform::ROT_90;
5362 uint8_t rotation_flip_hv = rotation & ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005363 if (rotation_rot_90 & hw_rot_90) {
Peiyong Linefefaac2018-08-17 12:27:51 -07005364 rotation_flip_hv = (~rotation_flip_hv) & ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005365 }
Peiyong Linefefaac2018-08-17 12:27:51 -07005366 rotation = static_cast<ui::Transform::orientation_flags>
Iris Chang7501ed62018-04-30 14:45:42 +08005367 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5368 }
5369
Mathias Agopian180f10d2013-04-10 22:55:41 -07005370 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005371 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005372 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005373 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005374
chaviw50da5042018-04-09 13:49:37 -07005375 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005376 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005377 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005378
chaviwa76b2712017-09-20 12:02:26 -07005379 traverseLayers([&](Layer* layer) {
5380 if (filtering) layer->setFiltering(true);
David Sodmanfb95bcc2017-12-22 15:45:30 -08005381 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005382 if (filtering) layer->setFiltering(false);
5383 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005384}
5385
chaviwa76b2712017-09-20 12:02:26 -07005386status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5387 TraverseLayersFunction traverseLayers,
5388 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005389 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005390 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005391 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005392 ATRACE_CALL();
5393
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005394 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005395
5396 traverseLayers([&](Layer* layer) {
5397 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5398 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005399
Robert Carr03480e22018-01-04 16:02:06 -08005400 // We allow the system server to take screenshots of secure layers for
5401 // use in situations like the Screen-rotation animation and place
5402 // the impetus on WindowManager to not persist them.
5403 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005404 ALOGW("FB is protected: PERMISSION_DENIED");
5405 return PERMISSION_DENIED;
5406 }
5407
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005408 // this binds the given EGLImage as a framebuffer for the
5409 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005410 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005411 if (bufferBond.getStatus() != NO_ERROR) {
5412 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005413 return INVALID_OPERATION;
5414 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005415
Dan Stozaabcda352017-06-01 14:37:39 -07005416 // this will in fact render into our dequeued buffer
5417 // via an FBO, which means we didn't have to create
5418 // an EGLSurface and therefore we're not
5419 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005420 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005421
Dan Stozaabcda352017-06-01 14:37:39 -07005422 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005423 getRenderEngine().finish();
5424 *outSyncFd = -1;
5425
chaviwa76b2712017-09-20 12:02:26 -07005426 const auto reqWidth = renderArea.getReqWidth();
5427 const auto reqHeight = renderArea.getReqHeight();
5428
Dan Stozaabcda352017-06-01 14:37:39 -07005429 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5430 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005431 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005432 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005433 } else {
5434 base::unique_fd syncFd = getRenderEngine().flush();
5435 if (syncFd < 0) {
5436 getRenderEngine().finish();
5437 }
5438 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005439 }
5440
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005441 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005442}
5443
Mathias Agopiand5556842013-09-19 17:08:37 -07005444void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005445 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005446 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005447 for (size_t y = 0; y < h; y++) {
5448 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5449 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005450 if (p[x] != 0xFF000000) return;
5451 }
5452 }
chaviwa76b2712017-09-20 12:02:26 -07005453 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005454
Robert Carr2047fae2016-11-28 14:09:09 -08005455 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005456 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005457 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005458 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5459 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5460 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5461 static_cast<float>(state.color.a));
5462 i++;
5463 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005464 }
5465}
5466
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005467// ---------------------------------------------------------------------------
5468
Dan Stoza412903f2017-04-27 13:42:17 -07005469void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5470 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005471}
5472
Dan Stoza412903f2017-04-27 13:42:17 -07005473void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5474 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005475}
5476
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005477void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5478 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005479 const LayerVector::Visitor& visitor) {
5480 // We loop through the first level of layers without traversing,
5481 // as we need to interpret min/max layer Z in the top level Z space.
5482 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005483 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005484 continue;
5485 }
5486 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005487 // relative layers are traversed in Layer::traverseInZOrder
5488 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005489 continue;
5490 }
5491 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005492 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005493 return;
5494 }
chaviwa76b2712017-09-20 12:02:26 -07005495 if (!layer->isVisible()) {
5496 return;
5497 }
5498 visitor(layer);
5499 });
5500 }
5501}
5502
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005503}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005504
Lloyd Pique074e8122018-07-26 12:57:23 -07005505
Mathias Agopian3f844832013-08-07 21:24:32 -07005506#if defined(__gl_h_)
5507#error "don't include gl/gl.h in this file"
5508#endif
5509
5510#if defined(__gl2_h_)
5511#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005512#endif