blob: 31e44449b3cc781d478fcad5e03604aad7bad993 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Chia-I Wud49d6692018-06-27 07:17:41 +080040#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060041#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070043#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080048#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070050
51#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Robert Carr578038f2018-03-09 12:25:24 -080065#include "BufferLayer.h"
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"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070073#include "DispSync.h"
Robert Carr578038f2018-03-09 12:25:24 -080074#include "DisplayDevice.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070075#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080076#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070078#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080079#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080#include "SurfaceFlinger.h"
Robert Carr578038f2018-03-09 12:25:24 -080081#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082
Steven Thomasb02664d2017-07-26 18:48:28 -070083#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070084#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070085#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070086#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070087#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080088
Mathias Agopianff2ed702013-09-01 21:36:12 -070089#include "Effects/Daltonizer.h"
90
Mathias Agopian875d8e12013-06-07 15:35:48 -070091#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070092#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070093
Jiyong Park4b20c2e2017-01-14 19:45:11 +090094#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080095#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
96#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090097#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090098
chaviw1d044282017-09-27 12:19:28 -070099#include <layerproto/LayerProtoParser.h>
100
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800101#define DISPLAY_COUNT 1
102
Mathias Agopianfee2b462013-07-03 12:34:01 -0700103/*
104 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
105 * black pixels.
106 */
107#define DEBUG_SCREENSHOTS false
108
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800109namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700110
Jaesoo Lee43518572017-01-23 19:03:16 +0900111using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900112using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700113using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700114using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700115using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700116using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900117
Steven Thomasb02664d2017-07-26 18:48:28 -0700118namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700119
120#pragma clang diagnostic push
121#pragma clang diagnostic error "-Wswitch-enum"
122
123bool isWideColorMode(const ColorMode colorMode) {
124 switch (colorMode) {
125 case ColorMode::DISPLAY_P3:
126 case ColorMode::ADOBE_RGB:
127 case ColorMode::DCI_P3:
128 case ColorMode::BT2020:
129 case ColorMode::BT2100_PQ:
130 case ColorMode::BT2100_HLG:
131 return true;
132 case ColorMode::NATIVE:
133 case ColorMode::STANDARD_BT601_625:
134 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
135 case ColorMode::STANDARD_BT601_525:
136 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
137 case ColorMode::STANDARD_BT709:
138 case ColorMode::SRGB:
139 return false;
140 }
141 return false;
142}
143
144#pragma clang diagnostic pop
145
Steven Thomasb02664d2017-07-26 18:48:28 -0700146class ConditionalLock {
147public:
148 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
149 if (lock) {
150 mMutex.lock();
151 }
152 }
153 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
154private:
155 Mutex& mMutex;
156 bool mLocked;
157};
Peiyong Linfca547f2018-07-09 13:03:33 -0700158
Steven Thomasb02664d2017-07-26 18:48:28 -0700159} // namespace anonymous
160
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800161// ---------------------------------------------------------------------------
162
Mathias Agopian99b49842011-06-27 16:05:52 -0700163const String16 sHardwareTest("android.permission.HARDWARE_TEST");
164const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
165const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
166const String16 sDump("android.permission.DUMP");
167
168// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800169int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
170int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700171int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700172bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800173uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800174bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800175bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800176int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800177// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600178bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700179
Kalle Raitaa099a242017-01-11 11:17:29 -0800180
181std::string getHwcServiceName() {
182 char value[PROPERTY_VALUE_MAX] = {};
183 property_get("debug.sf.hwc_service_name", value, "default");
184 ALOGI("Using HWComposer service: '%s'", value);
185 return std::string(value);
186}
187
188bool useTrebleTestingOverride() {
189 char value[PROPERTY_VALUE_MAX] = {};
190 property_get("debug.sf.treble_testing_override", value, "false");
191 ALOGI("Treble testing override: '%s'", value);
192 return std::string(value) == "true";
193}
194
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800195std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
196 switch(displayColorSetting) {
197 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700198 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800199 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700200 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800201 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700202 return std::string("Enhanced");
203 default:
204 return std::string("Unknown ") +
205 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800206 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800207}
208
Lloyd Pique99d3da52018-01-22 17:48:03 -0800209NativeWindowSurface::~NativeWindowSurface() = default;
210
211namespace impl {
212
213class NativeWindowSurface final : public android::NativeWindowSurface {
214public:
215 static std::unique_ptr<android::NativeWindowSurface> create(
216 const sp<IGraphicBufferProducer>& producer) {
217 return std::make_unique<NativeWindowSurface>(producer);
218 }
219
220 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
221 : surface(new Surface(producer, false)) {}
222
223 ~NativeWindowSurface() override = default;
224
225private:
226 sp<ANativeWindow> getNativeWindow() const override { return surface; }
227
228 void preallocateBuffers() override { surface->allocateBuffers(); }
229
230 sp<Surface> surface;
231};
232
233} // namespace impl
234
David Sodmanbc815282017-11-05 18:57:52 -0800235SurfaceFlingerBE::SurfaceFlingerBE()
236 : mHwcServiceName(getHwcServiceName()),
237 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800238 mFrameBuckets(),
239 mTotalTime(0),
240 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800241 mComposerSequenceId(0) {
242}
243
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800244SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800245 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800246 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700247 mTransactionPending(false),
248 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700249 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700250 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700251 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800252 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700253 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800254 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800255 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800256 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800257 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800258 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700259 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700260 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700261 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700262 mDebugInSwapBuffers(0),
263 mLastSwapBufferTime(0),
264 mDebugInTransaction(0),
265 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700266 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700267 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700268 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800269 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800270 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700271 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800272 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800273 mCreateBufferQueue(&BufferQueue::createBufferQueue),
274 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800275
276SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800277 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800278
279 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
280 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
281
282 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
283 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
284
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800285 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
286 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800287
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700288 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
289 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
290
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700291 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
292 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
293
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800294 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
295 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
296
Steven Thomas050b2c82017-03-06 11:45:16 -0800297 // Vr flinger is only enabled on Daydream ready devices.
298 useVrFlinger = getBool< ISurfaceFlingerConfigs,
299 &ISurfaceFlingerConfigs::useVrFlinger>(false);
300
Fabien Sanglard1971b632017-03-10 14:50:03 -0800301 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
302 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
303
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600304 hasWideColorDisplay =
305 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
306
Iris Chang7501ed62018-04-30 14:45:42 +0800307 V1_1::DisplayOrientation primaryDisplayOrientation =
308 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
309 V1_1::DisplayOrientation::ORIENTATION_0);
310
311 switch (primaryDisplayOrientation) {
312 case V1_1::DisplayOrientation::ORIENTATION_90:
313 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
314 break;
315 case V1_1::DisplayOrientation::ORIENTATION_180:
316 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
317 break;
318 case V1_1::DisplayOrientation::ORIENTATION_270:
319 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
320 break;
321 default:
322 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
323 break;
324 }
325 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
326
Lloyd Pique41be5d22018-06-21 13:11:48 -0700327 // Note: We create a local temporary with the real DispSync implementation
328 // type temporarily so we can initialize it with the configured values,
329 // before storing it for more generic use using the interface type.
330 auto primaryDispSync = std::make_unique<impl::DispSync>("PrimaryDispSync");
331 primaryDispSync->init(SurfaceFlinger::hasSyncFramework,
332 SurfaceFlinger::dispSyncPresentTimeOffset);
333 mPrimaryDispSync = std::move(primaryDispSync);
Saurabh Shahf4174532017-07-13 10:45:07 -0700334
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800335 // debugging stuff...
336 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700337
Mathias Agopianb4b17302013-03-20 18:36:41 -0700338 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700339 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700340
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800341 property_get("debug.sf.showupdates", value, "0");
342 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700343
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700344 property_get("debug.sf.ddms", value, "0");
345 mDebugDDMS = atoi(value);
346 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700347 if (!startDdmConnection()) {
348 // start failed, and DDMS debugging not enabled
349 mDebugDDMS = 0;
350 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700351 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700352 ALOGI_IF(mDebugRegion, "showupdates enabled");
353 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700354
355 property_get("debug.sf.disable_backpressure", value, "0");
356 mPropagateBackpressure = !atoi(value);
357 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700358
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800359 property_get("debug.sf.enable_hwc_vds", value, "0");
360 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800361 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800362
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800363 property_get("ro.sf.disable_triple_buffer", value, "1");
364 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800365 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700366
Yiwei Zhang243b3782018-05-15 17:40:04 -0700367 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700368 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
369 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
370
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200371 property_get("debug.sf.early_phase_offset_ns", value, "-1");
372 const int earlySfOffsetNs = atoi(value);
373
374 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
375 const int earlyGlSfOffsetNs = atoi(value);
376
377 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
378 const int earlyAppOffsetNs = atoi(value);
379
380 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
381 const int earlyGlAppOffsetNs = atoi(value);
382
383 const VSyncModulator::Offsets earlyOffsets =
384 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
385 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
386 const VSyncModulator::Offsets earlyGlOffsets =
387 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
388 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
389 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
390 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700391
Romain Guy11d63f42017-07-20 12:47:14 -0700392 // We should be reading 'persist.sys.sf.color_saturation' here
393 // but since /data may be encrypted, we need to wait until after vold
394 // comes online to attempt to read the property. The property is
395 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800396
397 if (useTrebleTestingOverride()) {
398 // Without the override SurfaceFlinger cannot connect to HIDL
399 // services that are not listed in the manifests. Considered
400 // deriving the setting from the set service name, but it
401 // would be brittle if the name that's not 'default' is used
402 // for production purposes later on.
403 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
404 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800405}
406
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800407void SurfaceFlinger::onFirstRef()
408{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800409 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800410}
411
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800412SurfaceFlinger::~SurfaceFlinger()
413{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800414}
415
Dan Stozac7014012014-02-14 15:03:43 -0800416void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800417{
418 // the window manager died on us. prepare its eulogy.
419
Andy McFadden13a082e2012-08-24 10:16:42 -0700420 // restore initial conditions (default device unblank, etc)
421 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800422
423 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700424 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800425}
426
Robert Carr1db73f62016-12-21 12:58:51 -0800427static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700428 status_t err = client->initCheck();
429 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800430 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800431 }
Robert Carr1db73f62016-12-21 12:58:51 -0800432 return nullptr;
433}
434
435sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
436 return initClient(new Client(this));
437}
438
439sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
440 const sp<IGraphicBufferProducer>& gbp) {
441 if (authenticateSurfaceTexture(gbp) == false) {
442 return nullptr;
443 }
444 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
445 if (layer == nullptr) {
446 return nullptr;
447 }
448
449 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800450}
451
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700452sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
453 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700454{
455 class DisplayToken : public BBinder {
456 sp<SurfaceFlinger> flinger;
457 virtual ~DisplayToken() {
458 // no more references, this display must be terminated
459 Mutex::Autolock _l(flinger->mStateLock);
460 flinger->mCurrentState.displays.removeItem(this);
461 flinger->setTransactionFlags(eDisplayTransactionNeeded);
462 }
463 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700464 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700465 : flinger(flinger) {
466 }
467 };
468
469 sp<BBinder> token = new DisplayToken(this);
470
471 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700472 DisplayDeviceState info;
473 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700474 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700475 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700476 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800477 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700478 return token;
479}
480
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700481void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700482 Mutex::Autolock _l(mStateLock);
483
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700484 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700485 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700486 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700487 return;
488 }
489
490 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700491 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700492 ALOGE("destroyDisplay called for non-virtual display");
493 return;
494 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700495 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700496 mCurrentState.displays.removeItemsAt(idx);
497 setTransactionFlags(eDisplayTransactionNeeded);
498}
499
Mathias Agopiane57f2922012-08-09 16:29:12 -0700500sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700501 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700502 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800503 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700504 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700505 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700506}
507
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800508void SurfaceFlinger::bootFinished()
509{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700510 if (mStartPropertySetThread->join() != NO_ERROR) {
511 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800512 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800513 const nsecs_t now = systemTime();
514 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000515 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700516
517 // wait patiently for the window manager death
518 const String16 name("window");
519 sp<IBinder> window(defaultServiceManager()->getService(name));
520 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700521 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700522 }
523
Steven Thomas050b2c82017-03-06 11:45:16 -0800524 if (mVrFlinger) {
525 mVrFlinger->OnBootFinished();
526 }
527
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700528 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700529 // formerly we would just kill the process, but we now ask it to exit so it
530 // can choose where to stop the animation.
531 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700532
533 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
534 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
535 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700536
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800537 postMessageAsync(new LambdaMessage([this] {
538 readPersistentProperties();
539 mBootStage = BootStage::FINISHED;
540 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800541}
542
Dan Stoza436ccf32018-06-21 12:10:12 -0700543uint32_t SurfaceFlinger::getNewTexture() {
544 {
545 std::lock_guard lock(mTexturePoolMutex);
546 if (!mTexturePool.empty()) {
547 uint32_t name = mTexturePool.back();
548 mTexturePool.pop_back();
549 ATRACE_INT("TexturePoolSize", mTexturePool.size());
550 return name;
551 }
552
553 // The pool was too small, so increase it for the future
554 ++mTexturePoolSize;
555 }
556
557 // The pool was empty, so we need to get a new texture name directly using a
558 // blocking call to the main thread
559 uint32_t name = 0;
560 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
561 return name;
562}
563
Mathias Agopian3f844832013-08-07 21:24:32 -0700564void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700565 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700566}
567
Lloyd Piquee83f9312018-02-01 12:53:17 -0800568class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700569public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700570 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000571 const char* name) :
572 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700573 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700574 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000575 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
576 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700577 mDispSync(dispSync),
578 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700579 mVsyncMutex(),
580 mPhaseOffset(phaseOffset),
581 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700582
Lloyd Piquee83f9312018-02-01 12:53:17 -0800583 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700584
Lloyd Piquee83f9312018-02-01 12:53:17 -0800585 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700586 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700587 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000588 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700589 static_cast<DispSync::Callback*>(this));
590 if (err != NO_ERROR) {
591 ALOGE("error registering vsync callback: %s (%d)",
592 strerror(-err), err);
593 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700594 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700595 } else {
596 status_t err = mDispSync->removeEventListener(
597 static_cast<DispSync::Callback*>(this));
598 if (err != NO_ERROR) {
599 ALOGE("error unregistering vsync callback: %s (%d)",
600 strerror(-err), err);
601 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700602 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700603 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700604 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700605 }
606
Lloyd Piquee83f9312018-02-01 12:53:17 -0800607 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700608 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700609 mCallback = callback;
610 }
611
Lloyd Piquee83f9312018-02-01 12:53:17 -0800612 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700613 Mutex::Autolock lock(mVsyncMutex);
614
615 // Normalize phaseOffset to [0, period)
616 auto period = mDispSync->getPeriod();
617 phaseOffset %= period;
618 if (phaseOffset < 0) {
619 // If we're here, then phaseOffset is in (-period, 0). After this
620 // operation, it will be in (0, period)
621 phaseOffset += period;
622 }
623 mPhaseOffset = phaseOffset;
624
625 // If we're not enabled, we don't need to mess with the listeners
626 if (!mEnabled) {
627 return;
628 }
629
Dan Stoza84d619e2018-03-28 17:07:36 -0700630 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
631 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700632 if (err != NO_ERROR) {
Dan Stoza84d619e2018-03-28 17:07:36 -0700633 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700634 strerror(-err), err);
635 }
636 }
637
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700638private:
639 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800640 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700641 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700642 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700643 callback = mCallback;
644
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700645 if (mTraceVsync) {
646 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700647 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700648 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700649 }
650
Peiyong Lin566a3b42018-01-09 18:22:43 -0800651 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700652 callback->onVSyncEvent(when);
653 }
654 }
655
Tim Murray4a4e4a22016-04-19 16:29:23 +0000656 const char* const mName;
657
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700658 int mValue;
659
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700660 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700661 const String8 mVsyncOnLabel;
662 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700663
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700664 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700665
666 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800667 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700668
669 Mutex mVsyncMutex; // Protects the following
670 nsecs_t mPhaseOffset;
671 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700672};
673
Lloyd Piquee83f9312018-02-01 12:53:17 -0800674class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700675public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800676 InjectVSyncSource() = default;
677 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700678
Lloyd Piquee83f9312018-02-01 12:53:17 -0800679 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700680 std::lock_guard<std::mutex> lock(mCallbackMutex);
681 mCallback = callback;
682 }
683
Lloyd Piquee83f9312018-02-01 12:53:17 -0800684 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700685 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700686 if (mCallback) {
687 mCallback->onVSyncEvent(when);
688 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700689 }
690
Lloyd Piquee83f9312018-02-01 12:53:17 -0800691 void setVSyncEnabled(bool) override {}
692 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700693
694private:
695 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800696 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700697};
698
Wei Wangf9b05ee2017-07-19 20:59:39 -0700699// Do not call property_set on main thread which will be blocked by init
700// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700701void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700702 ALOGI( "SurfaceFlinger's main thread ready to run. "
703 "Initializing graphics H/W...");
704
Thierry Strudel2924d012017-08-14 15:19:37 -0700705 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900706
Steven Thomasb02664d2017-07-26 18:48:28 -0700707 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800708
Steven Thomasb02664d2017-07-26 18:48:28 -0700709 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800710 mEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700711 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
712 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800713 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700714 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800715 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800716 "appEventThread");
717 mSfEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700718 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800719 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800720
Lloyd Pique24b0a482018-03-09 18:52:26 -0800721 mSFEventThread =
722 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700723 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800724 [this](nsecs_t timestamp) {
725 mInterceptor->saveVSyncEvent(timestamp);
726 },
727 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800728 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200729 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800730
Steven Thomasb02664d2017-07-26 18:48:28 -0700731 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800732 getBE().mRenderEngine =
733 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
734 hasWideColorDisplay
735 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
736 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800737 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700738
739 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
740 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800741 getBE().mHwc.reset(
742 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700743 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800744 // Process any initial hotplug and resulting display changes.
745 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700746 const auto display = getDefaultDisplayDeviceLocked();
747 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
748 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
749 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800750
Lloyd Piquefcd86612017-12-14 17:15:36 -0800751 // make the default display GLContext current so that we can create textures
752 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700753 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800754
Steven Thomas050b2c82017-03-06 11:45:16 -0800755 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700756 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700757 // This callback is called from the vr flinger dispatch thread. We
758 // need to call signalTransaction(), which requires holding
759 // mStateLock when we're not on the main thread. Acquiring
760 // mStateLock from the vr flinger dispatch thread might trigger a
761 // deadlock in surface flinger (see b/66916578), so post a message
762 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700763 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700764 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
765 mVrFlingerRequestsDisplay = requestDisplay;
766 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700767 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800768 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700769 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
770 getHwComposer()
771 .getHwcDisplayId(display->getId())
772 .value_or(0),
773 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800774 if (!mVrFlinger) {
775 ALOGE("Failed to start vrflinger");
776 }
777 }
778
Lloyd Pique379adc12018-01-22 17:31:47 -0800779 mEventControlThread = std::make_unique<impl::EventControlThread>(
780 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700781
Mathias Agopian92a979a2012-08-02 18:32:23 -0700782 // initialize our drawing state
783 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700784
Andy McFadden13a082e2012-08-24 10:16:42 -0700785 // set initial conditions (e.g. unblank default device)
786 initializeDisplays();
787
David Sodmanbc815282017-11-05 18:57:52 -0800788 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700789
Wei Wangf9b05ee2017-07-19 20:59:39 -0700790 // Inform native graphics APIs whether the present timestamp is supported:
791 if (getHwComposer().hasCapability(
792 HWC2::Capability::PresentFenceIsNotReliable)) {
793 mStartPropertySetThread = new StartPropertySetThread(false);
794 } else {
795 mStartPropertySetThread = new StartPropertySetThread(true);
796 }
797
798 if (mStartPropertySetThread->Start() != NO_ERROR) {
799 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800800 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800801
Chia-I Wud49d6692018-06-27 07:17:41 +0800802 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
803 // is used to saturate legacy sRGB content. However, to make sure the same color under
804 // Display P3 will be saturated to the same color, we intentionally break the API spec
805 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
806 // such saturation matrix on Display P3 is understood fully, the API should always return
807 // identify matrix.
808 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
809 Dataspace::SRGB_LINEAR);
810
811 // we will apply this on Display P3.
812 if (mEnhancedSaturationMatrix != mat4()) {
813 ColorSpace srgb(ColorSpace::sRGB());
814 ColorSpace displayP3(ColorSpace::DisplayP3());
815 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
816 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
817 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
818 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800819
Dan Stoza9e56aa02015-11-02 13:00:03 -0800820 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700821}
822
Romain Guy11d63f42017-07-20 12:47:14 -0700823void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700824 Mutex::Autolock _l(mStateLock);
825
Romain Guy11d63f42017-07-20 12:47:14 -0700826 char value[PROPERTY_VALUE_MAX];
827
828 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800829 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700830 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800831 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100832
833 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700834 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700835}
836
Mathias Agopiana67e4182012-06-19 17:26:12 -0700837void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800838 // Start boot animation service by setting a property mailbox
839 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700840 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800841 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700842 if (mStartPropertySetThread->join() != NO_ERROR) {
843 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800844 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700845}
846
Mathias Agopian875d8e12013-06-07 15:35:48 -0700847size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800848 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700849}
850
Mathias Agopian875d8e12013-06-07 15:35:48 -0700851size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800852 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700853}
854
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800855// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800856
Jamie Gennis582270d2011-08-17 18:19:00 -0700857bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800858 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800859 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800860 return authenticateSurfaceTextureLocked(bufferProducer);
861}
862
863bool SurfaceFlinger::authenticateSurfaceTextureLocked(
864 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800865 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800866 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800867}
868
Brian Anderson6b376712017-04-04 10:51:39 -0700869status_t SurfaceFlinger::getSupportedFrameTimestamps(
870 std::vector<FrameEvent>* outSupported) const {
871 *outSupported = {
872 FrameEvent::REQUESTED_PRESENT,
873 FrameEvent::ACQUIRE,
874 FrameEvent::LATCH,
875 FrameEvent::FIRST_REFRESH_START,
876 FrameEvent::LAST_REFRESH_START,
877 FrameEvent::GPU_COMPOSITION_DONE,
878 FrameEvent::DEQUEUE_READY,
879 FrameEvent::RELEASE,
880 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700881 ConditionalLock _l(mStateLock,
882 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700883 if (!getHwComposer().hasCapability(
884 HWC2::Capability::PresentFenceIsNotReliable)) {
885 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
886 }
887 return NO_ERROR;
888}
889
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700890status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
891 Vector<DisplayInfo>* configs) {
892 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700893 return BAD_VALUE;
894 }
895
Jesse Hall692c7232012-11-08 15:41:56 -0800896 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700897 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
898 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700899 type = i;
900 break;
901 }
902 }
903
904 if (type < 0) {
905 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700906 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700907
Mathias Agopian8b736f12012-08-13 17:54:26 -0700908 // TODO: Not sure if display density should handled by SF any longer
909 class Density {
910 static int getDensityFromProperty(char const* propName) {
911 char property[PROPERTY_VALUE_MAX];
912 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800913 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700914 density = atoi(property);
915 }
916 return density;
917 }
918 public:
919 static int getEmuDensity() {
920 return getDensityFromProperty("qemu.sf.lcd_density"); }
921 static int getBuildDensity() {
922 return getDensityFromProperty("ro.sf.lcd_density"); }
923 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700924
Dan Stoza7f7da322014-05-02 15:26:25 -0700925 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700926
Steven Thomas6d8110b2017-08-31 18:24:21 -0700927 ConditionalLock _l(mStateLock,
928 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800929 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700930 DisplayInfo info = DisplayInfo();
931
Dan Stoza9e56aa02015-11-02 13:00:03 -0800932 float xdpi = hwConfig->getDpiX();
933 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700934
935 if (type == DisplayDevice::DISPLAY_PRIMARY) {
936 // The density of the device is provided by a build property
937 float density = Density::getBuildDensity() / 160.0f;
938 if (density == 0) {
939 // the build doesn't provide a density -- this is wrong!
940 // use xdpi instead
941 ALOGE("ro.sf.lcd_density must be defined as a build property");
942 density = xdpi / 160.0f;
943 }
944 if (Density::getEmuDensity()) {
945 // if "qemu.sf.lcd_density" is specified, it overrides everything
946 xdpi = ydpi = density = Density::getEmuDensity();
947 density /= 160.0f;
948 }
949 info.density = density;
950
951 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700952 const auto display = getDefaultDisplayDeviceLocked();
953 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700954 } else {
955 // TODO: where should this value come from?
956 static const int TV_DENSITY = 213;
957 info.density = TV_DENSITY / 160.0f;
958 info.orientation = 0;
959 }
960
Dan Stoza9e56aa02015-11-02 13:00:03 -0800961 info.w = hwConfig->getWidth();
962 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700963 info.xdpi = xdpi;
964 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800965 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900966 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800967
Andy McFadden91b2ca82014-06-13 14:04:23 -0700968 // This is how far in advance a buffer must be queued for
969 // presentation at a given time. If you want a buffer to appear
970 // on the screen at time N, you must submit the buffer before
971 // (N - presentationDeadline).
972 //
973 // Normally it's one full refresh period (to give SF a chance to
974 // latch the buffer), but this can be reduced by configuring a
975 // DispSync offset. Any additional delays introduced by the hardware
976 // composer or panel must be accounted for here.
977 //
978 // We add an additional 1ms to allow for processing time and
979 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800980 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800981 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700982
983 // All non-virtual displays are currently considered secure.
984 info.secure = true;
985
Iris Chang7501ed62018-04-30 14:45:42 +0800986 if (type == DisplayDevice::DISPLAY_PRIMARY &&
987 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
988 std::swap(info.w, info.h);
989 }
990
Michael Wright28f24d02016-07-12 13:30:53 -0700991 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700992 }
993
Dan Stoza7f7da322014-05-02 15:26:25 -0700994 return NO_ERROR;
995}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700996
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700997status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
998 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700999 return BAD_VALUE;
1000 }
1001
1002 // FIXME for now we always return stats for the primary display
1003 memset(stats, 0, sizeof(*stats));
Lloyd Pique41be5d22018-06-21 13:11:48 -07001004 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1005 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001006 return NO_ERROR;
1007}
1008
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001009int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
1010 const auto display = getDisplayDevice(displayToken);
1011 if (!display) {
1012 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +08001013 return BAD_VALUE;
1014 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001015
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001016 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -07001017}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001018
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001019void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
1020 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001021 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001022 return;
1023 }
1024
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001025 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001026 ALOGW("Trying to set config for virtual display");
1027 return;
1028 }
1029
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001030 display->setActiveConfig(mode);
1031 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001032}
1033
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001034status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001035 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001036 Vector<DisplayInfo> configs;
1037 getDisplayConfigs(displayToken, &configs);
1038 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
1039 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
1040 configs.size());
1041 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001042 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001043 const auto display = getDisplayDevice(displayToken);
1044 if (!display) {
1045 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
1046 displayToken.get());
1047 } else if (display->isVirtual()) {
1048 ALOGW("Attempt to set active config %d for virtual display", mode);
1049 } else {
1050 setActiveConfigInternal(display, mode);
1051 }
1052 }));
1053
Mathias Agopian888c8222012-08-04 21:10:38 -07001054 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001055}
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001056status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1057 Vector<ColorMode>* outColorModes) {
1058 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001059 return BAD_VALUE;
1060 }
1061
Michael Wright28f24d02016-07-12 13:30:53 -07001062 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001063 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
1064 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -07001065 type = i;
1066 break;
1067 }
1068 }
1069
1070 if (type < 0) {
1071 return type;
1072 }
1073
Peiyong Lina52f0292018-03-14 17:26:31 -07001074 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001075 {
1076 ConditionalLock _l(mStateLock,
1077 std::this_thread::get_id() != mMainThreadId);
1078 modes = getHwComposer().getColorModes(type);
1079 }
Michael Wright28f24d02016-07-12 13:30:53 -07001080 outColorModes->clear();
1081 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1082
1083 return NO_ERROR;
1084}
1085
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001086ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1087 if (const auto display = getDisplayDevice(displayToken)) {
1088 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001089 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001090 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001091}
1092
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001093void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1094 Dataspace dataSpace, RenderIntent renderIntent) {
1095 ColorMode currentMode = display->getActiveColorMode();
1096 Dataspace currentDataSpace = display->getCompositionDataSpace();
1097 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001098
Peiyong Lin38e9a562018-04-10 16:24:20 -07001099 if (mode == currentMode && dataSpace == currentDataSpace &&
1100 renderIntent == currentRenderIntent) {
1101 return;
1102 }
1103
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001104 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001105 ALOGW("Trying to set config for virtual display");
1106 return;
1107 }
1108
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001109 display->setActiveColorMode(mode);
1110 display->setCompositionDataSpace(dataSpace);
1111 display->setActiveRenderIntent(renderIntent);
1112 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001113
1114 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001115 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1116 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001117}
1118
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001119status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001120 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001121 Vector<ColorMode> modes;
1122 getDisplayColorModes(displayToken, &modes);
1123 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1124 if (mode < ColorMode::NATIVE || !exists) {
1125 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1126 decodeColorMode(mode).c_str(), mode, displayToken.get());
1127 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001128 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001129 const auto display = getDisplayDevice(displayToken);
1130 if (!display) {
1131 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1132 decodeColorMode(mode).c_str(), mode, displayToken.get());
1133 } else if (display->isVirtual()) {
1134 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1135 decodeColorMode(mode).c_str(), mode);
1136 } else {
1137 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1138 RenderIntent::COLORIMETRIC);
1139 }
1140 }));
1141
Michael Wright28f24d02016-07-12 13:30:53 -07001142 return NO_ERROR;
1143}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001144
Svetoslavd85084b2014-03-20 10:28:31 -07001145status_t SurfaceFlinger::clearAnimationFrameStats() {
1146 Mutex::Autolock _l(mStateLock);
1147 mAnimFrameTracker.clearStats();
1148 return NO_ERROR;
1149}
1150
1151status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1152 Mutex::Autolock _l(mStateLock);
1153 mAnimFrameTracker.getStats(outStats);
1154 return NO_ERROR;
1155}
1156
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001157status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1158 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001159 Mutex::Autolock _l(mStateLock);
1160
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001161 const auto display = getDisplayDeviceLocked(displayToken);
1162 if (!display) {
1163 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001164 return BAD_VALUE;
1165 }
1166
Peiyong Linfb069302018-04-25 14:34:31 -07001167 // At this point the DisplayDeivce should already be set up,
1168 // meaning the luminance information is already queried from
1169 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001170 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001171 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1172 capabilities.getDesiredMaxLuminance(),
1173 capabilities.getDesiredMaxAverageLuminance(),
1174 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001175
1176 return NO_ERROR;
1177}
1178
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001179status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001180 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001181 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001182
Chia-I Wu90f669f2017-10-05 14:24:41 -07001183 if (mInjectVSyncs == enable) {
1184 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001185 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001186
1187 if (enable) {
1188 ALOGV("VSync Injections enabled");
1189 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001190 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001191 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001192 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001193 impl::EventThread::InterceptVSyncsCallback(),
1194 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001195 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001196 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001197 } else {
1198 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001199 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001200 }
1201
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001202 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001203 }));
1204
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001205 return NO_ERROR;
1206}
1207
1208status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001209 Mutex::Autolock _l(mStateLock);
1210
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001211 if (!mInjectVSyncs) {
1212 ALOGE("VSync Injections not enabled");
1213 return BAD_VALUE;
1214 }
1215 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1216 ALOGV("Injecting VSync inside SurfaceFlinger");
1217 mVSyncInjector->onInjectSyncEvent(when);
1218 }
1219 return NO_ERROR;
1220}
1221
Lloyd Pique755e3192018-01-31 16:46:15 -08001222status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1223 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001224 IPCThreadState* ipc = IPCThreadState::self();
1225 const int pid = ipc->getCallingPid();
1226 const int uid = ipc->getCallingUid();
1227 if ((uid != AID_SHELL) &&
1228 !PermissionCache::checkPermission(sDump, pid, uid)) {
1229 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1230 return PERMISSION_DENIED;
1231 }
1232
1233 // Try to acquire a lock for 1s, fail gracefully
1234 const status_t err = mStateLock.timedLock(s2ns(1));
1235 const bool locked = (err == NO_ERROR);
1236 if (!locked) {
1237 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1238 return TIMED_OUT;
1239 }
1240
1241 outLayers->clear();
1242 mCurrentState.traverseInZOrder([&](Layer* layer) {
1243 outLayers->push_back(layer->getLayerDebugInfo());
1244 });
1245
1246 mStateLock.unlock();
1247 return NO_ERROR;
1248}
1249
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001250// ----------------------------------------------------------------------------
1251
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001252sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1253 ISurfaceComposer::VsyncSource vsyncSource) {
1254 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1255 return mSFEventThread->createEventConnection();
1256 } else {
1257 return mEventThread->createEventConnection();
1258 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001259}
1260
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001261// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001262
1263void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001264 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001265}
1266
1267void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001268 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001269}
1270
1271void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001272 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001273}
1274
1275void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001276 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001277 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001278}
1279
1280status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001281 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001282 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001283}
1284
1285status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001286 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001287 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001288 if (res == NO_ERROR) {
1289 msg->wait();
1290 }
1291 return res;
1292}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001293
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001294void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001295 do {
1296 waitForEvent();
1297 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001298}
1299
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001300void SurfaceFlinger::enableHardwareVsync() {
1301 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001302 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001303 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001304 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001305 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001306 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001307}
1308
Jesse Hall948fe0c2013-10-14 12:56:09 -07001309void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001310 Mutex::Autolock _l(mHWVsyncLock);
1311
Jesse Hall948fe0c2013-10-14 12:56:09 -07001312 if (makeAvailable) {
1313 mHWVsyncAvailable = true;
1314 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001315 // Hardware vsync is not currently available, so abort the resync
1316 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001317 return;
1318 }
1319
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001320 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1321 if (!getHwComposer().isConnected(displayId)) {
1322 return;
1323 }
1324
1325 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001326 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001327
Lloyd Pique41be5d22018-06-21 13:11:48 -07001328 mPrimaryDispSync->reset();
1329 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001330
1331 if (!mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001332 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001333 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001334 mPrimaryHWVsyncEnabled = true;
1335 }
1336}
1337
Jesse Hall948fe0c2013-10-14 12:56:09 -07001338void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001339 Mutex::Autolock _l(mHWVsyncLock);
1340 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001341 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001342 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001343 mPrimaryHWVsyncEnabled = false;
1344 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001345 if (makeUnavailable) {
1346 mHWVsyncAvailable = false;
1347 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001348}
1349
Tim Murray4a4e4a22016-04-19 16:29:23 +00001350void SurfaceFlinger::resyncWithRateLimit() {
1351 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001352
1353 // No explicit locking is needed here since EventThread holds a lock while calling this method
1354 static nsecs_t sLastResyncAttempted = 0;
1355 const nsecs_t now = systemTime();
1356 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001357 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001358 }
Dan Stoza57164302017-05-08 14:03:54 -07001359 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001360}
1361
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001362void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1363 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001364 ATRACE_NAME("SF onVsync");
1365
Steven Thomas3cfac282017-02-06 12:29:30 -08001366 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001367 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001368 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001369 return;
1370 }
1371
1372 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001373 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001374 return;
1375 }
1376
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001377 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1378 // For now, we don't do anything with external display vsyncs.
1379 return;
1380 }
1381
Jamie Gennisd1700752013-10-14 12:22:52 -07001382 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001383
Jamie Gennisd1700752013-10-14 12:22:52 -07001384 { // Scope for the lock
1385 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001386 if (mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001387 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001388 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001389 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001390
1391 if (needsHwVsync) {
1392 enableHardwareVsync();
1393 } else {
1394 disableHardwareVsync(false);
1395 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001396}
1397
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001398void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001399 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1400 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001401}
1402
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001403void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001404 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001405 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001406 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001407
Lloyd Piqueba04e622017-12-14 17:11:26 -08001408 // Ignore events that do not have the right sequenceId.
1409 if (sequenceId != getBE().mComposerSequenceId) {
1410 return;
1411 }
1412
Steven Thomasb02664d2017-07-26 18:48:28 -07001413 // Only lock if we're not on the main thread. This function is normally
1414 // called on a hwbinder thread, but for the primary display it's called on
1415 // the main thread with the state lock already held, so don't attempt to
1416 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001417 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001418
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001419 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001420
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001421 if (std::this_thread::get_id() == mMainThreadId) {
1422 // Process all pending hot plug events immediately if we are on the main thread.
1423 processDisplayHotplugEventsLocked();
1424 }
1425
Lloyd Piqueba04e622017-12-14 17:11:26 -08001426 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001427}
1428
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001429void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001430 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001431 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001432 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001433 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001434 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001435}
1436
Dan Stoza9e56aa02015-11-02 13:00:03 -08001437void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001438 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001439 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001440 getHwComposer().setVsyncEnabled(disp,
1441 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001442}
1443
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001444// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001445void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001446 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001447 // Clear the drawing state so that the logic inside of
1448 // handleTransactionLocked will fire. It will determine the delta between
1449 // mCurrentState and mDrawingState and re-apply all changes when we make the
1450 // transition.
1451 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001452 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001453 mDisplays.clear();
1454}
1455
Steven Thomas050b2c82017-03-06 11:45:16 -08001456void SurfaceFlinger::updateVrFlinger() {
1457 if (!mVrFlinger)
1458 return;
1459 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001460 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001461 return;
1462 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001463
David Sodman105b7dc2017-11-04 20:28:14 -07001464 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001465 ALOGE("Vr flinger is only supported for remote hardware composer"
1466 " service connections. Ignoring request to transition to vr"
1467 " flinger.");
1468 mVrFlingerRequestsDisplay = false;
1469 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001470 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001471
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001472 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001473
Steven Thomas0123ac62018-07-12 11:32:34 -07001474 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001475 LOG_ALWAYS_FATAL_IF(!display);
1476 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001477 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1478 // called below. Clear the reference now so we don't accidentally use it
1479 // later.
1480 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001481
Steven Thomasb02664d2017-07-26 18:48:28 -07001482 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001483 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001484 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001485
Steven Thomasb02664d2017-07-26 18:48:28 -07001486 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001487 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001488 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1489 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001490 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001491
David Sodman105b7dc2017-11-04 20:28:14 -07001492 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1493 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001494
1495 if (vrFlingerRequestsDisplay) {
1496 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001497 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001498
1499 mVisibleRegionsDirty = true;
1500 invalidateHwcGeometry();
1501
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001502 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001503 display = getDefaultDisplayDeviceLocked();
1504 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001505 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001506
Steven Thomasb02664d2017-07-26 18:48:28 -07001507 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001508 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001509 const nsecs_t period = activeConfig->getVsyncPeriod();
1510 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001511
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001512 // The present fences returned from vr_hwc are not an accurate
1513 // representation of vsync times.
Lloyd Pique41be5d22018-06-21 13:11:48 -07001514 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1515 !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001516
Steven Thomasb02664d2017-07-26 18:48:28 -07001517 // Use phase of 0 since phase is not known.
1518 // Use latency of 0, which will snap to the ideal latency.
1519 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001520
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001521 resyncToHardwareVsync(false);
1522
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001523 android_atomic_or(1, &mRepaintEverything);
1524 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001525}
1526
Mathias Agopian4fec8732012-06-29 14:12:52 -07001527void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001528 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001529 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001530 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001531 bool frameMissed = !mHadClientComposition &&
1532 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001533 (mPreviousPresentFence->getSignalTime() ==
1534 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001535 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001536 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001537 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001538 mTimeStats.incrementMissedFrames();
1539 if (mPropagateBackpressure) {
1540 signalLayerUpdate();
1541 break;
1542 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001543 }
Dan Stoza50182882016-07-08 12:02:20 -07001544
Steven Thomas050b2c82017-03-06 11:45:16 -08001545 // Now that we're going to make it to the handleMessageTransaction()
1546 // call below it's safe to call updateVrFlinger(), which will
1547 // potentially trigger a display handoff.
1548 updateVrFlinger();
1549
Dan Stoza6b9454d2014-11-07 16:00:59 -08001550 bool refreshNeeded = handleMessageTransaction();
1551 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001552 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001553 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001554 // Signal a refresh if a transaction modified the window state,
1555 // a new buffer was latched, or if HWC has requested a full
1556 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001557 signalRefresh();
1558 }
1559 break;
1560 }
1561 case MessageQueue::REFRESH: {
1562 handleMessageRefresh();
1563 break;
1564 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001565 }
1566}
1567
Dan Stoza6b9454d2014-11-07 16:00:59 -08001568bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001569 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001570 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001571 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001572 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001573 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001574 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001575}
1576
Dan Stoza6b9454d2014-11-07 16:00:59 -08001577bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001578 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001579 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001580}
1581
1582void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001583 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001584
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001585 mRefreshPending = false;
1586
Lloyd Pique074e8122018-07-26 12:57:23 -07001587 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1588
1589 preComposition(refreshStartTime);
1590 rebuildLayerStacks();
1591 setUpHWComposer();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001592 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001593 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001594 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001595 doComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001596 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001597
Dan Stozabfbffeb2016-07-21 14:49:33 -07001598 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001599 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001600 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001601 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001602 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001603 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001604
Dan Stoza9e56aa02015-11-02 13:00:03 -08001605 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001606}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001607
Mathias Agopiancd60f992012-08-16 16:28:27 -07001608void SurfaceFlinger::doDebugFlashRegions()
1609{
1610 // is debugging enabled
1611 if (CC_LIKELY(!mDebugRegion))
1612 return;
1613
1614 const bool repaintEverything = mRepaintEverything;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001615 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001616 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001617 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001618 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001619 if (!dirtyRegion.isEmpty()) {
1620 // redraw the whole screen
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001621 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001622
1623 // and draw the dirty region
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001624 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001625 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001626 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1627
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001628 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001629 }
1630 }
1631 }
1632
1633 postFramebuffer();
1634
1635 if (mDebugRegion > 1) {
1636 usleep(mDebugRegion * 1000);
1637 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001638
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001639 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001640 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001641 continue;
1642 }
1643
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001644 status_t result = display->prepareFrame(*getBE().mHwc);
1645 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001646 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001647 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001648}
1649
Adrian Roos1e1a1282017-11-01 19:05:31 +01001650void SurfaceFlinger::doTracing(const char* where) {
1651 ATRACE_CALL();
1652 ATRACE_NAME(where);
1653 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001654 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001655 }
1656}
1657
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001658void SurfaceFlinger::logLayerStats() {
1659 ATRACE_CALL();
1660 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001661 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001662 if (display->isPrimary()) {
1663 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001664 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001665 }
1666 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001667
1668 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001669 }
1670}
1671
Lloyd Pique074e8122018-07-26 12:57:23 -07001672void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001673{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001674 ATRACE_CALL();
1675 ALOGV("preComposition");
1676
Mathias Agopiancd60f992012-08-16 16:28:27 -07001677 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001678 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique074e8122018-07-26 12:57:23 -07001679 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001680 needExtraInvalidate = true;
1681 }
Robert Carr2047fae2016-11-28 14:09:09 -08001682 });
1683
Mathias Agopiancd60f992012-08-16 16:28:27 -07001684 if (needExtraInvalidate) {
1685 signalLayerUpdate();
1686 }
1687}
1688
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001689void SurfaceFlinger::updateCompositorTiming(
1690 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1691 std::shared_ptr<FenceTime>& presentFenceTime) {
1692 // Update queue of past composite+present times and determine the
1693 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001694 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001695 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001696 while (!getBE().mCompositePresentTimes.empty()) {
1697 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001698 // Cached values should have been updated before calling this method,
1699 // which helps avoid duplicate syscalls.
1700 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1701 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1702 break;
1703 }
1704 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001705 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001706 }
1707
1708 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001709 while (getBE().mCompositePresentTimes.size() > 16) {
1710 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001711 }
1712
Brian Andersond0010582017-03-07 13:20:31 -08001713 setCompositorTimingSnapped(
1714 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1715}
1716
1717void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1718 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001719 // Integer division and modulo round toward 0 not -inf, so we need to
1720 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001721 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001722 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1723 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1724
Brian Andersond0010582017-03-07 13:20:31 -08001725 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1726 if (idealLatency <= 0) {
1727 idealLatency = vsyncInterval;
1728 }
1729
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001730 // Snap the latency to a value that removes scheduling jitter from the
1731 // composition and present times, which often have >1ms of jitter.
1732 // Reducing jitter is important if an app attempts to extrapolate
1733 // something (such as user input) to an accurate diasplay time.
1734 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1735 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001736 nsecs_t bias = vsyncInterval / 2;
1737 int64_t extraVsyncs =
1738 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1739 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1740 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001741
David Sodman99974d22017-11-28 12:04:33 -08001742 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1743 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1744 getBE().mCompositorTiming.interval = vsyncInterval;
1745 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001746}
1747
Lloyd Pique074e8122018-07-26 12:57:23 -07001748void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001749{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001750 ATRACE_CALL();
1751 ALOGV("postComposition");
1752
Brian Anderson3546a3f2016-07-14 11:51:14 -07001753 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001754 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001755 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001756 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001757 }
1758
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001759 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001760 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001761
David Sodman73beded2017-11-15 11:56:06 -08001762 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001763 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001764 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001765 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001766 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001767 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001768 } else {
1769 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1770 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001771
David Sodman73beded2017-11-15 11:56:06 -08001772 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001773 mPreviousPresentFence =
1774 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1775 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001776 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001777
Lloyd Pique41be5d22018-06-21 13:11:48 -07001778 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1779 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001780
Lloyd Pique074e8122018-07-26 12:57:23 -07001781 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001782 // when we started doing work for this frame, but that should be okay
1783 // since updateCompositorTiming has snapping logic.
1784 updateCompositorTiming(
Lloyd Pique074e8122018-07-26 12:57:23 -07001785 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001786 CompositorTiming compositorTiming;
1787 {
David Sodman99974d22017-11-28 12:04:33 -08001788 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1789 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001790 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001791
Robert Carr2047fae2016-11-28 14:09:09 -08001792 mDrawingState.traverseInZOrder([&](Layer* layer) {
1793 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001794 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001795 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001796 recordBufferingStats(layer->getName().string(),
1797 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001798 }
Robert Carr2047fae2016-11-28 14:09:09 -08001799 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001800
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001801 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001802 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001803 enableHardwareVsync();
1804 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001805 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001806 }
1807 }
1808
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001809 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001810 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001811 enableHardwareVsync();
1812 }
1813 }
1814
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001815 if (mAnimCompositionPending) {
1816 mAnimCompositionPending = false;
1817
Brian Anderson4e606e32017-03-16 15:34:57 -07001818 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001819 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001820 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001821 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001822 // The HWC doesn't support present fences, so use the refresh
1823 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001824 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001825 mAnimFrameTracker.setActualPresentTime(presentTime);
1826 }
1827 mAnimFrameTracker.advanceFrame();
1828 }
Dan Stozab90cf072015-03-05 11:05:59 -08001829
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001830 mTimeStats.incrementTotalFrames();
1831 if (mHadClientComposition) {
1832 mTimeStats.incrementClientCompositionFrames();
1833 }
1834
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001835 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001836 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001837 return;
1838 }
1839
1840 nsecs_t currentTime = systemTime();
1841 if (mHasPoweredOff) {
1842 mHasPoweredOff = false;
1843 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001844 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001845 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001846 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1847 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001848 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001849 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001850 }
David Sodman4a36e932017-11-07 14:29:47 -08001851 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001852 }
David Sodman4a36e932017-11-07 14:29:47 -08001853 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001854
1855 {
1856 std::lock_guard lock(mTexturePoolMutex);
1857 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1858 if (refillCount > 0) {
1859 const size_t offset = mTexturePool.size();
1860 mTexturePool.resize(mTexturePoolSize);
1861 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1862 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1863 }
1864 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001865}
1866
1867void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001868 ATRACE_CALL();
1869 ALOGV("rebuildLayerStacks");
1870
Mathias Agopiancd60f992012-08-16 16:28:27 -07001871 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001872 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001873 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001874 mVisibleRegionsDirty = false;
1875 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001876
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001877 for (const auto& pair : mDisplays) {
1878 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001879 Region opaqueRegion;
1880 Region dirtyRegion;
1881 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001882 Vector<sp<Layer>> layersNeedingFences;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001883 const Transform& tr = display->getTransform();
1884 const Rect bounds = display->getBounds();
1885 if (display->isPoweredOn()) {
1886 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001887
Jeff Sharkey76488112017-02-27 14:15:18 -07001888 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001889 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001890 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001891 Region drawRegion(tr.transform(
1892 layer->visibleNonTransparentRegion));
1893 drawRegion.andSelf(bounds);
1894 if (!drawRegion.isEmpty()) {
1895 layersSortedByZ.add(layer);
1896 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001897 // Clear out the HWC layer if this layer was
1898 // previously visible, but no longer is
1899 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001900 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001901 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001902 // WM changes display->layerStack upon sleep/awake.
1903 // Here we make sure we delete the HWC layers even if
1904 // WM changed their layer stack.
1905 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001906 }
1907
1908 // If a layer is not going to get a release fence because
1909 // it is invisible, but it is also going to release its
1910 // old buffer, add it to the list of layers needing
1911 // fences.
1912 if (hwcLayerDestroyed) {
1913 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1914 mLayersWithQueuedFrames.cend(), layer);
1915 if (found != mLayersWithQueuedFrames.cend()) {
1916 layersNeedingFences.add(layer);
1917 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001918 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001919 });
1920 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001921 display->setVisibleLayersSortedByZ(layersSortedByZ);
1922 display->setLayersNeedingFences(layersNeedingFences);
1923 display->undefinedRegion.set(bounds);
1924 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1925 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001926 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001927 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001928}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001929
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001930// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001931// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001932// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001933// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001934// The returned HDR data space is one of
1935// - Dataspace::UNKNOWN
1936// - Dataspace::BT2020_HLG
1937// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001938Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1939 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001940 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001941 *outHdrDataSpace = Dataspace::UNKNOWN;
1942
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001943 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001944 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001945 case Dataspace::V0_SCRGB:
1946 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001947 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001948 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001949 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001950 case Dataspace::BT2020_PQ:
1951 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001952 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001953 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001954 case Dataspace::BT2020_HLG:
1955 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001956 // When there's mixed PQ content and HLG content, we set the HDR
1957 // data space to be BT2020_PQ and convert HLG to PQ.
1958 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1959 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001960 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001961 break;
1962 default:
1963 break;
1964 }
Romain Guy54f154a2017-10-24 21:40:32 +01001965 }
1966
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001967 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001968}
1969
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001970// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001971void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1972 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001973 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1974 *outMode = ColorMode::NATIVE;
1975 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001976 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001977 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001978 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001979
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001980 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001981 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001982
Peiyong Lindfde5112018-06-05 10:58:41 -07001983 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001984 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001985 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001986 if (isHdr) {
1987 bestDataSpace = hdrDataSpace;
1988 }
1989
Chia-I Wu0d711262018-05-21 15:19:35 -07001990 RenderIntent intent;
1991 switch (mDisplayColorSetting) {
1992 case DisplayColorSetting::MANAGED:
1993 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001994 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001995 break;
1996 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001997 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001998 break;
1999 default: // vendor display color setting
2000 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2001 break;
2002 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002003
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002004 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002005}
2006
Lloyd Pique074e8122018-07-26 12:57:23 -07002007void SurfaceFlinger::setUpHWComposer() {
2008 ATRACE_CALL();
2009 ALOGV("setUpHWComposer");
Lloyd Piqueb7d12302018-07-26 12:56:47 -07002010
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002011 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002012 bool dirty = !display->getDirtyRegion(mRepaintEverything).isEmpty();
2013 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2014 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
Jesse Hallb7a05492014-08-14 15:45:06 -07002015
2016 // If nothing has changed (!dirty), don't recompose.
2017 // If something changed, but we don't currently have any visible layers,
2018 // and didn't when we last did a composition, then skip it this time.
2019 // The second rule does two things:
2020 // - When all layers are removed from a display, we'll emit one black
2021 // frame, then nothing more until we get new layers.
2022 // - When a display is created with a private layer stack, we won't
2023 // emit any black frames until a layer is added to the layer stack.
2024 bool mustRecompose = dirty && !(empty && wasEmpty);
2025
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002026 ALOGV_IF(display->isVirtual(), "Display %d: %s composition (%sdirty %sempty %swasEmpty)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002027 display->getId(), mustRecompose ? "doing" : "skipping", dirty ? "+" : "-",
2028 empty ? "+" : "-", wasEmpty ? "+" : "-");
Jesse Hallb7a05492014-08-14 15:45:06 -07002029
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002030 display->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07002031
2032 if (mustRecompose) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002033 display->lastCompositionHadVisibleLayers = !empty;
Jesse Hallb7a05492014-08-14 15:45:06 -07002034 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07002035 }
2036
Lloyd Pique074e8122018-07-26 12:57:23 -07002037 // build the h/w work list
2038 if (CC_UNLIKELY(mGeometryInvalid)) {
2039 mGeometryInvalid = false;
2040 for (const auto& [token, display] : mDisplays) {
2041 const auto displayId = display->getId();
2042 if (displayId >= 0) {
2043 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
2044 for (size_t i = 0; i < currentLayers.size(); i++) {
2045 const auto& layer = currentLayers[i];
2046 if (!layer->hasHwcLayer(displayId)) {
2047 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
2048 layer->forceClientComposition(displayId);
2049 continue;
2050 }
2051 }
2052
2053 layer->setGeometry(display, i);
2054 if (mDebugDisableHWC || mDebugRegion) {
2055 layer->forceClientComposition(displayId);
2056 }
2057 }
2058 }
2059 }
2060 }
2061
2062 // Set the per-frame data
2063 for (const auto& [token, display] : mDisplays) {
2064 const auto displayId = display->getId();
2065 if (displayId < 0) {
2066 continue;
2067 }
2068
2069 if (mDrawingState.colorMatrixChanged) {
2070 display->setColorTransform(mDrawingState.colorMatrix);
2071 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
2072 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %d: %d",
2073 displayId, result);
2074 }
2075 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2076 if (layer->isHdrY410()) {
2077 layer->forceClientComposition(displayId);
2078 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2079 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
2080 !display->hasHDR10Support()) {
2081 layer->forceClientComposition(displayId);
2082 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2083 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
2084 !display->hasHLGSupport()) {
2085 layer->forceClientComposition(displayId);
2086 }
2087
2088 if (layer->getForceClientComposition(displayId)) {
2089 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2090 layer->setCompositionType(displayId, HWC2::Composition::Client);
2091 continue;
2092 }
2093
2094 layer->setPerFrameData(display);
2095 }
2096
2097 if (hasWideColorDisplay) {
2098 ColorMode colorMode;
2099 Dataspace dataSpace;
2100 RenderIntent renderIntent;
2101 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
2102 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
2103 }
2104 }
2105
2106 mDrawingState.colorMatrixChanged = false;
2107
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002108 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002109 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002110 continue;
2111 }
2112
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002113 status_t result = display->prepareFrame(*getBE().mHwc);
2114 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002115 display->getId(), result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002116 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002117}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002118
Mathias Agopiancd60f992012-08-16 16:28:27 -07002119void SurfaceFlinger::doComposition() {
2120 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002121 ALOGV("doComposition");
2122
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002123 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002124 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002125 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002126 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002127 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002128
2129 // repaint the framebuffer (if needed)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002130 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002131
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002132 display->dirtyRegion.clear();
2133 display->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002134 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002135 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002136 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002137}
2138
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002139void SurfaceFlinger::postFramebuffer()
2140{
Mathias Agopian841cde52012-03-01 15:44:37 -08002141 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002142 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002143
Mathias Agopiana44b0412011-10-16 18:46:35 -07002144 const nsecs_t now = systemTime();
2145 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002146
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002147 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002148 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002149 continue;
2150 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07002151 const auto displayId = display->getId();
2152 if (displayId >= 0) {
2153 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002154 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002155 display->onSwapBuffersCompleted();
2156 display->makeCurrent();
2157 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002158 sp<Fence> releaseFence = Fence::NO_FENCE;
2159
Chia-I Wu7b549592017-11-15 09:14:57 -08002160 // The layer buffer from the previous frame (if any) is released
2161 // by HWC only when the release fence from this frame (if any) is
2162 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002163 auto hwcLayer = layer->getHwcLayer(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002164 if (displayId >= 0) {
2165 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
2166 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002167
2168 // If the layer was client composited in the previous frame, we
2169 // need to merge with the previous client target acquire fence.
2170 // Since we do not track that, always merge with the current
2171 // client target acquire fence when it is available, even though
2172 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002173 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002174 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002175 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002176 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002177
David Sodmanb8af7922017-12-21 15:17:55 -08002178 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002179 }
Chia-I Wu83806892017-11-16 10:50:20 -08002180
2181 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002182 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002183 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002184 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002185 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002186 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002187 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002188 }
2189 }
2190
Dominik Laskowski7e045462018-05-30 13:02:02 -07002191 if (displayId >= 0) {
2192 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002193 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002194 }
2195
Mathias Agopiana44b0412011-10-16 18:46:35 -07002196 mLastSwapBufferTime = systemTime() - now;
2197 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002198
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002199 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002200 const auto display = getDefaultDisplayDeviceLocked();
2201 if (display && getHwComposer().isConnected(display->getId())) {
2202 const uint32_t flipCount = display->getPageFlipCount();
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002203 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2204 logFrameStats();
2205 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002206 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002207}
2208
Mathias Agopian87baae12012-07-31 12:38:26 -07002209void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002210{
Mathias Agopian841cde52012-03-01 15:44:37 -08002211 ATRACE_CALL();
2212
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002213 // here we keep a copy of the drawing state (that is the state that's
2214 // going to be overwritten by handleTransactionLocked()) outside of
2215 // mStateLock so that the side-effects of the State assignment
2216 // don't happen with mStateLock held (which can cause deadlocks).
2217 State drawingState(mDrawingState);
2218
Mathias Agopianca4d3602011-05-19 15:38:14 -07002219 Mutex::Autolock _l(mStateLock);
2220 const nsecs_t now = systemTime();
2221 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002222
Mathias Agopianca4d3602011-05-19 15:38:14 -07002223 // Here we're guaranteed that some transaction flags are set
2224 // so we can call handleTransactionLocked() unconditionally.
2225 // We call getTransactionFlags(), which will also clear the flags,
2226 // with mStateLock held to guarantee that mCurrentState won't change
2227 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002228
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002229 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002230 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002231 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002232
Mathias Agopianca4d3602011-05-19 15:38:14 -07002233 mLastTransactionTime = systemTime() - now;
2234 mDebugInTransaction = 0;
2235 invalidateHwcGeometry();
2236 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002237}
2238
Dominik Laskowski7e045462018-05-30 13:02:02 -07002239DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002240 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002241 // Figure out whether the event is for the primary display or an
2242 // external display by matching the Hwc display id against one for a
2243 // connected display. If we did not find a match, we then check what
2244 // displays are not already connected to determine the type. If we don't
2245 // have a connected primary display, we assume the new display is meant to
2246 // be the primary display, and then if we don't have an external display,
2247 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002248 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2249 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002250 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002251 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002252 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002253 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002254 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002255 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002256 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002257 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002258 return DisplayDevice::DISPLAY_EXTERNAL;
2259 }
2260
2261 return DisplayDevice::DISPLAY_ID_INVALID;
2262}
2263
Lloyd Piqueba04e622017-12-14 17:11:26 -08002264void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2265 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002266 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002267 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002268 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002269 continue;
2270 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002271
2272 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2273 ALOGE("External displays are not supported by the vr hardware composer.");
2274 continue;
2275 }
2276
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002277 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002278 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002279 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002280 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002281 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002282
2283 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002284 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002285 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002286 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002287 DisplayDeviceState info;
2288 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002289 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2290 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002291 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002292 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002293 mInterceptor->saveDisplayCreation(info);
2294 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002295 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002296 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002297
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002298 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002299 if (idx >= 0) {
2300 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002301 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002302 mCurrentState.displays.removeItemsAt(idx);
2303 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002304 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002305 }
2306
2307 processDisplayChangesLocked();
2308 }
2309
2310 mPendingHotplugEvents.clear();
2311}
2312
Lloyd Pique99d3da52018-01-22 17:48:03 -08002313sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002314 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002315 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002316 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002317 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002318 HdrCapabilities hdrCapabilities;
2319 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002320
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002321 if (hasWideColorDisplay && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002322 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002323 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002324 if (isWideColorMode(colorMode)) {
2325 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002326 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002327
Dominik Laskowski7e045462018-05-30 13:02:02 -07002328 std::vector<RenderIntent> renderIntents =
2329 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002330 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002331 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002332
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002333 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2334 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2335 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002336
2337 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2338 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2339
2340 /*
2341 * Create our display's surface
2342 */
2343 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2344 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002345 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002346 renderSurface->setNativeWindow(nativeWindow.get());
2347 const int displayWidth = renderSurface->queryWidth();
2348 const int displayHeight = renderSurface->queryHeight();
2349
2350 // Make sure that composition can never be stalled by a virtual display
2351 // consumer that isn't processing buffers fast enough. We have to do this
2352 // in two places:
2353 // * Here, in case the display is composed entirely by HWC.
2354 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2355 // window's swap interval in eglMakeCurrent, so they'll override the
2356 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002357 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002358 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2359 }
2360
2361 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002362 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002363
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002364 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002365 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2366 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2367 displayHeight, hasWideColorGamut, hdrCapabilities,
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002368 supportedPerFrameMetadata, hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002369
2370 if (maxFrameBufferAcquiredBuffers >= 3) {
2371 nativeWindowSurface->preallocateBuffers();
2372 }
2373
2374 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002375 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2376 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002377 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002378 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002379 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002380 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002381 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002382 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002383 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002384 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002385 display->setLayerStack(state.layerStack);
2386 display->setProjection(state.orientation, state.viewport, state.frame);
2387 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002388
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002389 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002390}
2391
Lloyd Pique347200f2017-12-14 17:00:15 -08002392void SurfaceFlinger::processDisplayChangesLocked() {
2393 // here we take advantage of Vector's copy-on-write semantics to
2394 // improve performance by skipping the transaction entirely when
2395 // know that the lists are identical
2396 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2397 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2398 if (!curr.isIdenticalTo(draw)) {
2399 mVisibleRegionsDirty = true;
2400 const size_t cc = curr.size();
2401 size_t dc = draw.size();
2402
2403 // find the displays that were removed
2404 // (ie: in drawing state but not in current state)
2405 // also handle displays that changed
2406 // (ie: displays that are in both lists)
2407 for (size_t i = 0; i < dc;) {
2408 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2409 if (j < 0) {
2410 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002411 // Call makeCurrent() on the primary display so we can
2412 // be sure that nothing associated with this display
2413 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002414 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2415 defaultDisplay->makeCurrent();
2416 }
2417 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2418 display->disconnect(getHwComposer());
2419 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002420 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2421 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2422 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2423 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2424 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002425 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002426 } else {
2427 // this display is in both lists. see if something changed.
2428 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002429 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002430 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2431 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2432 if (state_binder != draw_binder) {
2433 // changing the surface is like destroying and
2434 // recreating the DisplayDevice, so we just remove it
2435 // from the drawing state, so that it get re-added
2436 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002437 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2438 display->disconnect(getHwComposer());
2439 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002440 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002441 mDrawingState.displays.removeItemsAt(i);
2442 dc--;
2443 // at this point we must loop to the next item
2444 continue;
2445 }
2446
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002447 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002448 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002449 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002450 }
2451 if ((state.orientation != draw[i].orientation) ||
2452 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002453 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002454 }
2455 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002456 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002457 }
2458 }
2459 }
2460 ++i;
2461 }
2462
2463 // find displays that were added
2464 // (ie: in current state but not in drawing state)
2465 for (size_t i = 0; i < cc; i++) {
2466 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2467 const DisplayDeviceState& state(curr[i]);
2468
2469 sp<DisplaySurface> dispSurface;
2470 sp<IGraphicBufferProducer> producer;
2471 sp<IGraphicBufferProducer> bqProducer;
2472 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002473 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002474
Dominik Laskowski7e045462018-05-30 13:02:02 -07002475 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002476 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002477 // Virtual displays without a surface are dormant:
2478 // they have external state (layer stack, projection,
2479 // etc.) but no internal state (i.e. a DisplayDevice).
2480 if (state.surface != nullptr) {
2481 // Allow VR composer to use virtual displays.
2482 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2483 int width = 0;
2484 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2485 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2486 int height = 0;
2487 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2488 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2489 int intFormat = 0;
2490 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2491 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002492 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002493
Dominik Laskowski7e045462018-05-30 13:02:02 -07002494 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2495 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002496 }
2497
2498 // TODO: Plumb requested format back up to consumer
2499
2500 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002501 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002502 bqProducer, bqConsumer,
2503 state.displayName);
2504
2505 dispSurface = vds;
2506 producer = vds;
2507 }
2508 } else {
2509 ALOGE_IF(state.surface != nullptr,
2510 "adding a supported display, but rendering "
2511 "surface is provided (%p), ignoring it",
2512 state.surface.get());
2513
Dominik Laskowski7e045462018-05-30 13:02:02 -07002514 displayId = state.type;
2515 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002516 producer = bqProducer;
2517 }
2518
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002519 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002520 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002521 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002522 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002523 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002524 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002525 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2526 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2527 true);
2528 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2529 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2530 true);
2531 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002532 }
2533 }
2534 }
2535 }
2536 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002537
2538 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002539}
2540
Mathias Agopian87baae12012-07-31 12:38:26 -07002541void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002542{
Dan Stoza7dde5992015-05-22 09:51:44 -07002543 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002544 mCurrentState.traverseInZOrder([](Layer* layer) {
2545 layer->notifyAvailableFrames();
2546 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002547
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002548 /*
2549 * Traversal of the children
2550 * (perform the transaction for each of them if needed)
2551 */
2552
Mathias Agopian3559b072012-08-15 13:46:03 -07002553 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002554 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002555 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002556 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002557
2558 const uint32_t flags = layer->doTransaction(0);
2559 if (flags & Layer::eVisibleRegion)
2560 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002561 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002562 }
2563
2564 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002565 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002566 */
2567
Mathias Agopiane57f2922012-08-09 16:29:12 -07002568 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002569 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002570 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002571 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002572
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002573 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002574 // The transform hint might have changed for some layers
2575 // (either because a display has changed, or because a layer
2576 // as changed).
2577 //
2578 // Walk through all the layers in currentLayers,
2579 // and update their transform hint.
2580 //
2581 // If a layer is visible only on a single display, then that
2582 // display is used to calculate the hint, otherwise we use the
2583 // default display.
2584 //
2585 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2586 // the hint is set before we acquire a buffer from the surface texture.
2587 //
2588 // NOTE: layer transactions have taken place already, so we use their
2589 // drawing state. However, SurfaceFlinger's own transaction has not
2590 // happened yet, so we must use the current state layer list
2591 // (soon to become the drawing state list).
2592 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002593 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002594 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002595 bool first = true;
2596 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002597 // NOTE: we rely on the fact that layers are sorted by
2598 // layerStack first (so we don't have to traverse the list
2599 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002600 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002601 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002602 currentlayerStack = layerStack;
2603 // figure out if this layerstack is mirrored
2604 // (more than one display) if so, pick the default display,
2605 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002606 hintDisplay = nullptr;
2607 for (const auto& [token, display] : mDisplays) {
2608 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2609 if (hintDisplay) {
2610 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002611 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002612 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002613 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002614 }
2615 }
2616 }
2617 }
Chet Haase91d25932013-04-11 15:24:55 -07002618
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002619 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002620 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2621 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002622
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002623 // could be null when this layer is using a layerStack
2624 // that is not visible on any display. Also can occur at
2625 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002626 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002627 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002628
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002629 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002630 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002631 if (hintDisplay) {
2632 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002633 }
Robert Carr2047fae2016-11-28 14:09:09 -08002634
2635 first = false;
2636 });
Mathias Agopian84300952012-11-21 16:02:13 -08002637 }
2638
2639
Mathias Agopian3559b072012-08-15 13:46:03 -07002640 /*
2641 * Perform our own transaction if needed
2642 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002643
2644 if (mLayersAdded) {
2645 mLayersAdded = false;
2646 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002647 mVisibleRegionsDirty = true;
2648 }
2649
2650 // some layers might have been removed, so
2651 // we need to update the regions they're exposing.
2652 if (mLayersRemoved) {
2653 mLayersRemoved = false;
2654 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002655 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002656 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002657 // this layer is not visible anymore
2658 // TODO: we could traverse the tree from front to back and
2659 // compute the actual visible region
2660 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002661 Region visibleReg;
2662 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002663 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002664 }
Robert Carr2047fae2016-11-28 14:09:09 -08002665 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002666 }
2667
2668 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002669
2670 updateCursorAsync();
2671}
2672
2673void SurfaceFlinger::updateCursorAsync()
2674{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002675 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002676 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002677 continue;
2678 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002679
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002680 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2681 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002682 }
2683 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002684}
2685
2686void SurfaceFlinger::commitTransaction()
2687{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002688 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002689 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002690 for (const auto& l : mLayersPendingRemoval) {
2691 recordBufferingStats(l->getName().string(),
2692 l->getOccupancyHistory(true));
2693 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002694 }
2695 mLayersPendingRemoval.clear();
2696 }
2697
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002698 // If this transaction is part of a window animation then the next frame
2699 // we composite should be considered an animation as well.
2700 mAnimCompositionPending = mAnimTransactionPending;
2701
Mathias Agopian4fec8732012-06-29 14:12:52 -07002702 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002703 // clear the "changed" flags in current state
2704 mCurrentState.colorMatrixChanged = false;
2705
Robert Carr1f0a16a2016-10-24 16:27:39 -07002706 mDrawingState.traverseInZOrder([](Layer* layer) {
2707 layer->commitChildList();
2708 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002709 mTransactionPending = false;
2710 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002711 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002712}
2713
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002714void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2715 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002716 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002717 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002718
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002719 Region aboveOpaqueLayers;
2720 Region aboveCoveredLayers;
2721 Region dirty;
2722
Mathias Agopian87baae12012-07-31 12:38:26 -07002723 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002724
Robert Carr2047fae2016-11-28 14:09:09 -08002725 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002726 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002727 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002728
Jesse Hall01e29052013-02-19 16:13:35 -08002729 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002730 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002731 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002732 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002733
Mathias Agopianab028732010-03-16 16:41:46 -07002734 /*
2735 * opaqueRegion: area of a surface that is fully opaque.
2736 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002737 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002738
2739 /*
2740 * visibleRegion: area of a surface that is visible on screen
2741 * and not fully transparent. This is essentially the layer's
2742 * footprint minus the opaque regions above it.
2743 * Areas covered by a translucent surface are considered visible.
2744 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002745 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002746
2747 /*
2748 * coveredRegion: area of a surface that is covered by all
2749 * visible regions above it (which includes the translucent areas).
2750 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002751 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002752
Jesse Halla8026d22012-09-25 13:25:04 -07002753 /*
2754 * transparentRegion: area of a surface that is hinted to be completely
2755 * transparent. This is only used to tell when the layer has no visible
2756 * non-transparent regions and can be removed from the layer list. It
2757 * does not affect the visibleRegion of this layer or any layers
2758 * beneath it. The hint may not be correct if apps don't respect the
2759 * SurfaceView restrictions (which, sadly, some don't).
2760 */
2761 Region transparentRegion;
2762
Mathias Agopianab028732010-03-16 16:41:46 -07002763
2764 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002765 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002766 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002767 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002768 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002769 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002770 if (!visibleRegion.isEmpty()) {
2771 // Remove the transparent area from the visible region
2772 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002773 if (tr.preserveRects()) {
2774 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002775 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002776 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002777 // transformation too complex, can't do the
2778 // transparent region optimization.
2779 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002780 }
Mathias Agopianab028732010-03-16 16:41:46 -07002781 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002782
Mathias Agopianab028732010-03-16 16:41:46 -07002783 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002784 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002785 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002786 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2787 // the opaque region is the layer's footprint
2788 opaqueRegion = visibleRegion;
2789 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002790 }
2791 }
2792
Robert Carre5f4f692018-01-12 13:12:28 -08002793 if (visibleRegion.isEmpty()) {
2794 layer->clearVisibilityRegions();
2795 return;
2796 }
2797
Mathias Agopianab028732010-03-16 16:41:46 -07002798 // Clip the covered region to the visible region
2799 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2800
2801 // Update aboveCoveredLayers for next (lower) layer
2802 aboveCoveredLayers.orSelf(visibleRegion);
2803
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002804 // subtract the opaque region covered by the layers above us
2805 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002806
2807 // compute this layer's dirty region
2808 if (layer->contentDirty) {
2809 // we need to invalidate the whole region
2810 dirty = visibleRegion;
2811 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002812 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002813 layer->contentDirty = false;
2814 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002815 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002816 * the exposed region consists of two components:
2817 * 1) what's VISIBLE now and was COVERED before
2818 * 2) what's EXPOSED now less what was EXPOSED before
2819 *
2820 * note that (1) is conservative, we start with the whole
2821 * visible region but only keep what used to be covered by
2822 * something -- which mean it may have been exposed.
2823 *
2824 * (2) handles areas that were not covered by anything but got
2825 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002826 */
Mathias Agopianab028732010-03-16 16:41:46 -07002827 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002828 const Region oldVisibleRegion = layer->visibleRegion;
2829 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002830 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2831 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002832 }
2833 dirty.subtractSelf(aboveOpaqueLayers);
2834
2835 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002836 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002837
Mathias Agopianab028732010-03-16 16:41:46 -07002838 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002839 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002840
Jesse Halla8026d22012-09-25 13:25:04 -07002841 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002842 layer->setVisibleRegion(visibleRegion);
2843 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002844 layer->setVisibleNonTransparentRegion(
2845 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002846 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002847
Mathias Agopian87baae12012-07-31 12:38:26 -07002848 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002849}
2850
Chia-I Wuab0c3192017-08-01 11:29:00 -07002851void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002852 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002853 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2854 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002855 }
2856 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002857}
2858
Dan Stoza6b9454d2014-11-07 16:00:59 -08002859bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002860{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002861 ALOGV("handlePageFlip");
2862
Brian Andersond6927fb2016-07-23 23:37:30 -07002863 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002864
Mathias Agopian4fec8732012-06-29 14:12:52 -07002865 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002866 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002867 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002868
2869 // Store the set of layers that need updates. This set must not change as
2870 // buffers are being latched, as this could result in a deadlock.
2871 // Example: Two producers share the same command stream and:
2872 // 1.) Layer 0 is latched
2873 // 2.) Layer 0 gets a new frame
2874 // 2.) Layer 1 gets a new frame
2875 // 3.) Layer 1 is latched.
2876 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2877 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002878 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002879 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002880 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07002881 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002882 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002883 } else {
2884 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002885 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002886 } else {
2887 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002888 }
Robert Carr2047fae2016-11-28 14:09:09 -08002889 });
2890
Dan Stoza9e56aa02015-11-02 13:00:03 -08002891 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002892 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002893 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002894 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002895 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002896 newDataLatched = true;
2897 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002898 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002899
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002900 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002901
2902 // If we will need to wake up at some time in the future to deal with a
2903 // queued frame that shouldn't be displayed during this vsync period, wake
2904 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002905 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002906 signalLayerUpdate();
2907 }
2908
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002909 // enter boot animation on first buffer latch
2910 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2911 ALOGI("Enter boot animation");
2912 mBootStage = BootStage::BOOTANIMATION;
2913 }
2914
Dan Stoza6b9454d2014-11-07 16:00:59 -08002915 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002916 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002917}
2918
Mathias Agopianad456f92011-01-13 17:53:01 -08002919void SurfaceFlinger::invalidateHwcGeometry()
2920{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002921 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002922}
2923
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002924void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2925 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002926 // We only need to actually compose the display if:
2927 // 1) It is being handled by hardware composer, which may need this to
2928 // keep its virtual display state machine in sync, or
2929 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002930 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002931 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002932 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002933 return;
2934 }
2935
Dan Stoza9e56aa02015-11-02 13:00:03 -08002936 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002937 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002938
2939 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002940 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002941}
2942
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002943bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002944 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002945
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002946 const Region bounds(display->bounds());
2947 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002948 const auto displayId = display->getId();
2949 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002950 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002951
Chia-I Wu8e50e692018-05-04 10:12:37 -07002952 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002953 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002954
Dan Stoza9e56aa02015-11-02 13:00:03 -08002955 if (hasClientComposition) {
2956 ALOGV("hasClientComposition");
2957
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002958 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002959 if (display->hasWideColorGamut()) {
2960 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002961 }
2962 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002963 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002964 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002965
Dominik Laskowski7e045462018-05-30 13:02:02 -07002966 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002967 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2968 HWC2::Capability::SkipClientColorTransform);
2969
Chia-I Wud49d6692018-06-27 07:17:41 +08002970 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002971 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2972 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08002973 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002974 }
2975
Chia-I Wud49d6692018-06-27 07:17:41 +08002976 // The current enhanced saturation matrix is designed to enhance Display P3,
2977 // thus we only apply this matrix when the render intent is not colorimetric
2978 // and the output color space is Display P3.
2979 needsEnhancedColorMatrix =
2980 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2981 outputDataspace == Dataspace::DISPLAY_P3);
2982 if (needsEnhancedColorMatrix) {
2983 colorMatrix *= mEnhancedSaturationMatrix;
2984 }
2985
2986 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002987
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002988 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002989 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002990 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002991 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002992
2993 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002994 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
2995 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
2996 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07002997 }
2998 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002999 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003000
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003001 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003002 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003003 // when using overlays, we assume a fully transparent framebuffer
3004 // NOTE: we could reduce how much we need to clear, for instance
3005 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003006 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003007 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003008 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003009 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003010 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003011 // we're left with the letterbox region
3012 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003013 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003014
3015 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003016 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003017
Mathias Agopianb9494d52012-04-18 02:28:45 -07003018 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003019 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003020 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003021 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003022 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003023 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003024
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003025 if (!display->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07003026 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07003027 // scissor on the main display. It should never be needed
3028 // anyways (though in theory it could since the API allows it).
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003029 const Rect& bounds = display->getBounds();
3030 const Rect& scissor = display->getScissor();
Mathias Agopianf45c5102012-10-24 16:29:17 -07003031 if (scissor != bounds) {
3032 // scissor doesn't match the screen's dimensions, so we
3033 // need to clear everything outside of it and enable
3034 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003035
Mathias Agopianf45c5102012-10-24 16:29:17 -07003036 // enable scissor for this frame
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003037 const uint32_t height = display->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08003038 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07003039 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003040 }
3041 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003042 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003043
Mathias Agopian85d751c2012-08-29 16:59:24 -07003044 /*
3045 * and then, render the layers targeted at the framebuffer
3046 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003047
Dan Stoza9e56aa02015-11-02 13:00:03 -08003048 ALOGV("Rendering client layers");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003049 const Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003050 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003051 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003052 const Region clip(bounds.intersect(
3053 displayTransform.transform(layer->visibleRegion)));
3054 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07003055 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003056 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003057 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003058 case HWC2::Composition::Cursor:
3059 case HWC2::Composition::Device:
3060 case HWC2::Composition::Sideband:
3061 case HWC2::Composition::SolidColor: {
3062 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07003063 if (layer->getClearClientTarget(displayId) && !firstLayer &&
Rajavenu Kyatham2eae6d32018-04-10 12:34:05 +05303064 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3065 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003066 // never clear the very first layer since we're
3067 // guaranteed the FB is already cleared
3068 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003069 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003070 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003071 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003072 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003073 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003074 break;
3075 }
3076 default:
3077 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003078 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003079 } else {
3080 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003081 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003082 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003083 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003084
Chia-I Wud49d6692018-06-27 07:17:41 +08003085 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003086 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003087 }
3088
Mathias Agopianf45c5102012-10-24 16:29:17 -07003089 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003090 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003091 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003092}
3093
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003094void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
3095 const Region& region) const {
3096 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003097 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003098 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003099}
3100
Dan Stoza7d89d062015-04-30 13:29:25 -07003101status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003102 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003103 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003104 const sp<Layer>& lbc,
3105 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003106{
Dan Stoza7d89d062015-04-30 13:29:25 -07003107 // add this layer to the current state list
3108 {
3109 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003110 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003111 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3112 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003113 return NO_MEMORY;
3114 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003115 if (parent == nullptr) {
3116 mCurrentState.layersSortedByZ.add(lbc);
3117 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003118 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003119 ALOGE("addClientLayer called with a removed parent");
3120 return NAME_NOT_FOUND;
3121 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003122 parent->addChild(lbc);
3123 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003124
Yiwei Zhang243b3782018-05-15 17:40:04 -07003125 if (gbc != nullptr) {
3126 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3127 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3128 mMaxGraphicBufferProducerListSize,
3129 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3130 mGraphicBufferProducerList.size(),
3131 mMaxGraphicBufferProducerListSize, mNumLayers);
3132 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003133 mLayersAdded = true;
3134 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003135 }
3136
Mathias Agopian96f08192010-06-02 23:28:45 -07003137 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003138 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003139
Dan Stoza7d89d062015-04-30 13:29:25 -07003140 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003141}
3142
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003143status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003144 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003145 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3146}
Robert Carr7f9b8992017-03-10 11:08:39 -08003147
chaviwca27f252018-02-06 16:46:39 -08003148status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3149 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003150 if (layer->isPendingRemoval()) {
3151 return NO_ERROR;
3152 }
3153
Robert Carr1f0a16a2016-10-24 16:27:39 -07003154 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003155 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003156 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003157 if (topLevelOnly) {
3158 return NO_ERROR;
3159 }
3160
Chia-I Wu98f1c102017-05-30 14:54:08 -07003161 sp<Layer> ancestor = p;
3162 while (ancestor->getParent() != nullptr) {
3163 ancestor = ancestor->getParent();
3164 }
3165 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3166 ALOGE("removeLayer called with a layer whose parent has been removed");
3167 return NAME_NOT_FOUND;
3168 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003169
3170 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003171 } else {
3172 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003173 }
3174
Robert Carr136e2f62017-02-08 17:54:29 -08003175 // As a matter of normal operation, the LayerCleaner will produce a second
3176 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3177 // so we will succeed in promoting it, but it's already been removed
3178 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3179 // otherwise something has gone wrong and we are leaking the layer.
3180 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003181 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3182 layer->getName().string(),
3183 (p != nullptr) ? p->getName().string() : "no-parent");
3184 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003185 } else if (index < 0) {
3186 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003187 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003188
Chia-I Wuc6657022017-08-15 11:18:17 -07003189 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003190 mLayersPendingRemoval.add(layer);
3191 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003192 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003193 setTransactionFlags(eTransactionNeeded);
3194 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003195}
3196
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003197uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003198 return android_atomic_release_load(&mTransactionFlags);
3199}
3200
Mathias Agopian3f844832013-08-07 21:24:32 -07003201uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003202 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3203}
3204
Mathias Agopian3f844832013-08-07 21:24:32 -07003205uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003206 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3207}
3208
3209uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3210 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003211 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003212 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003213 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003214 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003215 }
3216 return old;
3217}
3218
chaviwca27f252018-02-06 16:46:39 -08003219bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3220 for (const ComposerState& state : states) {
3221 // Here we need to check that the interface we're given is indeed
3222 // one of our own. A malicious client could give us a nullptr
3223 // IInterface, or one of its own or even one of our own but a
3224 // different type. All these situations would cause us to crash.
3225 if (state.client == nullptr) {
3226 return true;
3227 }
3228
3229 sp<IBinder> binder = IInterface::asBinder(state.client);
3230 if (binder == nullptr) {
3231 return true;
3232 }
3233
3234 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3235 return true;
3236 }
3237 }
3238 return false;
3239}
3240
Mathias Agopian8b33f032012-07-24 20:43:54 -07003241void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003242 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003243 const Vector<DisplayState>& displays,
3244 uint32_t flags)
3245{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003246 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003247 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003248 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003249
chaviwca27f252018-02-06 16:46:39 -08003250 if (containsAnyInvalidClientState(states)) {
3251 return;
3252 }
3253
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003254 if (flags & eAnimation) {
3255 // For window updates that are part of an animation we must wait for
3256 // previous animation "frames" to be handled.
3257 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003258 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003259 if (CC_UNLIKELY(err != NO_ERROR)) {
3260 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003261 // caller after a few seconds.
3262 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3263 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003264 mAnimTransactionPending = false;
3265 break;
3266 }
3267 }
3268 }
3269
chaviwca27f252018-02-06 16:46:39 -08003270 for (const DisplayState& display : displays) {
3271 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003272 }
3273
chaviwca27f252018-02-06 16:46:39 -08003274 for (const ComposerState& state : states) {
3275 transactionFlags |= setClientStateLocked(state);
3276 }
3277
3278 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3279 // as destroyed should only occur after setting all other states. This is to allow for a
3280 // child re-parent to happen before marking its original parent as destroyed (which would
3281 // then mark the child as destroyed).
3282 for (const ComposerState& state : states) {
3283 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003284 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003285
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003286 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3287 // anyway. This can be used as a flush mechanism for previous async transactions.
3288 // Empty animation transaction can be used to simulate back-pressure, so also force a
3289 // transaction for empty animation transactions.
3290 if (transactionFlags == 0 &&
3291 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003292 transactionFlags = eTransactionNeeded;
3293 }
3294
Mathias Agopian386aa982011-11-07 21:58:03 -08003295 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003296 if (mInterceptor->isEnabled()) {
3297 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003298 }
Irvel468051e2016-06-13 16:44:44 -07003299
Mathias Agopian386aa982011-11-07 21:58:03 -08003300 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003301 const auto start = (flags & eEarlyWakeup)
3302 ? VSyncModulator::TransactionStart::EARLY
3303 : VSyncModulator::TransactionStart::NORMAL;
3304 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003305
3306 // if this is a synchronous transaction, wait for it to take effect
3307 // before returning.
3308 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003309 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003310 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003311 if (flags & eAnimation) {
3312 mAnimTransactionPending = true;
3313 }
3314 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003315 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3316 if (CC_UNLIKELY(err != NO_ERROR)) {
3317 // just in case something goes wrong in SF, return to the
3318 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003319 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3320 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003321 break;
3322 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003323 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003324 }
3325}
3326
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003327uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3328 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3329 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003330
Mathias Agopiane57f2922012-08-09 16:29:12 -07003331 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003332 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3333
3334 const uint32_t what = s.what;
3335 if (what & DisplayState::eSurfaceChanged) {
3336 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3337 state.surface = s.surface;
3338 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003339 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003340 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003341 if (what & DisplayState::eLayerStackChanged) {
3342 if (state.layerStack != s.layerStack) {
3343 state.layerStack = s.layerStack;
3344 flags |= eDisplayTransactionNeeded;
3345 }
3346 }
3347 if (what & DisplayState::eDisplayProjectionChanged) {
3348 if (state.orientation != s.orientation) {
3349 state.orientation = s.orientation;
3350 flags |= eDisplayTransactionNeeded;
3351 }
3352 if (state.frame != s.frame) {
3353 state.frame = s.frame;
3354 flags |= eDisplayTransactionNeeded;
3355 }
3356 if (state.viewport != s.viewport) {
3357 state.viewport = s.viewport;
3358 flags |= eDisplayTransactionNeeded;
3359 }
3360 }
3361 if (what & DisplayState::eDisplaySizeChanged) {
3362 if (state.width != s.width) {
3363 state.width = s.width;
3364 flags |= eDisplayTransactionNeeded;
3365 }
3366 if (state.height != s.height) {
3367 state.height = s.height;
3368 flags |= eDisplayTransactionNeeded;
3369 }
3370 }
3371
Mathias Agopiane57f2922012-08-09 16:29:12 -07003372 return flags;
3373}
3374
Robert Carrd4ae7f32018-06-07 16:10:57 -07003375bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3376 IPCThreadState* ipc = IPCThreadState::self();
3377 const int pid = ipc->getCallingPid();
3378 const int uid = ipc->getCallingUid();
3379
3380 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3381 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3382 return false;
3383 }
3384 return true;
3385}
3386
chaviwca27f252018-02-06 16:46:39 -08003387uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3388 const layer_state_t& s = composerState.state;
3389 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3390
Mathias Agopian13127d82013-03-05 17:47:11 -08003391 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003392 if (layer == nullptr) {
3393 return 0;
3394 }
3395
3396 if (layer->isPendingRemoval()) {
3397 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3398 return 0;
3399 }
3400
3401 uint32_t flags = 0;
3402
3403 const uint32_t what = s.what;
3404 bool geometryAppliesWithResize =
3405 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003406
3407 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3408 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003409 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003410 layer->pushPendingState();
3411 }
3412
chaviw8b3871a2017-11-01 17:41:01 -07003413 if (what & layer_state_t::ePositionChanged) {
3414 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3415 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003416 }
chaviw8b3871a2017-11-01 17:41:01 -07003417 }
3418 if (what & layer_state_t::eLayerChanged) {
3419 // NOTE: index needs to be calculated before we update the state
3420 const auto& p = layer->getParent();
3421 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003422 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003423 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003424 mCurrentState.layersSortedByZ.removeAt(idx);
3425 mCurrentState.layersSortedByZ.add(layer);
3426 // we need traversal (state changed)
3427 // AND transaction (list changed)
3428 flags |= eTransactionNeeded|eTraversalNeeded;
3429 }
chaviw8b3871a2017-11-01 17:41:01 -07003430 } else {
3431 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003432 flags |= eTransactionNeeded|eTraversalNeeded;
3433 }
3434 }
chaviw8b3871a2017-11-01 17:41:01 -07003435 }
3436 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003437 // NOTE: index needs to be calculated before we update the state
3438 const auto& p = layer->getParent();
3439 if (p == nullptr) {
3440 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3441 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3442 mCurrentState.layersSortedByZ.removeAt(idx);
3443 mCurrentState.layersSortedByZ.add(layer);
3444 // we need traversal (state changed)
3445 // AND transaction (list changed)
3446 flags |= eTransactionNeeded|eTraversalNeeded;
3447 }
3448 } else {
3449 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3450 flags |= eTransactionNeeded|eTraversalNeeded;
3451 }
chaviw8b3871a2017-11-01 17:41:01 -07003452 }
3453 }
3454 if (what & layer_state_t::eSizeChanged) {
3455 if (layer->setSize(s.w, s.h)) {
3456 flags |= eTraversalNeeded;
3457 }
3458 }
3459 if (what & layer_state_t::eAlphaChanged) {
3460 if (layer->setAlpha(s.alpha))
3461 flags |= eTraversalNeeded;
3462 }
3463 if (what & layer_state_t::eColorChanged) {
3464 if (layer->setColor(s.color))
3465 flags |= eTraversalNeeded;
3466 }
3467 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003468 // TODO: b/109894387
3469 //
3470 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3471 // rotation. To see the problem observe that if we have a square parent, and a child
3472 // of the same size, then we rotate the child 45 degrees around it's center, the child
3473 // must now be cropped to a non rectangular 8 sided region.
3474 //
3475 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3476 // private API, and the WindowManager only uses rotation in one case, which is on a top
3477 // level layer in which cropping is not an issue.
3478 //
3479 // However given that abuse of rotation matrices could lead to surfaces extending outside
3480 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3481 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3482 // transformations.
3483 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003484 flags |= eTraversalNeeded;
3485 }
3486 if (what & layer_state_t::eTransparentRegionChanged) {
3487 if (layer->setTransparentRegionHint(s.transparentRegion))
3488 flags |= eTraversalNeeded;
3489 }
3490 if (what & layer_state_t::eFlagsChanged) {
3491 if (layer->setFlags(s.flags, s.mask))
3492 flags |= eTraversalNeeded;
3493 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003494 if (what & layer_state_t::eCropChanged_legacy) {
3495 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003496 flags |= eTraversalNeeded;
3497 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003498 if (what & layer_state_t::eFinalCropChanged_legacy) {
3499 if (layer->setFinalCrop_legacy(s.finalCrop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003500 flags |= eTraversalNeeded;
3501 }
3502 if (what & layer_state_t::eLayerStackChanged) {
3503 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3504 // We only allow setting layer stacks for top level layers,
3505 // everything else inherits layer stack from its parent.
3506 if (layer->hasParent()) {
3507 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3508 layer->getName().string());
3509 } else if (idx < 0) {
3510 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3511 "that also does not appear in the top level layer list. Something"
3512 " has gone wrong.", layer->getName().string());
3513 } else if (layer->setLayerStack(s.layerStack)) {
3514 mCurrentState.layersSortedByZ.removeAt(idx);
3515 mCurrentState.layersSortedByZ.add(layer);
3516 // we need traversal (state changed)
3517 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003518 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003519 }
3520 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003521 if (what & layer_state_t::eDeferTransaction_legacy) {
3522 if (s.barrierHandle_legacy != nullptr) {
3523 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3524 } else if (s.barrierGbp_legacy != nullptr) {
3525 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003526 if (authenticateSurfaceTextureLocked(gbp)) {
3527 const auto& otherLayer =
3528 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003529 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003530 } else {
3531 ALOGE("Attempt to defer transaction to to an"
3532 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003533 }
3534 }
chaviw8b3871a2017-11-01 17:41:01 -07003535 // We don't trigger a traversal here because if no other state is
3536 // changed, we don't want this to cause any more work
3537 }
3538 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003539 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003540 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003541 if (!hadParent) {
3542 mCurrentState.layersSortedByZ.remove(layer);
3543 }
chaviw8b3871a2017-11-01 17:41:01 -07003544 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003545 }
chaviw8b3871a2017-11-01 17:41:01 -07003546 }
3547 if (what & layer_state_t::eReparentChildren) {
3548 if (layer->reparentChildren(s.reparentHandle)) {
3549 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003550 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003551 }
chaviw8b3871a2017-11-01 17:41:01 -07003552 if (what & layer_state_t::eDetachChildren) {
3553 layer->detachChildren();
3554 }
3555 if (what & layer_state_t::eOverrideScalingModeChanged) {
3556 layer->setOverrideScalingMode(s.overrideScalingMode);
3557 // We don't trigger a traversal here because if no other state is
3558 // changed, we don't want this to cause any more work
3559 }
Marissa Wall61c58622018-07-18 10:12:20 -07003560 if (what & layer_state_t::eTransformChanged) {
3561 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3562 }
3563 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3564 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3565 flags |= eTraversalNeeded;
3566 }
3567 if (what & layer_state_t::eCropChanged) {
3568 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3569 }
3570 if (what & layer_state_t::eBufferChanged) {
3571 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3572 }
3573 if (what & layer_state_t::eAcquireFenceChanged) {
3574 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3575 }
3576 if (what & layer_state_t::eDataspaceChanged) {
3577 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3578 }
3579 if (what & layer_state_t::eHdrMetadataChanged) {
3580 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3581 }
3582 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3583 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3584 }
3585 if (what & layer_state_t::eApiChanged) {
3586 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3587 }
3588 if (what & layer_state_t::eSidebandStreamChanged) {
3589 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3590 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003591 return flags;
3592}
3593
chaviwca27f252018-02-06 16:46:39 -08003594void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3595 const layer_state_t& state = composerState.state;
3596 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3597
3598 sp<Layer> layer(client->getLayerUser(state.surface));
3599 if (layer == nullptr) {
3600 return;
3601 }
3602
3603 if (layer->isPendingRemoval()) {
3604 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3605 return;
3606 }
3607
3608 if (state.what & layer_state_t::eDestroySurface) {
3609 removeLayerLocked(mStateLock, layer);
3610 }
3611}
3612
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003613status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003614 const String8& name,
3615 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003616 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003617 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003618 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003619{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003620 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003621 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003622 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003623 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003624 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003625
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003626 status_t result = NO_ERROR;
3627
3628 sp<Layer> layer;
3629
Cody Northropbc755282017-03-31 12:00:08 -06003630 String8 uniqueName = getUniqueLayerName(name);
3631
Mathias Agopian3165cc22012-08-08 19:42:09 -07003632 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003633 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003634 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3635 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003636
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003637 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003638 case ISurfaceComposerClient::eFXSurfaceBufferState:
3639 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3640 break;
chaviw13fdc492017-06-27 12:40:18 -07003641 case ISurfaceComposerClient::eFXSurfaceColor:
3642 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003643 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003644 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003645 break;
3646 default:
3647 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003648 break;
3649 }
3650
Dan Stoza7d89d062015-04-30 13:29:25 -07003651 if (result != NO_ERROR) {
3652 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003653 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003654
Chia-I Wuab0c3192017-08-01 11:29:00 -07003655 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3656 // TODO b/64227542
3657 if (windowType == 441731) {
3658 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3659 layer->setPrimaryDisplayOnly();
3660 }
3661
Albert Chaulk479c60c2017-01-27 14:21:34 -05003662 layer->setInfo(windowType, ownerUid);
3663
Robert Carr1f0a16a2016-10-24 16:27:39 -07003664 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003665 if (result != NO_ERROR) {
3666 return result;
3667 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003668 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003669
3670 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003671 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003672}
3673
Cody Northropbc755282017-03-31 12:00:08 -06003674String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3675{
3676 bool matchFound = true;
3677 uint32_t dupeCounter = 0;
3678
3679 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3680 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3681
Dan Stoza436ccf32018-06-21 12:10:12 -07003682 // Grab the state lock since we're accessing mCurrentState
3683 Mutex::Autolock lock(mStateLock);
3684
Cody Northropbc755282017-03-31 12:00:08 -06003685 // Loop over layers until we're sure there is no matching name
3686 while (matchFound) {
3687 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003688 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003689 if (layer->getName() == uniqueName) {
3690 matchFound = true;
3691 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3692 }
3693 });
3694 }
3695
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003696 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3697 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003698
3699 return uniqueName;
3700}
3701
Marissa Wallfd668622018-05-10 10:21:13 -07003702status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3703 uint32_t w, uint32_t h, uint32_t flags,
3704 PixelFormat& format, sp<IBinder>* handle,
3705 sp<IGraphicBufferProducer>* gbp,
3706 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003707 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003708 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003709 case PIXEL_FORMAT_TRANSPARENT:
3710 case PIXEL_FORMAT_TRANSLUCENT:
3711 format = PIXEL_FORMAT_RGBA_8888;
3712 break;
3713 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003714 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003715 break;
3716 }
3717
Marissa Wallfd668622018-05-10 10:21:13 -07003718 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3719 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003720 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003721 *handle = layer->getHandle();
3722 *gbp = layer->getProducer();
3723 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003724 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003725
Marissa Wallfd668622018-05-10 10:21:13 -07003726 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003727 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003728}
3729
Marissa Wall61c58622018-07-18 10:12:20 -07003730status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3731 uint32_t w, uint32_t h, uint32_t flags,
3732 sp<IBinder>* handle, sp<Layer>* outLayer) {
3733 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3734 *handle = layer->getHandle();
3735 *outLayer = layer;
3736
3737 return NO_ERROR;
3738}
3739
chaviw13fdc492017-06-27 12:40:18 -07003740status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003741 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003742 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003743{
chaviw13fdc492017-06-27 12:40:18 -07003744 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003745 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003746 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003747}
3748
Mathias Agopianac9fa422013-02-11 16:40:36 -08003749status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003750{
Robert Carr9524cb32017-02-13 11:32:32 -08003751 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003752 status_t err = NO_ERROR;
3753 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003754 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003755 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003756 err = removeLayer(l);
3757 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3758 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003759 }
3760 return err;
3761}
3762
Mathias Agopian13127d82013-03-05 17:47:11 -08003763status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003764{
Mathias Agopian67106042013-03-14 19:18:13 -07003765 // called by ~LayerCleaner() when all references to the IBinder (handle)
3766 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003767 sp<Layer> l = layer.promote();
3768 if (l == nullptr) {
3769 // The layer has already been removed, carry on
3770 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003771 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003772 // If we have a parent, then we can continue to live as long as it does.
3773 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003774}
3775
Mathias Agopianb60314a2012-04-10 22:09:54 -07003776// ---------------------------------------------------------------------------
3777
Andy McFadden13a082e2012-08-24 10:16:42 -07003778void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003779 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3780 if (!displayToken) return;
3781
Jesse Hall01e29052013-02-19 16:13:35 -08003782 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003783 Vector<ComposerState> state;
3784 Vector<DisplayState> displays;
3785 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003786 d.what = DisplayState::eDisplayProjectionChanged |
3787 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003788 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003789 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003790 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003791 d.frame.makeInvalid();
3792 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003793 d.width = 0;
3794 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003795 displays.add(d);
3796 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003797
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003798 const auto display = getDisplayDevice(displayToken);
3799 if (!display) return;
3800
3801 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3802
3803 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003804 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003805 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003806
Brian Andersond0010582017-03-07 13:20:31 -08003807 // Use phase of 0 since phase is not known.
3808 // Use latency of 0, which will snap to the ideal latency.
3809 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003810}
3811
3812void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003813 // Async since we may be called from the main thread.
3814 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003815}
3816
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003817void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3818 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003819 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003820 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003821
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003822 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003823 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003824 return;
3825 }
3826
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003827 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003828 ALOGW("Trying to set power mode for virtual display");
3829 return;
3830 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003831
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003832 display->setPowerMode(mode);
3833
Lloyd Pique4dccc412018-01-22 17:21:36 -08003834 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003835 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003836 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003837 if (idx < 0) {
3838 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3839 return;
3840 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003841 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003842 }
3843
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003844 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003845 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003846 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003847 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003848 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003849 // FIXME: eventthread only knows about the main display right now
3850 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003851 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003852 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003853
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003854 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003855 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003856 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003857
3858 struct sched_param param = {0};
3859 param.sched_priority = 1;
3860 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3861 ALOGW("Couldn't set SCHED_FIFO on display on");
3862 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003863 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003864 // Turn off the display
3865 struct sched_param param = {0};
3866 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3867 ALOGW("Couldn't set SCHED_OTHER on display off");
3868 }
3869
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003870 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003871 disableHardwareVsync(true); // also cancels any in-progress resync
3872
Mathias Agopiancde87a32012-09-13 14:09:01 -07003873 // FIXME: eventthread only knows about the main display right now
3874 mEventThread->onScreenReleased();
3875 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003876
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003877 getHwComposer().setPowerMode(type, mode);
3878 mVisibleRegionsDirty = true;
3879 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003880 } else if (mode == HWC_POWER_MODE_DOZE ||
3881 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003882 // Update display while dozing
3883 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003884 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003885 // FIXME: eventthread only knows about the main display right now
3886 mEventThread->onScreenAcquired();
3887 resyncToHardwareVsync(true);
3888 }
3889 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3890 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003891 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003892 disableHardwareVsync(true); // also cancels any in-progress resync
3893 // FIXME: eventthread only knows about the main display right now
3894 mEventThread->onScreenReleased();
3895 }
3896 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003897 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003898 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003899 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003900 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003901
3902 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003903}
3904
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003905void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003906 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003907 const auto display = getDisplayDevice(displayToken);
3908 if (!display) {
3909 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3910 displayToken.get());
3911 } else if (display->isVirtual()) {
3912 ALOGW("Attempt to set power mode %d for virtual display", mode);
3913 } else {
3914 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003915 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003916 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003917}
3918
3919// ---------------------------------------------------------------------------
3920
Lloyd Pique755e3192018-01-31 16:46:15 -08003921status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3922 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003923 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003924
Mathias Agopianbd115332013-04-18 16:41:04 -07003925 IPCThreadState* ipc = IPCThreadState::self();
3926 const int pid = ipc->getCallingPid();
3927 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003928
Mathias Agopianbd115332013-04-18 16:41:04 -07003929 if ((uid != AID_SHELL) &&
3930 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003931 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003932 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003933 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003934 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003935 // (this would indicate SF is stuck, but we want to be able to
3936 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003937 status_t err = mStateLock.timedLock(s2ns(1));
3938 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003939 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003940 result.appendFormat(
3941 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3942 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003943 }
3944
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003945 bool dumpAll = true;
3946 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003947 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003948
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003949 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003950 if ((index < numArgs) &&
3951 (args[index] == String16("--list"))) {
3952 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003953 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003954 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003955 }
3956
3957 if ((index < numArgs) &&
3958 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003959 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003960 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003961 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003962 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003963
3964 if ((index < numArgs) &&
3965 (args[index] == String16("--latency-clear"))) {
3966 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003967 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003968 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003969 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003970
3971 if ((index < numArgs) &&
3972 (args[index] == String16("--dispsync"))) {
3973 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07003974 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07003975 dumpAll = false;
3976 }
Dan Stozab90cf072015-03-05 11:05:59 -08003977
3978 if ((index < numArgs) &&
3979 (args[index] == String16("--static-screen"))) {
3980 index++;
3981 dumpStaticScreenStats(result);
3982 dumpAll = false;
3983 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003984
3985 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003986 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003987 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003988 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003989 dumpAll = false;
3990 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003991
3992 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3993 index++;
3994 dumpWideColorInfo(result);
3995 dumpAll = false;
3996 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003997
3998 if ((index < numArgs) &&
3999 (args[index] == String16("--enable-layer-stats"))) {
4000 index++;
4001 mLayerStats.enable();
4002 dumpAll = false;
4003 }
4004
4005 if ((index < numArgs) &&
4006 (args[index] == String16("--disable-layer-stats"))) {
4007 index++;
4008 mLayerStats.disable();
4009 dumpAll = false;
4010 }
4011
4012 if ((index < numArgs) &&
4013 (args[index] == String16("--clear-layer-stats"))) {
4014 index++;
4015 mLayerStats.clear();
4016 dumpAll = false;
4017 }
4018
4019 if ((index < numArgs) &&
4020 (args[index] == String16("--dump-layer-stats"))) {
4021 index++;
4022 mLayerStats.dump(result);
4023 dumpAll = false;
4024 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004025
4026 if ((index < numArgs) &&
4027 (args[index] == String16("--display-identification"))) {
4028 index++;
4029 dumpDisplayIdentificationData(result);
4030 dumpAll = false;
4031 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004032
4033 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4034 index++;
4035 mTimeStats.parseArgs(asProto, args, index, result);
4036 dumpAll = false;
4037 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004038 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004039
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004040 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004041 if (asProto) {
4042 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4043 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4044 } else {
4045 dumpAllLocked(args, index, result);
4046 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004047 }
4048
Mathias Agopian9795c422009-08-26 16:36:26 -07004049 if (locked) {
4050 mStateLock.unlock();
4051 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004052 }
4053 write(fd, result.string(), result.size());
4054 return NO_ERROR;
4055}
4056
Dan Stozac7014012014-02-14 15:03:43 -08004057void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4058 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004059{
Robert Carr2047fae2016-11-28 14:09:09 -08004060 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004061 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004062 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004063}
4064
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004065void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004066 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004067{
4068 String8 name;
4069 if (index < args.size()) {
4070 name = String8(args[index]);
4071 index++;
4072 }
4073
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004074 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4075 getHwComposer().isConnected(displayId)) {
4076 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4077 const nsecs_t period = activeConfig->getVsyncPeriod();
4078 result.appendFormat("%" PRId64 "\n", period);
4079 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004080
4081 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004082 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004083 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004084 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004085 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004086 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004087 }
Robert Carr2047fae2016-11-28 14:09:09 -08004088 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004089 }
4090}
4091
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004092void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004093 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004094{
4095 String8 name;
4096 if (index < args.size()) {
4097 name = String8(args[index]);
4098 index++;
4099 }
4100
Robert Carr2047fae2016-11-28 14:09:09 -08004101 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004102 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004103 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004104 }
Robert Carr2047fae2016-11-28 14:09:09 -08004105 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004106
Svetoslavd85084b2014-03-20 10:28:31 -07004107 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004108}
4109
Jamie Gennis6547ff42013-07-16 20:12:42 -07004110// This should only be called from the main thread. Otherwise it would need
4111// the lock and should use mCurrentState rather than mDrawingState.
4112void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004113 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004114 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004115 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004116
4117 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4118}
4119
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004120void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004121{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004122 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004123
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004124 if (isLayerTripleBufferingDisabled())
4125 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004126
4127 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004128 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004129 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004130 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004131 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4132 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004133 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004134}
4135
Dan Stozab90cf072015-03-05 11:05:59 -08004136void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4137{
4138 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004139 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4140 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004141 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004142 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004143 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4144 b + 1, bucketTimeSec, percent);
4145 }
David Sodman4a36e932017-11-07 14:29:47 -08004146 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004147 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004148 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004149 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004150 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004151}
4152
Dan Stozae77c7662016-05-13 11:37:28 -07004153void SurfaceFlinger::recordBufferingStats(const char* layerName,
4154 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004155 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4156 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004157 for (const auto& segment : history) {
4158 if (!segment.usedThirdBuffer) {
4159 stats.twoBufferTime += segment.totalTime;
4160 }
4161 if (segment.occupancyAverage < 1.0f) {
4162 stats.doubleBufferedTime += segment.totalTime;
4163 } else if (segment.occupancyAverage < 2.0f) {
4164 stats.tripleBufferedTime += segment.totalTime;
4165 }
4166 ++stats.numSegments;
4167 stats.totalTime += segment.totalTime;
4168 }
4169}
4170
Brian Andersond6927fb2016-07-23 23:37:30 -07004171void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4172 result.appendFormat("Layer frame timestamps:\n");
4173
4174 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4175 const size_t count = currentLayers.size();
4176 for (size_t i=0 ; i<count ; i++) {
4177 currentLayers[i]->dumpFrameEvents(result);
4178 }
4179}
4180
Dan Stozae77c7662016-05-13 11:37:28 -07004181void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4182 result.append("Buffering stats:\n");
4183 result.append(" [Layer name] <Active time> <Two buffer> "
4184 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004185 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004186 typedef std::tuple<std::string, float, float, float> BufferTuple;
4187 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004188 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004189 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004190 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004191 if (stats.numSegments == 0) {
4192 continue;
4193 }
4194 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4195 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4196 stats.totalTime;
4197 float doubleBufferRatio = static_cast<float>(
4198 stats.doubleBufferedTime) / stats.totalTime;
4199 float tripleBufferRatio = static_cast<float>(
4200 stats.tripleBufferedTime) / stats.totalTime;
4201 sorted.insert({activeTime, {name, twoBufferRatio,
4202 doubleBufferRatio, tripleBufferRatio}});
4203 }
4204 for (const auto& sortedPair : sorted) {
4205 float activeTime = sortedPair.first;
4206 const BufferTuple& values = sortedPair.second;
4207 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4208 std::get<0>(values).c_str(), activeTime,
4209 std::get<1>(values), std::get<2>(values),
4210 std::get<3>(values));
4211 }
4212 result.append("\n");
4213}
4214
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004215void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004216 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004217 const int32_t displayId = display->getId();
4218 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4219 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004220 continue;
4221 }
4222
Dominik Laskowski7e045462018-05-30 13:02:02 -07004223 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004224 uint8_t port;
4225 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004226 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004227 result.append("no identification data\n");
4228 continue;
4229 }
4230
4231 if (!isEdid(data)) {
4232 result.append("unknown identification data: ");
4233 for (uint8_t byte : data) {
4234 result.appendFormat("%x ", byte);
4235 }
4236 result.append("\n");
4237 continue;
4238 }
4239
4240 const auto edid = parseEdid(data);
4241 if (!edid) {
4242 result.append("invalid EDID: ");
4243 for (uint8_t byte : data) {
4244 result.appendFormat("%x ", byte);
4245 }
4246 result.append("\n");
4247 continue;
4248 }
4249
4250 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4251 result.append(edid->displayName.data(), edid->displayName.length());
4252 result.append("\"\n");
4253 }
4254 result.append("\n");
4255}
4256
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004257void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4258 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004259 result.appendFormat("DisplayColorSetting: %s\n",
4260 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004261
4262 // TODO: print out if wide-color mode is active or not
4263
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004264 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004265 const int32_t displayId = display->getId();
4266 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004267 continue;
4268 }
4269
Dominik Laskowski7e045462018-05-30 13:02:02 -07004270 result.appendFormat("Display %d color modes:\n", displayId);
4271 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004272 for (auto&& mode : modes) {
4273 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4274 }
4275
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004276 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004277 result.appendFormat(" Current color mode: %s (%d)\n",
4278 decodeColorMode(currentMode).c_str(), currentMode);
4279 }
4280 result.append("\n");
4281}
4282
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004283LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004284 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004285 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4286 const State& state = useDrawing ? mDrawingState : mCurrentState;
4287 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004288 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004289 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004290 });
4291
4292 return layersProto;
4293}
4294
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004295LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004296 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004297
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004298 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004299 resolution->set_w(display.getWidth());
4300 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004301
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004302 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4303 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4304 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004305
Dominik Laskowski7e045462018-05-30 13:02:02 -07004306 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004307 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004308 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004309 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004310 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004311 }
4312 });
4313
4314 return layersProto;
4315}
4316
Mathias Agopian74d211a2013-04-22 16:55:35 +02004317void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4318 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004319{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004320 bool colorize = false;
4321 if (index < args.size()
4322 && (args[index] == String16("--color"))) {
4323 colorize = true;
4324 index++;
4325 }
4326
4327 Colorizer colorizer(colorize);
4328
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004329 // figure out if we're stuck somewhere
4330 const nsecs_t now = systemTime();
4331 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4332 const nsecs_t inTransaction(mDebugInTransaction);
4333 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4334 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4335
4336 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004337 * Dump library configuration.
4338 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004339
4340 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004341 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004342 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004343 appendSfConfigString(result);
4344 appendUiConfigString(result);
4345 appendGuiConfigString(result);
4346 result.append("\n");
4347
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004348 result.append("\nDisplay identification data:\n");
4349 dumpDisplayIdentificationData(result);
4350
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004351 result.append("\nWide-Color information:\n");
4352 dumpWideColorInfo(result);
4353
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004354 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004355 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004356 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004357 result.append(SyncFeatures::getInstance().toString());
4358 result.append("\n");
4359
Andy McFadden41d67d72014-04-25 16:58:34 -07004360 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004361 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004362 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004363
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004364 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4365 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004366 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4367 getHwComposer().isConnected(displayId)) {
4368 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004369 result.appendFormat("Display %d: "
4370 "app phase %" PRId64 " ns, "
4371 "sf phase %" PRId64 " ns, "
4372 "early app phase %" PRId64 " ns, "
4373 "early sf phase %" PRId64 " ns, "
4374 "early app gl phase %" PRId64 " ns, "
4375 "early sf gl phase %" PRId64 " ns, "
4376 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4377 displayId,
4378 vsyncPhaseOffsetNs,
4379 sfVsyncPhaseOffsetNs,
4380 appEarlyOffset,
4381 sfEarlyOffset,
4382 appEarlyGlOffset,
4383 sfEarlyOffset,
4384 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004385 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004386 result.append("\n");
4387
Dan Stozab90cf072015-03-05 11:05:59 -08004388 // Dump static screen stats
4389 result.append("\n");
4390 dumpStaticScreenStats(result);
4391 result.append("\n");
4392
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004393 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4394
Dan Stozae77c7662016-05-13 11:37:28 -07004395 dumpBufferingStats(result);
4396
Andy McFadden4803b742012-09-24 19:07:20 -07004397 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004398 * Dump the visible layer list
4399 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004400 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004401 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004402 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4403 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004404 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004405
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004406 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004407 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004408 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004409 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004410
4411 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004412 * Dump Display state
4413 */
4414
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004415 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004416 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004417 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004418 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004419 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004420 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004421 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004422
4423 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004424 * Dump SurfaceFlinger global state
4425 */
4426
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004427 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004428 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004429 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004430
Mathias Agopian888c8222012-08-04 21:10:38 -07004431 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004432 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004433
David Sodmanbc815282017-11-05 18:57:52 -08004434 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004435
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004436 if (display) {
4437 display->undefinedRegion.dump(result, "undefinedRegion");
4438 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4439 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004440 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004441 result.appendFormat(" last eglSwapBuffers() time: %f us\n"
4442 " last transaction time : %f us\n"
4443 " transaction-flags : %08x\n"
4444 " gpu_to_cpu_unsupported : %d\n",
4445 mLastSwapBufferTime / 1000.0, mLastTransactionTime / 1000.0,
4446 mTransactionFlags, !mGpuToCpuSupported);
4447
4448 if (display) {
4449 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4450 result.appendFormat(" refresh-rate : %f fps\n"
4451 " x-dpi : %f\n"
4452 " y-dpi : %f\n",
4453 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4454 activeConfig->getDpiY());
4455 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004456
Mathias Agopian74d211a2013-04-22 16:55:35 +02004457 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004458 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004459
Mathias Agopian74d211a2013-04-22 16:55:35 +02004460 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004461 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004462
4463 /*
4464 * VSYNC state
4465 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004466 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004467 result.append("\n");
4468
4469 /*
4470 * HWC layer minidump
4471 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004472 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004473 const int32_t displayId = display->getId();
4474 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004475 continue;
4476 }
4477
Dominik Laskowski7e045462018-05-30 13:02:02 -07004478 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004479 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004480 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004481 result.append("\n");
4482 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004483
4484 /*
4485 * Dump HWComposer state
4486 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004487 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004488 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004489 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004490 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004491 result.appendFormat(" h/w composer %s\n",
4492 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004493 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004494
4495 /*
4496 * Dump gralloc state
4497 */
4498 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4499 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004500
4501 /*
4502 * Dump VrFlinger state if in use.
4503 */
4504 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4505 result.append("VrFlinger state:\n");
4506 result.append(mVrFlinger->Dump().c_str());
4507 result.append("\n");
4508 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004509}
4510
Dominik Laskowski7e045462018-05-30 13:02:02 -07004511const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004512 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004513 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004514 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004515 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004516 }
4517 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004518
4519 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4520 static const Vector<sp<Layer>> empty;
4521 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004522}
4523
Keun young Park63f165f2012-08-31 10:53:36 -07004524bool SurfaceFlinger::startDdmConnection()
4525{
4526 void* libddmconnection_dso =
4527 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4528 if (!libddmconnection_dso) {
4529 return false;
4530 }
4531 void (*DdmConnection_start)(const char* name);
4532 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004533 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004534 if (!DdmConnection_start) {
4535 dlclose(libddmconnection_dso);
4536 return false;
4537 }
4538 (*DdmConnection_start)(getServiceName());
4539 return true;
4540}
4541
Chia-I Wu28f320b2018-05-03 11:02:56 -07004542void SurfaceFlinger::updateColorMatrixLocked() {
4543 mat4 colorMatrix;
4544 if (mGlobalSaturationFactor != 1.0f) {
4545 // Rec.709 luma coefficients
4546 float3 luminance{0.213f, 0.715f, 0.072f};
4547 luminance *= 1.0f - mGlobalSaturationFactor;
4548 mat4 saturationMatrix = mat4(
4549 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4550 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4551 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4552 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4553 );
4554 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4555 } else {
4556 colorMatrix = mClientColorMatrix * mDaltonizer();
4557 }
4558
4559 if (mCurrentState.colorMatrix != colorMatrix) {
4560 mCurrentState.colorMatrix = colorMatrix;
4561 mCurrentState.colorMatrixChanged = true;
4562 setTransactionFlags(eTransactionNeeded);
4563 }
4564}
4565
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004566status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004567 switch (code) {
4568 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004569 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004570 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004571 case CLEAR_ANIMATION_FRAME_STATS:
4572 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004573 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004574 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004575 case ENABLE_VSYNC_INJECTIONS:
4576 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004577 {
4578 // codes that require permission check
Robert Carrd4ae7f32018-06-07 16:10:57 -07004579 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4580 IPCThreadState* ipc = IPCThreadState::self();
4581 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4582 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004583 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004584 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004585 break;
4586 }
Robert Carr1db73f62016-12-21 12:58:51 -08004587 /*
4588 * Calling setTransactionState is safe, because you need to have been
4589 * granted a reference to Client* and Handle* to do anything with it.
4590 *
4591 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4592 */
4593 case SET_TRANSACTION_STATE:
4594 case CREATE_SCOPED_CONNECTION:
4595 {
4596 return OK;
4597 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004598 case CAPTURE_SCREEN:
4599 {
4600 // codes that require permission check
4601 IPCThreadState* ipc = IPCThreadState::self();
4602 const int pid = ipc->getCallingPid();
4603 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004604 if ((uid != AID_GRAPHICS) &&
4605 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004606 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004607 return PERMISSION_DENIED;
4608 }
4609 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004610 }
chaviwa76b2712017-09-20 12:02:26 -07004611 case CAPTURE_LAYERS: {
4612 IPCThreadState* ipc = IPCThreadState::self();
4613 const int pid = ipc->getCallingPid();
4614 const int uid = ipc->getCallingUid();
4615 if ((uid != AID_GRAPHICS) &&
4616 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4617 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4618 return PERMISSION_DENIED;
4619 }
4620 break;
4621 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004622 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004623 return OK;
4624}
4625
4626status_t SurfaceFlinger::onTransact(
4627 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4628{
4629 status_t credentialCheck = CheckTransactCodeCredentials(code);
4630 if (credentialCheck != OK) {
4631 return credentialCheck;
4632 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004633
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004634 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4635 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004636 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004637 IPCThreadState* ipc = IPCThreadState::self();
4638 const int uid = ipc->getCallingUid();
4639 if (CC_UNLIKELY(uid != AID_SYSTEM
4640 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004641 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004642 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004643 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004644 return PERMISSION_DENIED;
4645 }
4646 int n;
4647 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004648 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004649 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004650 return NO_ERROR;
4651 case 1002: // SHOW_UPDATES
4652 n = data.readInt32();
4653 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004654 invalidateHwcGeometry();
4655 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004656 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004657 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004658 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004659 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004660 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004661 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004662 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004663 setTransactionFlags(
4664 eTransactionNeeded|
4665 eDisplayTransactionNeeded|
4666 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004667 return NO_ERROR;
4668 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004669 case 1006:{ // send empty update
4670 signalRefresh();
4671 return NO_ERROR;
4672 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004673 case 1008: // toggle use of hw composer
4674 n = data.readInt32();
4675 mDebugDisableHWC = n ? 1 : 0;
4676 invalidateHwcGeometry();
4677 repaintEverything();
4678 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004679 case 1009: // toggle use of transform hint
4680 n = data.readInt32();
4681 mDebugDisableTransformHint = n ? 1 : 0;
4682 invalidateHwcGeometry();
4683 repaintEverything();
4684 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004685 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004686 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004687 reply->writeInt32(0);
4688 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004689 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004690 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004691 return NO_ERROR;
4692 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004693 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004694 if (!display) {
4695 return NAME_NOT_FOUND;
4696 }
4697
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004698 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004699 return NO_ERROR;
4700 }
4701 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004702 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004703 // daltonize
4704 n = data.readInt32();
4705 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004706 case 1:
4707 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4708 break;
4709 case 2:
4710 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4711 break;
4712 case 3:
4713 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4714 break;
4715 default:
4716 mDaltonizer.setType(ColorBlindnessType::None);
4717 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004718 }
4719 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004720 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004721 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004722 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004723 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004724
4725 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004726 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004727 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004728 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004729 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004730 // apply a color matrix
4731 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004732 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004733 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004734 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004735 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004736 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004737 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004738 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004739 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004740 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004741 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004742
4743 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4744 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004745 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004746 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4747 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4748 }
4749
Chia-I Wu28f320b2018-05-03 11:02:56 -07004750 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004751 return NO_ERROR;
4752 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004753 // This is an experimental interface
4754 // Needs to be shifted to proper binder interface when we productize
4755 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004756 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07004757 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004758 return NO_ERROR;
4759 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004760 case 1017: {
4761 n = data.readInt32();
4762 mForceFullDamage = static_cast<bool>(n);
4763 return NO_ERROR;
4764 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004765 case 1018: { // Modify Choreographer's phase offset
4766 n = data.readInt32();
4767 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4768 return NO_ERROR;
4769 }
4770 case 1019: { // Modify SurfaceFlinger's phase offset
4771 n = data.readInt32();
4772 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4773 return NO_ERROR;
4774 }
Irvel468051e2016-06-13 16:44:44 -07004775 case 1020: { // Layer updates interceptor
4776 n = data.readInt32();
4777 if (n) {
4778 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004779 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004780 }
4781 else{
4782 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004783 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004784 }
4785 return NO_ERROR;
4786 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004787 case 1021: { // Disable HWC virtual displays
4788 n = data.readInt32();
4789 mUseHwcVirtualDisplays = !n;
4790 return NO_ERROR;
4791 }
Romain Guy0147a172017-06-01 13:53:56 -07004792 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004793 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004794 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004795
Chia-I Wu28f320b2018-05-03 11:02:56 -07004796 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004797 return NO_ERROR;
4798 }
Romain Guy54f154a2017-10-24 21:40:32 +01004799 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004800 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004801 invalidateHwcGeometry();
4802 repaintEverything();
4803 return NO_ERROR;
4804 }
4805 case 1024: { // Is wide color gamut rendering/color management supported?
4806 reply->writeBool(hasWideColorDisplay);
4807 return NO_ERROR;
4808 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004809 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004810 n = data.readInt32();
4811 if (n) {
4812 ALOGV("LayerTracing enabled");
4813 mTracing.enable();
4814 doTracing("tracing.enable");
4815 reply->writeInt32(NO_ERROR);
4816 } else {
4817 ALOGV("LayerTracing disabled");
4818 status_t err = mTracing.disable();
4819 reply->writeInt32(err);
4820 }
4821 return NO_ERROR;
4822 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004823 case 1026: { // Get layer tracing status
4824 reply->writeBool(mTracing.isEnabled());
4825 return NO_ERROR;
4826 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004827 // Is a DisplayColorSetting supported?
4828 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004829 const auto display = getDefaultDisplayDevice();
4830 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004831 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004832 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004833
4834 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4835 switch (setting) {
4836 case DisplayColorSetting::MANAGED:
4837 reply->writeBool(hasWideColorDisplay);
4838 break;
4839 case DisplayColorSetting::UNMANAGED:
4840 reply->writeBool(true);
4841 break;
4842 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004843 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004844 break;
4845 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004846 reply->writeBool(
4847 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004848 break;
4849 }
4850 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004851 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004852 // Is VrFlinger active?
4853 case 1028: {
4854 Mutex::Autolock _l(mStateLock);
4855 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4856 return NO_ERROR;
4857 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004858 }
4859 }
4860 return err;
4861}
4862
Steven Thomas6d8110b2017-08-31 18:24:21 -07004863void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004864 android_atomic_or(1, &mRepaintEverything);
4865 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004866}
4867
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004868// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4869class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004870public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004871 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4872 ~WindowDisconnector() {
4873 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004874 }
4875
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004876private:
4877 ANativeWindow* mWindow;
4878 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004879};
4880
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004881status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4882 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4883 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4884 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004885 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004886 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004887
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004888 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004889
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004890 const auto display = getDisplayDeviceLocked(displayToken);
4891 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004892
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004893 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004894
4895 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004896 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004897 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004898}
4899
4900status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004901 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004902 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004903 ATRACE_CALL();
4904
4905 class LayerRenderArea : public RenderArea {
4906 public:
Robert Carr578038f2018-03-09 12:25:24 -08004907 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4908 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004909 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004910 mLayer(layer),
4911 mCrop(crop),
4912 mFlinger(flinger),
4913 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004914 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004915 Rect getBounds() const override {
4916 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07004917 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07004918 }
Marissa Wall61c58622018-07-18 10:12:20 -07004919 int getHeight() const override {
4920 return mLayer->getActiveHeight(mLayer->getDrawingState());
4921 }
4922 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07004923 bool isSecure() const override { return false; }
4924 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004925 Rect getSourceCrop() const override {
4926 if (mCrop.isEmpty()) {
4927 return getBounds();
4928 } else {
4929 return mCrop;
4930 }
4931 }
Robert Carr578038f2018-03-09 12:25:24 -08004932 class ReparentForDrawing {
4933 public:
4934 const sp<Layer>& oldParent;
4935 const sp<Layer>& newParent;
4936
4937 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4938 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004939 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004940 }
Robert Carr15eae092018-03-23 13:43:53 -07004941 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004942 };
4943
4944 void render(std::function<void()> drawLayers) override {
4945 if (!mChildrenOnly) {
4946 mTransform = mLayer->getTransform().inverse();
4947 drawLayers();
4948 } else {
4949 Rect bounds = getBounds();
4950 screenshotParentLayer =
4951 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4952 bounds.getWidth(), bounds.getHeight(), 0);
4953
4954 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4955 drawLayers();
4956 }
4957 }
chaviwa76b2712017-09-20 12:02:26 -07004958
chaviwa76b2712017-09-20 12:02:26 -07004959 private:
chaviw7206d492017-11-10 16:16:12 -08004960 const sp<Layer> mLayer;
4961 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004962
4963 // In the "childrenOnly" case we reparent the children to a screenshot
4964 // layer which has no properties set and which does not draw.
4965 sp<ContainerLayer> screenshotParentLayer;
4966 Transform mTransform;
4967
4968 SurfaceFlinger* mFlinger;
4969 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004970 };
4971
4972 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4973 auto parent = layerHandle->owner.promote();
4974
chaviw7206d492017-11-10 16:16:12 -08004975 if (parent == nullptr || parent->isPendingRemoval()) {
4976 ALOGE("captureLayers called with a removed parent");
4977 return NAME_NOT_FOUND;
4978 }
4979
Robert Carr578038f2018-03-09 12:25:24 -08004980 const int uid = IPCThreadState::self()->getCallingUid();
4981 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4982 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4983 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4984 return PERMISSION_DENIED;
4985 }
4986
chaviw7206d492017-11-10 16:16:12 -08004987 Rect crop(sourceCrop);
4988 if (sourceCrop.width() <= 0) {
4989 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07004990 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08004991 }
4992
4993 if (sourceCrop.height() <= 0) {
4994 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07004995 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08004996 }
4997
4998 int32_t reqWidth = crop.width() * frameScale;
4999 int32_t reqHeight = crop.height() * frameScale;
5000
Robert Carr578038f2018-03-09 12:25:24 -08005001 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005002
Robert Carr578038f2018-03-09 12:25:24 -08005003 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005004 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5005 if (!layer->isVisible()) {
5006 return;
Robert Carr578038f2018-03-09 12:25:24 -08005007 } else if (childrenOnly && layer == parent.get()) {
5008 return;
chaviwa76b2712017-09-20 12:02:26 -07005009 }
5010 visitor(layer);
5011 });
5012 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005013 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005014}
5015
5016status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5017 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005018 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005019 bool useIdentityTransform) {
5020 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005021
Iris Chang7501ed62018-04-30 14:45:42 +08005022 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07005023
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005024 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5025 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5026 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5027 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005028
5029 // This mutex protects syncFd and captureResult for communication of the return values from the
5030 // main thread back to this Binder thread
5031 std::mutex captureMutex;
5032 std::condition_variable captureCondition;
5033 std::unique_lock<std::mutex> captureLock(captureMutex);
5034 int syncFd = -1;
5035 std::optional<status_t> captureResult;
5036
Robert Carr03480e22018-01-04 16:02:06 -08005037 const int uid = IPCThreadState::self()->getCallingUid();
5038 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5039
Dominik Laskowski8c001672018-05-30 16:52:06 -07005040 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005041 // If there is a refresh pending, bug out early and tell the binder thread to try again
5042 // after the refresh.
5043 if (mRefreshPending) {
5044 ATRACE_NAME("Skipping screenshot for now");
5045 std::unique_lock<std::mutex> captureLock(captureMutex);
5046 captureResult = std::make_optional<status_t>(EAGAIN);
5047 captureCondition.notify_one();
5048 return;
5049 }
5050
5051 status_t result = NO_ERROR;
5052 int fd = -1;
5053 {
5054 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005055 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005056 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5057 useIdentityTransform, forSystem, &fd);
5058 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005059 }
5060
5061 {
5062 std::unique_lock<std::mutex> captureLock(captureMutex);
5063 syncFd = fd;
5064 captureResult = std::make_optional<status_t>(result);
5065 captureCondition.notify_one();
5066 }
5067 });
5068
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005069 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005070 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005071 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005072 while (*captureResult == EAGAIN) {
5073 captureResult.reset();
5074 result = postMessageAsync(message);
5075 if (result != NO_ERROR) {
5076 return result;
5077 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005078 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005079 }
5080 result = *captureResult;
5081 }
5082
5083 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005084 sync_wait(syncFd, -1);
5085 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005086 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005087
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005088 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005089}
5090
chaviwa76b2712017-09-20 12:02:26 -07005091void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5092 TraverseLayersFunction traverseLayers, bool yswap,
5093 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005094 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005095
Lloyd Pique144e1162017-12-20 16:44:52 -08005096 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005097
5098 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005099 const auto raWidth = renderArea.getWidth();
5100 const auto raHeight = renderArea.getHeight();
5101
5102 const auto reqWidth = renderArea.getReqWidth();
5103 const auto reqHeight = renderArea.getReqHeight();
5104 Rect sourceCrop = renderArea.getSourceCrop();
5105
Iris Chang7501ed62018-04-30 14:45:42 +08005106 bool filtering = false;
5107 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5108 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5109 static_cast<int32_t>(reqHeight) != raWidth;
5110 } else {
5111 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5112 static_cast<int32_t>(reqHeight) != raHeight;
5113 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005114
Dan Stozac1879002014-05-22 15:59:05 -07005115 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005116 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005117 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005118 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005119 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5120 Transform tr;
5121 uint32_t flags = 0x00;
5122 switch (mPrimaryDisplayOrientation) {
5123 case DisplayState::eOrientation90:
5124 flags = Transform::ROT_90;
5125 break;
5126 case DisplayState::eOrientation180:
5127 flags = Transform::ROT_180;
5128 break;
5129 case DisplayState::eOrientation270:
5130 flags = Transform::ROT_270;
5131 break;
5132 }
5133 tr.set(flags, raWidth, raHeight);
5134 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005135 }
5136
5137 // ensure that sourceCrop is inside screen
5138 if (sourceCrop.left < 0) {
5139 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5140 }
chaviwa76b2712017-09-20 12:02:26 -07005141 if (sourceCrop.right > raWidth) {
5142 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005143 }
5144 if (sourceCrop.top < 0) {
5145 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5146 }
chaviwa76b2712017-09-20 12:02:26 -07005147 if (sourceCrop.bottom > raHeight) {
5148 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005149 }
5150
Chia-I Wu36574d92018-05-16 10:54:36 -07005151 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5152 engine.setOutputDataSpace(Dataspace::SRGB);
5153 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005154
Mathias Agopian180f10d2013-04-10 22:55:41 -07005155 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005156 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005157
Iris Chang7501ed62018-04-30 14:45:42 +08005158 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5159 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5160 // convert hw orientation into flag presentation
5161 // here inverse transform needed
5162 uint8_t hw_rot_90 = 0x00;
5163 uint8_t hw_flip_hv = 0x00;
5164 switch (mPrimaryDisplayOrientation) {
5165 case DisplayState::eOrientation90:
5166 hw_rot_90 = Transform::ROT_90;
5167 hw_flip_hv = Transform::ROT_180;
5168 break;
5169 case DisplayState::eOrientation180:
5170 hw_flip_hv = Transform::ROT_180;
5171 break;
5172 case DisplayState::eOrientation270:
5173 hw_rot_90 = Transform::ROT_90;
5174 break;
5175 }
5176
5177 // transform flags operation
5178 // 1) flip H V if both have ROT_90 flag
5179 // 2) XOR these flags
5180 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5181 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5182 if (rotation_rot_90 & hw_rot_90) {
5183 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5184 }
5185 rotation = static_cast<Transform::orientation_flags>
5186 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5187 }
5188
Mathias Agopian180f10d2013-04-10 22:55:41 -07005189 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005190 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005191 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005192 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005193
chaviw50da5042018-04-09 13:49:37 -07005194 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005195 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005196 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005197
chaviwa76b2712017-09-20 12:02:26 -07005198 traverseLayers([&](Layer* layer) {
5199 if (filtering) layer->setFiltering(true);
David Sodmanca10ed22018-04-16 14:10:25 -07005200 layer->drawNow(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005201 if (filtering) layer->setFiltering(false);
5202 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005203}
5204
chaviwa76b2712017-09-20 12:02:26 -07005205status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5206 TraverseLayersFunction traverseLayers,
5207 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005208 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005209 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005210 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005211 ATRACE_CALL();
5212
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005213 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005214
5215 traverseLayers([&](Layer* layer) {
5216 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5217 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005218
Robert Carr03480e22018-01-04 16:02:06 -08005219 // We allow the system server to take screenshots of secure layers for
5220 // use in situations like the Screen-rotation animation and place
5221 // the impetus on WindowManager to not persist them.
5222 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005223 ALOGW("FB is protected: PERMISSION_DENIED");
5224 return PERMISSION_DENIED;
5225 }
5226
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005227 // this binds the given EGLImage as a framebuffer for the
5228 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005229 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005230 if (bufferBond.getStatus() != NO_ERROR) {
5231 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005232 return INVALID_OPERATION;
5233 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005234
Dan Stozaabcda352017-06-01 14:37:39 -07005235 // this will in fact render into our dequeued buffer
5236 // via an FBO, which means we didn't have to create
5237 // an EGLSurface and therefore we're not
5238 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005239 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005240
Dan Stozaabcda352017-06-01 14:37:39 -07005241 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005242 getRenderEngine().finish();
5243 *outSyncFd = -1;
5244
chaviwa76b2712017-09-20 12:02:26 -07005245 const auto reqWidth = renderArea.getReqWidth();
5246 const auto reqHeight = renderArea.getReqHeight();
5247
Dan Stozaabcda352017-06-01 14:37:39 -07005248 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5249 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005250 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005251 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005252 } else {
5253 base::unique_fd syncFd = getRenderEngine().flush();
5254 if (syncFd < 0) {
5255 getRenderEngine().finish();
5256 }
5257 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005258 }
5259
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005260 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005261}
5262
Mathias Agopiand5556842013-09-19 17:08:37 -07005263void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005264 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005265 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005266 for (size_t y = 0; y < h; y++) {
5267 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5268 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005269 if (p[x] != 0xFF000000) return;
5270 }
5271 }
chaviwa76b2712017-09-20 12:02:26 -07005272 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005273
Robert Carr2047fae2016-11-28 14:09:09 -08005274 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005275 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005276 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005277 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5278 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5279 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5280 static_cast<float>(state.color.a));
5281 i++;
5282 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005283 }
5284}
5285
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005286// ---------------------------------------------------------------------------
5287
Dan Stoza412903f2017-04-27 13:42:17 -07005288void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5289 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005290}
5291
Dan Stoza412903f2017-04-27 13:42:17 -07005292void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5293 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005294}
5295
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005296void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5297 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005298 const LayerVector::Visitor& visitor) {
5299 // We loop through the first level of layers without traversing,
5300 // as we need to interpret min/max layer Z in the top level Z space.
5301 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005302 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005303 continue;
5304 }
5305 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005306 // relative layers are traversed in Layer::traverseInZOrder
5307 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005308 continue;
5309 }
5310 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005311 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005312 return;
5313 }
chaviwa76b2712017-09-20 12:02:26 -07005314 if (!layer->isVisible()) {
5315 return;
5316 }
5317 visitor(layer);
5318 });
5319 }
5320}
5321
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005322}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005323
Lloyd Pique074e8122018-07-26 12:57:23 -07005324
Mathias Agopian3f844832013-08-07 21:24:32 -07005325#if defined(__gl_h_)
5326#error "don't include gl/gl.h in this file"
5327#endif
5328
5329#if defined(__gl2_h_)
5330#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005331#endif