blob: c0c684a502182fe716512cf5b89e802e8f2b77a9 [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"
Robert Carr578038f2018-03-09 12:25:24 -080073#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Steven Thomasb02664d2017-07-26 18:48:28 -070079#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070080#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070084#include "Effects/Daltonizer.h"
Mathias Agopian875d8e12013-06-07 15:35:48 -070085#include "RenderEngine/RenderEngine.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070086#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070087#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070088#include "Scheduler/EventControlThread.h"
89#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070090#include "Scheduler/InjectVSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070091
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 mDebugInTransaction(0),
263 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700264 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700265 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700266 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800267 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800268 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800269 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700270 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800271 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800272 mCreateBufferQueue(&BufferQueue::createBufferQueue),
273 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800274
275SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800276 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800277
278 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
279 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
280
281 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
282 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
283
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800284 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
285 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800286
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700287 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
288 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
289
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700290 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
291 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
292
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800293 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
294 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
295
Steven Thomas050b2c82017-03-06 11:45:16 -0800296 // Vr flinger is only enabled on Daydream ready devices.
297 useVrFlinger = getBool< ISurfaceFlingerConfigs,
298 &ISurfaceFlingerConfigs::useVrFlinger>(false);
299
Fabien Sanglard1971b632017-03-10 14:50:03 -0800300 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
301 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
302
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600303 hasWideColorDisplay =
304 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
305
Iris Chang7501ed62018-04-30 14:45:42 +0800306 V1_1::DisplayOrientation primaryDisplayOrientation =
307 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
308 V1_1::DisplayOrientation::ORIENTATION_0);
309
310 switch (primaryDisplayOrientation) {
311 case V1_1::DisplayOrientation::ORIENTATION_90:
312 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
313 break;
314 case V1_1::DisplayOrientation::ORIENTATION_180:
315 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
316 break;
317 case V1_1::DisplayOrientation::ORIENTATION_270:
318 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
319 break;
320 default:
321 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
322 break;
323 }
324 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
325
Lloyd Pique41be5d22018-06-21 13:11:48 -0700326 // Note: We create a local temporary with the real DispSync implementation
327 // type temporarily so we can initialize it with the configured values,
328 // before storing it for more generic use using the interface type.
329 auto primaryDispSync = std::make_unique<impl::DispSync>("PrimaryDispSync");
330 primaryDispSync->init(SurfaceFlinger::hasSyncFramework,
331 SurfaceFlinger::dispSyncPresentTimeOffset);
332 mPrimaryDispSync = std::move(primaryDispSync);
Saurabh Shahf4174532017-07-13 10:45:07 -0700333
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800334 // debugging stuff...
335 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700336
Mathias Agopianb4b17302013-03-20 18:36:41 -0700337 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700338 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700339
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800340 property_get("debug.sf.showupdates", value, "0");
341 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700342
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700343 property_get("debug.sf.ddms", value, "0");
344 mDebugDDMS = atoi(value);
345 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700346 if (!startDdmConnection()) {
347 // start failed, and DDMS debugging not enabled
348 mDebugDDMS = 0;
349 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700350 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700351 ALOGI_IF(mDebugRegion, "showupdates enabled");
352 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700353
354 property_get("debug.sf.disable_backpressure", value, "0");
355 mPropagateBackpressure = !atoi(value);
356 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700357
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800358 property_get("debug.sf.enable_hwc_vds", value, "0");
359 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800360 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800361
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800362 property_get("ro.sf.disable_triple_buffer", value, "1");
363 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800364 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700365
Yiwei Zhang243b3782018-05-15 17:40:04 -0700366 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700367 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
368 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
369
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200370 property_get("debug.sf.early_phase_offset_ns", value, "-1");
371 const int earlySfOffsetNs = atoi(value);
372
373 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
374 const int earlyGlSfOffsetNs = atoi(value);
375
376 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
377 const int earlyAppOffsetNs = atoi(value);
378
379 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
380 const int earlyGlAppOffsetNs = atoi(value);
381
382 const VSyncModulator::Offsets earlyOffsets =
383 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
384 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
385 const VSyncModulator::Offsets earlyGlOffsets =
386 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
387 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
388 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
389 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700390
Romain Guy11d63f42017-07-20 12:47:14 -0700391 // We should be reading 'persist.sys.sf.color_saturation' here
392 // but since /data may be encrypted, we need to wait until after vold
393 // comes online to attempt to read the property. The property is
394 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800395
396 if (useTrebleTestingOverride()) {
397 // Without the override SurfaceFlinger cannot connect to HIDL
398 // services that are not listed in the manifests. Considered
399 // deriving the setting from the set service name, but it
400 // would be brittle if the name that's not 'default' is used
401 // for production purposes later on.
402 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
403 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800404}
405
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800406void SurfaceFlinger::onFirstRef()
407{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800408 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800409}
410
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800411SurfaceFlinger::~SurfaceFlinger()
412{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800413}
414
Dan Stozac7014012014-02-14 15:03:43 -0800415void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800416{
417 // the window manager died on us. prepare its eulogy.
418
Andy McFadden13a082e2012-08-24 10:16:42 -0700419 // restore initial conditions (default device unblank, etc)
420 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800421
422 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700423 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800424}
425
Robert Carr1db73f62016-12-21 12:58:51 -0800426static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700427 status_t err = client->initCheck();
428 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800429 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800430 }
Robert Carr1db73f62016-12-21 12:58:51 -0800431 return nullptr;
432}
433
434sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
435 return initClient(new Client(this));
436}
437
438sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
439 const sp<IGraphicBufferProducer>& gbp) {
440 if (authenticateSurfaceTexture(gbp) == false) {
441 return nullptr;
442 }
443 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
444 if (layer == nullptr) {
445 return nullptr;
446 }
447
448 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800449}
450
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700451sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
452 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700453{
454 class DisplayToken : public BBinder {
455 sp<SurfaceFlinger> flinger;
456 virtual ~DisplayToken() {
457 // no more references, this display must be terminated
458 Mutex::Autolock _l(flinger->mStateLock);
459 flinger->mCurrentState.displays.removeItem(this);
460 flinger->setTransactionFlags(eDisplayTransactionNeeded);
461 }
462 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700463 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700464 : flinger(flinger) {
465 }
466 };
467
468 sp<BBinder> token = new DisplayToken(this);
469
470 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700471 DisplayDeviceState info;
472 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700473 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700474 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700475 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800476 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700477 return token;
478}
479
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700480void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700481 Mutex::Autolock _l(mStateLock);
482
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700483 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700484 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700485 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700486 return;
487 }
488
489 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700490 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700491 ALOGE("destroyDisplay called for non-virtual display");
492 return;
493 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700494 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700495 mCurrentState.displays.removeItemsAt(idx);
496 setTransactionFlags(eDisplayTransactionNeeded);
497}
498
Mathias Agopiane57f2922012-08-09 16:29:12 -0700499sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700500 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700501 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800502 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700503 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700504 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700505}
506
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800507void SurfaceFlinger::bootFinished()
508{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700509 if (mStartPropertySetThread->join() != NO_ERROR) {
510 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800511 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800512 const nsecs_t now = systemTime();
513 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000514 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700515
516 // wait patiently for the window manager death
517 const String16 name("window");
518 sp<IBinder> window(defaultServiceManager()->getService(name));
519 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700520 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700521 }
522
Steven Thomas050b2c82017-03-06 11:45:16 -0800523 if (mVrFlinger) {
524 mVrFlinger->OnBootFinished();
525 }
526
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700527 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700528 // formerly we would just kill the process, but we now ask it to exit so it
529 // can choose where to stop the animation.
530 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700531
532 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
533 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
534 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700535
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800536 postMessageAsync(new LambdaMessage([this] {
537 readPersistentProperties();
538 mBootStage = BootStage::FINISHED;
539 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800540}
541
Dan Stoza436ccf32018-06-21 12:10:12 -0700542uint32_t SurfaceFlinger::getNewTexture() {
543 {
544 std::lock_guard lock(mTexturePoolMutex);
545 if (!mTexturePool.empty()) {
546 uint32_t name = mTexturePool.back();
547 mTexturePool.pop_back();
548 ATRACE_INT("TexturePoolSize", mTexturePool.size());
549 return name;
550 }
551
552 // The pool was too small, so increase it for the future
553 ++mTexturePoolSize;
554 }
555
556 // The pool was empty, so we need to get a new texture name directly using a
557 // blocking call to the main thread
558 uint32_t name = 0;
559 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
560 return name;
561}
562
Mathias Agopian3f844832013-08-07 21:24:32 -0700563void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700564 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700565}
566
Wei Wangf9b05ee2017-07-19 20:59:39 -0700567// Do not call property_set on main thread which will be blocked by init
568// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700569void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700570 ALOGI( "SurfaceFlinger's main thread ready to run. "
571 "Initializing graphics H/W...");
572
Thierry Strudel2924d012017-08-14 15:19:37 -0700573 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900574
Steven Thomasb02664d2017-07-26 18:48:28 -0700575 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800576
Steven Thomasb02664d2017-07-26 18:48:28 -0700577 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800578 mEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700579 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
580 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800581 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700582 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800583 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800584 "appEventThread");
585 mSfEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700586 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800587 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800588
Lloyd Pique24b0a482018-03-09 18:52:26 -0800589 mSFEventThread =
590 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700591 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800592 [this](nsecs_t timestamp) {
593 mInterceptor->saveVSyncEvent(timestamp);
594 },
595 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800596 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200597 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800598
Steven Thomasb02664d2017-07-26 18:48:28 -0700599 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800600 getBE().mRenderEngine =
601 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
602 hasWideColorDisplay
603 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
604 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800605 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700606
607 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
608 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800609 getBE().mHwc.reset(
610 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700611 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800612 // Process any initial hotplug and resulting display changes.
613 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700614 const auto display = getDefaultDisplayDeviceLocked();
615 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
616 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
617 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800618
Lloyd Piquefcd86612017-12-14 17:15:36 -0800619 // make the default display GLContext current so that we can create textures
620 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700621 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800622
Steven Thomas050b2c82017-03-06 11:45:16 -0800623 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700624 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700625 // This callback is called from the vr flinger dispatch thread. We
626 // need to call signalTransaction(), which requires holding
627 // mStateLock when we're not on the main thread. Acquiring
628 // mStateLock from the vr flinger dispatch thread might trigger a
629 // deadlock in surface flinger (see b/66916578), so post a message
630 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700631 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700632 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
633 mVrFlingerRequestsDisplay = requestDisplay;
634 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700635 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800636 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700637 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
638 getHwComposer()
639 .getHwcDisplayId(display->getId())
640 .value_or(0),
641 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800642 if (!mVrFlinger) {
643 ALOGE("Failed to start vrflinger");
644 }
645 }
646
Lloyd Pique379adc12018-01-22 17:31:47 -0800647 mEventControlThread = std::make_unique<impl::EventControlThread>(
648 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700649
Mathias Agopian92a979a2012-08-02 18:32:23 -0700650 // initialize our drawing state
651 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700652
Andy McFadden13a082e2012-08-24 10:16:42 -0700653 // set initial conditions (e.g. unblank default device)
654 initializeDisplays();
655
David Sodmanbc815282017-11-05 18:57:52 -0800656 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700657
Wei Wangf9b05ee2017-07-19 20:59:39 -0700658 // Inform native graphics APIs whether the present timestamp is supported:
659 if (getHwComposer().hasCapability(
660 HWC2::Capability::PresentFenceIsNotReliable)) {
661 mStartPropertySetThread = new StartPropertySetThread(false);
662 } else {
663 mStartPropertySetThread = new StartPropertySetThread(true);
664 }
665
666 if (mStartPropertySetThread->Start() != NO_ERROR) {
667 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800668 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800669
Chia-I Wud49d6692018-06-27 07:17:41 +0800670 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
671 // is used to saturate legacy sRGB content. However, to make sure the same color under
672 // Display P3 will be saturated to the same color, we intentionally break the API spec
673 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
674 // such saturation matrix on Display P3 is understood fully, the API should always return
675 // identify matrix.
676 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
677 Dataspace::SRGB_LINEAR);
678
679 // we will apply this on Display P3.
680 if (mEnhancedSaturationMatrix != mat4()) {
681 ColorSpace srgb(ColorSpace::sRGB());
682 ColorSpace displayP3(ColorSpace::DisplayP3());
683 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
684 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
685 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
686 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800687
Dan Stoza9e56aa02015-11-02 13:00:03 -0800688 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700689}
690
Romain Guy11d63f42017-07-20 12:47:14 -0700691void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700692 Mutex::Autolock _l(mStateLock);
693
Romain Guy11d63f42017-07-20 12:47:14 -0700694 char value[PROPERTY_VALUE_MAX];
695
696 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800697 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700698 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800699 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100700
701 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700702 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700703}
704
Mathias Agopiana67e4182012-06-19 17:26:12 -0700705void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800706 // Start boot animation service by setting a property mailbox
707 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700708 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800709 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700710 if (mStartPropertySetThread->join() != NO_ERROR) {
711 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800712 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700713}
714
Mathias Agopian875d8e12013-06-07 15:35:48 -0700715size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800716 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700717}
718
Mathias Agopian875d8e12013-06-07 15:35:48 -0700719size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800720 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700721}
722
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800723// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800724
Jamie Gennis582270d2011-08-17 18:19:00 -0700725bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800726 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800727 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800728 return authenticateSurfaceTextureLocked(bufferProducer);
729}
730
731bool SurfaceFlinger::authenticateSurfaceTextureLocked(
732 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800733 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800734 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800735}
736
Brian Anderson6b376712017-04-04 10:51:39 -0700737status_t SurfaceFlinger::getSupportedFrameTimestamps(
738 std::vector<FrameEvent>* outSupported) const {
739 *outSupported = {
740 FrameEvent::REQUESTED_PRESENT,
741 FrameEvent::ACQUIRE,
742 FrameEvent::LATCH,
743 FrameEvent::FIRST_REFRESH_START,
744 FrameEvent::LAST_REFRESH_START,
745 FrameEvent::GPU_COMPOSITION_DONE,
746 FrameEvent::DEQUEUE_READY,
747 FrameEvent::RELEASE,
748 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700749 ConditionalLock _l(mStateLock,
750 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700751 if (!getHwComposer().hasCapability(
752 HWC2::Capability::PresentFenceIsNotReliable)) {
753 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
754 }
755 return NO_ERROR;
756}
757
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700758status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
759 Vector<DisplayInfo>* configs) {
760 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700761 return BAD_VALUE;
762 }
763
Jesse Hall692c7232012-11-08 15:41:56 -0800764 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700765 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
766 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700767 type = i;
768 break;
769 }
770 }
771
772 if (type < 0) {
773 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700774 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700775
Mathias Agopian8b736f12012-08-13 17:54:26 -0700776 // TODO: Not sure if display density should handled by SF any longer
777 class Density {
778 static int getDensityFromProperty(char const* propName) {
779 char property[PROPERTY_VALUE_MAX];
780 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800781 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700782 density = atoi(property);
783 }
784 return density;
785 }
786 public:
787 static int getEmuDensity() {
788 return getDensityFromProperty("qemu.sf.lcd_density"); }
789 static int getBuildDensity() {
790 return getDensityFromProperty("ro.sf.lcd_density"); }
791 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700792
Dan Stoza7f7da322014-05-02 15:26:25 -0700793 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700794
Steven Thomas6d8110b2017-08-31 18:24:21 -0700795 ConditionalLock _l(mStateLock,
796 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800797 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700798 DisplayInfo info = DisplayInfo();
799
Dan Stoza9e56aa02015-11-02 13:00:03 -0800800 float xdpi = hwConfig->getDpiX();
801 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700802
803 if (type == DisplayDevice::DISPLAY_PRIMARY) {
804 // The density of the device is provided by a build property
805 float density = Density::getBuildDensity() / 160.0f;
806 if (density == 0) {
807 // the build doesn't provide a density -- this is wrong!
808 // use xdpi instead
809 ALOGE("ro.sf.lcd_density must be defined as a build property");
810 density = xdpi / 160.0f;
811 }
812 if (Density::getEmuDensity()) {
813 // if "qemu.sf.lcd_density" is specified, it overrides everything
814 xdpi = ydpi = density = Density::getEmuDensity();
815 density /= 160.0f;
816 }
817 info.density = density;
818
819 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700820 const auto display = getDefaultDisplayDeviceLocked();
821 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700822 } else {
823 // TODO: where should this value come from?
824 static const int TV_DENSITY = 213;
825 info.density = TV_DENSITY / 160.0f;
826 info.orientation = 0;
827 }
828
Dan Stoza9e56aa02015-11-02 13:00:03 -0800829 info.w = hwConfig->getWidth();
830 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700831 info.xdpi = xdpi;
832 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800833 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900834 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800835
Andy McFadden91b2ca82014-06-13 14:04:23 -0700836 // This is how far in advance a buffer must be queued for
837 // presentation at a given time. If you want a buffer to appear
838 // on the screen at time N, you must submit the buffer before
839 // (N - presentationDeadline).
840 //
841 // Normally it's one full refresh period (to give SF a chance to
842 // latch the buffer), but this can be reduced by configuring a
843 // DispSync offset. Any additional delays introduced by the hardware
844 // composer or panel must be accounted for here.
845 //
846 // We add an additional 1ms to allow for processing time and
847 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800848 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800849 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700850
851 // All non-virtual displays are currently considered secure.
852 info.secure = true;
853
Iris Chang7501ed62018-04-30 14:45:42 +0800854 if (type == DisplayDevice::DISPLAY_PRIMARY &&
855 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
856 std::swap(info.w, info.h);
857 }
858
Michael Wright28f24d02016-07-12 13:30:53 -0700859 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700860 }
861
Dan Stoza7f7da322014-05-02 15:26:25 -0700862 return NO_ERROR;
863}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700864
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700865status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
866 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700867 return BAD_VALUE;
868 }
869
870 // FIXME for now we always return stats for the primary display
871 memset(stats, 0, sizeof(*stats));
Lloyd Pique41be5d22018-06-21 13:11:48 -0700872 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
873 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700874 return NO_ERROR;
875}
876
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700877int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
878 const auto display = getDisplayDevice(displayToken);
879 if (!display) {
880 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800881 return BAD_VALUE;
882 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700883
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700884 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700885}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700886
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700887void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
888 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700889 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700890 return;
891 }
892
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700893 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700894 ALOGW("Trying to set config for virtual display");
895 return;
896 }
897
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700898 display->setActiveConfig(mode);
899 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700900}
901
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700902status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700903 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700904 Vector<DisplayInfo> configs;
905 getDisplayConfigs(displayToken, &configs);
906 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
907 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
908 configs.size());
909 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700910 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700911 const auto display = getDisplayDevice(displayToken);
912 if (!display) {
913 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
914 displayToken.get());
915 } else if (display->isVirtual()) {
916 ALOGW("Attempt to set active config %d for virtual display", mode);
917 } else {
918 setActiveConfigInternal(display, mode);
919 }
920 }));
921
Mathias Agopian888c8222012-08-04 21:10:38 -0700922 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700923}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700924status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
925 Vector<ColorMode>* outColorModes) {
926 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700927 return BAD_VALUE;
928 }
929
Michael Wright28f24d02016-07-12 13:30:53 -0700930 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700931 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
932 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700933 type = i;
934 break;
935 }
936 }
937
938 if (type < 0) {
939 return type;
940 }
941
Peiyong Lina52f0292018-03-14 17:26:31 -0700942 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700943 {
944 ConditionalLock _l(mStateLock,
945 std::this_thread::get_id() != mMainThreadId);
946 modes = getHwComposer().getColorModes(type);
947 }
Michael Wright28f24d02016-07-12 13:30:53 -0700948 outColorModes->clear();
949 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
950
951 return NO_ERROR;
952}
953
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700954ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
955 if (const auto display = getDisplayDevice(displayToken)) {
956 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700957 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700958 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700959}
960
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700961void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
962 Dataspace dataSpace, RenderIntent renderIntent) {
963 ColorMode currentMode = display->getActiveColorMode();
964 Dataspace currentDataSpace = display->getCompositionDataSpace();
965 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -0700966
Peiyong Lin38e9a562018-04-10 16:24:20 -0700967 if (mode == currentMode && dataSpace == currentDataSpace &&
968 renderIntent == currentRenderIntent) {
969 return;
970 }
971
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700972 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -0700973 ALOGW("Trying to set config for virtual display");
974 return;
975 }
976
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700977 display->setActiveColorMode(mode);
978 display->setCompositionDataSpace(dataSpace);
979 display->setActiveRenderIntent(renderIntent);
980 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800981
982 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700983 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
984 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -0700985}
986
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700987status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700988 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700989 Vector<ColorMode> modes;
990 getDisplayColorModes(displayToken, &modes);
991 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
992 if (mode < ColorMode::NATIVE || !exists) {
993 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
994 decodeColorMode(mode).c_str(), mode, displayToken.get());
995 return;
Michael Wright28f24d02016-07-12 13:30:53 -0700996 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700997 const auto display = getDisplayDevice(displayToken);
998 if (!display) {
999 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1000 decodeColorMode(mode).c_str(), mode, displayToken.get());
1001 } else if (display->isVirtual()) {
1002 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1003 decodeColorMode(mode).c_str(), mode);
1004 } else {
1005 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1006 RenderIntent::COLORIMETRIC);
1007 }
1008 }));
1009
Michael Wright28f24d02016-07-12 13:30:53 -07001010 return NO_ERROR;
1011}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001012
Svetoslavd85084b2014-03-20 10:28:31 -07001013status_t SurfaceFlinger::clearAnimationFrameStats() {
1014 Mutex::Autolock _l(mStateLock);
1015 mAnimFrameTracker.clearStats();
1016 return NO_ERROR;
1017}
1018
1019status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1020 Mutex::Autolock _l(mStateLock);
1021 mAnimFrameTracker.getStats(outStats);
1022 return NO_ERROR;
1023}
1024
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001025status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1026 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001027 Mutex::Autolock _l(mStateLock);
1028
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001029 const auto display = getDisplayDeviceLocked(displayToken);
1030 if (!display) {
1031 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001032 return BAD_VALUE;
1033 }
1034
Peiyong Linfb069302018-04-25 14:34:31 -07001035 // At this point the DisplayDeivce should already be set up,
1036 // meaning the luminance information is already queried from
1037 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001038 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001039 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1040 capabilities.getDesiredMaxLuminance(),
1041 capabilities.getDesiredMaxAverageLuminance(),
1042 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001043
1044 return NO_ERROR;
1045}
1046
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001047status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001048 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001049 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001050
Chia-I Wu90f669f2017-10-05 14:24:41 -07001051 if (mInjectVSyncs == enable) {
1052 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001053 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001054
1055 if (enable) {
1056 ALOGV("VSync Injections enabled");
1057 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001058 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001059 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001060 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001061 impl::EventThread::InterceptVSyncsCallback(),
1062 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001063 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001064 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001065 } else {
1066 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001067 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001068 }
1069
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001070 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001071 }));
1072
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001073 return NO_ERROR;
1074}
1075
1076status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001077 Mutex::Autolock _l(mStateLock);
1078
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001079 if (!mInjectVSyncs) {
1080 ALOGE("VSync Injections not enabled");
1081 return BAD_VALUE;
1082 }
1083 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1084 ALOGV("Injecting VSync inside SurfaceFlinger");
1085 mVSyncInjector->onInjectSyncEvent(when);
1086 }
1087 return NO_ERROR;
1088}
1089
Lloyd Pique755e3192018-01-31 16:46:15 -08001090status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1091 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001092 // Try to acquire a lock for 1s, fail gracefully
1093 const status_t err = mStateLock.timedLock(s2ns(1));
1094 const bool locked = (err == NO_ERROR);
1095 if (!locked) {
1096 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1097 return TIMED_OUT;
1098 }
1099
1100 outLayers->clear();
1101 mCurrentState.traverseInZOrder([&](Layer* layer) {
1102 outLayers->push_back(layer->getLayerDebugInfo());
1103 });
1104
1105 mStateLock.unlock();
1106 return NO_ERROR;
1107}
1108
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001109// ----------------------------------------------------------------------------
1110
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001111sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1112 ISurfaceComposer::VsyncSource vsyncSource) {
1113 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1114 return mSFEventThread->createEventConnection();
1115 } else {
1116 return mEventThread->createEventConnection();
1117 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001118}
1119
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001120// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001121
1122void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001123 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001124}
1125
1126void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001127 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001128}
1129
1130void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001131 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001132}
1133
1134void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001135 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001136 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001137}
1138
1139status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001140 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001141 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001142}
1143
1144status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001145 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001146 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001147 if (res == NO_ERROR) {
1148 msg->wait();
1149 }
1150 return res;
1151}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001152
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001153void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001154 do {
1155 waitForEvent();
1156 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001157}
1158
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001159void SurfaceFlinger::enableHardwareVsync() {
1160 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001161 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001162 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001163 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001164 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001165 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001166}
1167
Jesse Hall948fe0c2013-10-14 12:56:09 -07001168void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001169 Mutex::Autolock _l(mHWVsyncLock);
1170
Jesse Hall948fe0c2013-10-14 12:56:09 -07001171 if (makeAvailable) {
1172 mHWVsyncAvailable = true;
1173 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001174 // Hardware vsync is not currently available, so abort the resync
1175 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001176 return;
1177 }
1178
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001179 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1180 if (!getHwComposer().isConnected(displayId)) {
1181 return;
1182 }
1183
1184 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001185 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001186
Lloyd Pique41be5d22018-06-21 13:11:48 -07001187 mPrimaryDispSync->reset();
1188 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001189
1190 if (!mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001191 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001192 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001193 mPrimaryHWVsyncEnabled = true;
1194 }
1195}
1196
Jesse Hall948fe0c2013-10-14 12:56:09 -07001197void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001198 Mutex::Autolock _l(mHWVsyncLock);
1199 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001200 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001201 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001202 mPrimaryHWVsyncEnabled = false;
1203 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001204 if (makeUnavailable) {
1205 mHWVsyncAvailable = false;
1206 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001207}
1208
Tim Murray4a4e4a22016-04-19 16:29:23 +00001209void SurfaceFlinger::resyncWithRateLimit() {
1210 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001211
1212 // No explicit locking is needed here since EventThread holds a lock while calling this method
1213 static nsecs_t sLastResyncAttempted = 0;
1214 const nsecs_t now = systemTime();
1215 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001216 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001217 }
Dan Stoza57164302017-05-08 14:03:54 -07001218 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001219}
1220
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001221void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1222 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001223 ATRACE_NAME("SF onVsync");
1224
Steven Thomas3cfac282017-02-06 12:29:30 -08001225 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001226 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001227 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001228 return;
1229 }
1230
1231 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001232 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001233 return;
1234 }
1235
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001236 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1237 // For now, we don't do anything with external display vsyncs.
1238 return;
1239 }
1240
Jamie Gennisd1700752013-10-14 12:22:52 -07001241 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001242
Jamie Gennisd1700752013-10-14 12:22:52 -07001243 { // Scope for the lock
1244 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001245 if (mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001246 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001247 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001248 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001249
1250 if (needsHwVsync) {
1251 enableHardwareVsync();
1252 } else {
1253 disableHardwareVsync(false);
1254 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001255}
1256
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001257void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001258 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1259 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001260}
1261
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001262void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001263 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001264 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001265 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001266
Lloyd Piqueba04e622017-12-14 17:11:26 -08001267 // Ignore events that do not have the right sequenceId.
1268 if (sequenceId != getBE().mComposerSequenceId) {
1269 return;
1270 }
1271
Steven Thomasb02664d2017-07-26 18:48:28 -07001272 // Only lock if we're not on the main thread. This function is normally
1273 // called on a hwbinder thread, but for the primary display it's called on
1274 // the main thread with the state lock already held, so don't attempt to
1275 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001276 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001277
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001278 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001279
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001280 if (std::this_thread::get_id() == mMainThreadId) {
1281 // Process all pending hot plug events immediately if we are on the main thread.
1282 processDisplayHotplugEventsLocked();
1283 }
1284
Lloyd Piqueba04e622017-12-14 17:11:26 -08001285 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001286}
1287
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001288void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001289 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001290 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001291 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001292 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001293 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001294}
1295
Dan Stoza9e56aa02015-11-02 13:00:03 -08001296void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001297 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001298 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001299 getHwComposer().setVsyncEnabled(disp,
1300 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001301}
1302
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001303// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001304void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001305 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001306 // Clear the drawing state so that the logic inside of
1307 // handleTransactionLocked will fire. It will determine the delta between
1308 // mCurrentState and mDrawingState and re-apply all changes when we make the
1309 // transition.
1310 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001311 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001312 mDisplays.clear();
1313}
1314
Steven Thomas050b2c82017-03-06 11:45:16 -08001315void SurfaceFlinger::updateVrFlinger() {
1316 if (!mVrFlinger)
1317 return;
1318 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001319 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001320 return;
1321 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001322
David Sodman105b7dc2017-11-04 20:28:14 -07001323 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001324 ALOGE("Vr flinger is only supported for remote hardware composer"
1325 " service connections. Ignoring request to transition to vr"
1326 " flinger.");
1327 mVrFlingerRequestsDisplay = false;
1328 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001329 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001330
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001331 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001332
Steven Thomas0123ac62018-07-12 11:32:34 -07001333 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001334 LOG_ALWAYS_FATAL_IF(!display);
1335 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001336 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1337 // called below. Clear the reference now so we don't accidentally use it
1338 // later.
1339 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001340
Steven Thomasb02664d2017-07-26 18:48:28 -07001341 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001342 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001343 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001344
Steven Thomasb02664d2017-07-26 18:48:28 -07001345 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001346 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001347 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1348 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001349 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001350
David Sodman105b7dc2017-11-04 20:28:14 -07001351 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1352 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001353
1354 if (vrFlingerRequestsDisplay) {
1355 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001356 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001357
1358 mVisibleRegionsDirty = true;
1359 invalidateHwcGeometry();
1360
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001361 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001362 display = getDefaultDisplayDeviceLocked();
1363 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001364 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001365
Steven Thomasb02664d2017-07-26 18:48:28 -07001366 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001367 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001368 const nsecs_t period = activeConfig->getVsyncPeriod();
1369 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001370
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001371 // The present fences returned from vr_hwc are not an accurate
1372 // representation of vsync times.
Lloyd Pique41be5d22018-06-21 13:11:48 -07001373 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1374 !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001375
Steven Thomasb02664d2017-07-26 18:48:28 -07001376 // Use phase of 0 since phase is not known.
1377 // Use latency of 0, which will snap to the ideal latency.
1378 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001379
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001380 resyncToHardwareVsync(false);
1381
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001382 android_atomic_or(1, &mRepaintEverything);
1383 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001384}
1385
Mathias Agopian4fec8732012-06-29 14:12:52 -07001386void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001387 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001388 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001389 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001390 bool frameMissed = !mHadClientComposition &&
1391 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001392 (mPreviousPresentFence->getSignalTime() ==
1393 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001394 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001395 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001396 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001397 mTimeStats.incrementMissedFrames();
1398 if (mPropagateBackpressure) {
1399 signalLayerUpdate();
1400 break;
1401 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001402 }
Dan Stoza50182882016-07-08 12:02:20 -07001403
Steven Thomas050b2c82017-03-06 11:45:16 -08001404 // Now that we're going to make it to the handleMessageTransaction()
1405 // call below it's safe to call updateVrFlinger(), which will
1406 // potentially trigger a display handoff.
1407 updateVrFlinger();
1408
Dan Stoza6b9454d2014-11-07 16:00:59 -08001409 bool refreshNeeded = handleMessageTransaction();
1410 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001411 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001412 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001413 // Signal a refresh if a transaction modified the window state,
1414 // a new buffer was latched, or if HWC has requested a full
1415 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001416 signalRefresh();
1417 }
1418 break;
1419 }
1420 case MessageQueue::REFRESH: {
1421 handleMessageRefresh();
1422 break;
1423 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001424 }
1425}
1426
Dan Stoza6b9454d2014-11-07 16:00:59 -08001427bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001428 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001429 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001430 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001431 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001432 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001433 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001434}
1435
Mathias Agopian4fec8732012-06-29 14:12:52 -07001436void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001437 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001438
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001439 mRefreshPending = false;
1440
David Sodmanfa9b2af2017-12-24 13:28:59 -08001441 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
David Sodman2b406362017-12-15 13:33:47 -08001442 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001443 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001444 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001445 for (const auto& [token, display] : mDisplays) {
1446 beginFrame(display);
1447 prepareFrame(display);
1448 doDebugFlashRegions(display, repaintEverything);
1449 doComposition(display, repaintEverything);
1450 }
1451
Adrian Roos1e1a1282017-11-01 19:05:31 +01001452 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001453 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001454
1455 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001456 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001457
Dan Stozabfbffeb2016-07-21 14:49:33 -07001458 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001459 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001460 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001461 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001462 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001463
Jorim Jaggi90535212018-05-23 23:44:06 +02001464 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001465
Dan Stoza9e56aa02015-11-02 13:00:03 -08001466 mLayersWithQueuedFrames.clear();
David Sodmanba340492018-08-05 21:51:33 -07001467 for (auto& compositionInfo : getBE().mCompositionInfo) {
1468 compositionInfo.hwc.hwcLayer = nullptr;
1469 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001470}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001471
David Sodmanfa9b2af2017-12-24 13:28:59 -08001472
1473bool SurfaceFlinger::handleMessageInvalidate() {
1474 ATRACE_CALL();
1475 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001476}
1477
David Sodman79bba0e2018-08-05 18:07:49 -07001478void SurfaceFlinger::calculateWorkingSet() {
1479 ATRACE_CALL();
1480 ALOGV(__FUNCTION__);
1481
David Sodman79bba0e2018-08-05 18:07:49 -07001482 // build the h/w work list
1483 if (CC_UNLIKELY(mGeometryInvalid)) {
1484 mGeometryInvalid = false;
1485 for (const auto& [token, display] : mDisplays) {
1486 const auto displayId = display->getId();
1487 if (displayId >= 0) {
1488 const Vector<sp<Layer>>& currentLayers(
1489 display->getVisibleLayersSortedByZ());
1490 for (size_t i = 0; i < currentLayers.size(); i++) {
1491 const auto& layer = currentLayers[i];
1492
1493 if (!layer->hasHwcLayer(displayId)) {
1494 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1495 layer->forceClientComposition(displayId);
1496 continue;
1497 }
1498 }
1499
1500 layer->setGeometry(display, i);
1501 if (mDebugDisableHWC || mDebugRegion) {
1502 layer->forceClientComposition(displayId);
1503 }
1504 }
1505 }
1506 }
1507 }
1508
1509 // Set the per-frame data
1510 for (const auto& [token, display] : mDisplays) {
1511 const auto displayId = display->getId();
1512 if (displayId < 0) {
1513 continue;
1514 }
1515
1516 if (mDrawingState.colorMatrixChanged) {
1517 display->setColorTransform(mDrawingState.colorMatrix);
1518 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1519 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1520 "display %d: %d", displayId, result);
1521 }
1522 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1523 if (layer->isHdrY410()) {
1524 layer->forceClientComposition(displayId);
1525 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1526 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1527 !display->hasHDR10Support()) {
1528 layer->forceClientComposition(displayId);
1529 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1530 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1531 !display->hasHLGSupport()) {
1532 layer->forceClientComposition(displayId);
1533 }
1534
1535 if (layer->getForceClientComposition(displayId)) {
1536 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1537 layer->setCompositionType(displayId, HWC2::Composition::Client);
1538 continue;
1539 }
1540
1541 layer->setPerFrameData(display);
1542 }
1543
1544 if (hasWideColorDisplay) {
1545 ColorMode colorMode;
1546 Dataspace dataSpace;
1547 RenderIntent renderIntent;
1548 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1549 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1550 }
1551 }
1552
1553 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001554 getBE().mCompositionInfo.clear();
1555
1556 for (const auto& [token, display] : mDisplays) {
1557 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1558 auto displayId = display->getId();
1559 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1560 if (!layer->setHwcLayer(displayId)) {
1561 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1562 }
1563 getBE().mCompositionInfo.push_back(layer->getBE().compositionInfo);
1564 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1565 }
1566 }
David Sodman79bba0e2018-08-05 18:07:49 -07001567}
1568
David Sodmanfa9b2af2017-12-24 13:28:59 -08001569void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001570{
1571 // is debugging enabled
1572 if (CC_LIKELY(!mDebugRegion))
1573 return;
1574
David Sodmanfa9b2af2017-12-24 13:28:59 -08001575 if (display->isPoweredOn()) {
1576 // transform the dirty region into this screen's coordinate space
1577 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1578 if (!dirtyRegion.isEmpty()) {
1579 // redraw the whole screen
1580 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001581
David Sodmanfa9b2af2017-12-24 13:28:59 -08001582 // and draw the dirty region
1583 const int32_t height = display->getHeight();
1584 auto& engine(getRenderEngine());
1585 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001586
David Sodmanfa9b2af2017-12-24 13:28:59 -08001587 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001588 }
1589 }
1590
David Sodmanfa9b2af2017-12-24 13:28:59 -08001591 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001592
1593 if (mDebugRegion > 1) {
1594 usleep(mDebugRegion * 1000);
1595 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001596
David Sodmanfa9b2af2017-12-24 13:28:59 -08001597 if (display->isPoweredOn()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001598 status_t result = display->prepareFrame(*getBE().mHwc);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001599 ALOGE_IF(result != NO_ERROR,
1600 "prepareFrame for display %d failed:"
1601 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001602 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001603 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001604}
1605
Adrian Roos1e1a1282017-11-01 19:05:31 +01001606void SurfaceFlinger::doTracing(const char* where) {
1607 ATRACE_CALL();
1608 ATRACE_NAME(where);
1609 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001610 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001611 }
1612}
1613
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001614void SurfaceFlinger::logLayerStats() {
1615 ATRACE_CALL();
1616 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001617 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001618 if (display->isPrimary()) {
1619 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001620 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001621 }
1622 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001623
1624 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001625 }
1626}
1627
David Sodman2b406362017-12-15 13:33:47 -08001628void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001629{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001630 ATRACE_CALL();
1631 ALOGV("preComposition");
1632
David Sodman2b406362017-12-15 13:33:47 -08001633 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1634
Mathias Agopiancd60f992012-08-16 16:28:27 -07001635 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001636 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001637 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001638 needExtraInvalidate = true;
1639 }
Robert Carr2047fae2016-11-28 14:09:09 -08001640 });
1641
Mathias Agopiancd60f992012-08-16 16:28:27 -07001642 if (needExtraInvalidate) {
1643 signalLayerUpdate();
1644 }
1645}
1646
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001647void SurfaceFlinger::updateCompositorTiming(
1648 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1649 std::shared_ptr<FenceTime>& presentFenceTime) {
1650 // Update queue of past composite+present times and determine the
1651 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001652 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001653 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001654 while (!getBE().mCompositePresentTimes.empty()) {
1655 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001656 // Cached values should have been updated before calling this method,
1657 // which helps avoid duplicate syscalls.
1658 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1659 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1660 break;
1661 }
1662 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001663 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001664 }
1665
1666 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001667 while (getBE().mCompositePresentTimes.size() > 16) {
1668 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001669 }
1670
Brian Andersond0010582017-03-07 13:20:31 -08001671 setCompositorTimingSnapped(
1672 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1673}
1674
1675void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1676 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001677 // Integer division and modulo round toward 0 not -inf, so we need to
1678 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001679 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001680 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1681 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1682
Brian Andersond0010582017-03-07 13:20:31 -08001683 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1684 if (idealLatency <= 0) {
1685 idealLatency = vsyncInterval;
1686 }
1687
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001688 // Snap the latency to a value that removes scheduling jitter from the
1689 // composition and present times, which often have >1ms of jitter.
1690 // Reducing jitter is important if an app attempts to extrapolate
1691 // something (such as user input) to an accurate diasplay time.
1692 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1693 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001694 nsecs_t bias = vsyncInterval / 2;
1695 int64_t extraVsyncs =
1696 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1697 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1698 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001699
David Sodman99974d22017-11-28 12:04:33 -08001700 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1701 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1702 getBE().mCompositorTiming.interval = vsyncInterval;
1703 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001704}
1705
David Sodman2b406362017-12-15 13:33:47 -08001706void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001707{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001708 ATRACE_CALL();
1709 ALOGV("postComposition");
1710
Brian Anderson3546a3f2016-07-14 11:51:14 -07001711 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001712 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001713 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001714 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001715 }
1716
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001717 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001718 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001719
David Sodman73beded2017-11-15 11:56:06 -08001720 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001721 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001722 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001723 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001724 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001725 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001726 } else {
1727 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1728 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001729
David Sodman73beded2017-11-15 11:56:06 -08001730 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001731 mPreviousPresentFence =
1732 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1733 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001734 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001735
Lloyd Pique41be5d22018-06-21 13:11:48 -07001736 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1737 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001738
David Sodman2b406362017-12-15 13:33:47 -08001739 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001740 // when we started doing work for this frame, but that should be okay
1741 // since updateCompositorTiming has snapping logic.
1742 updateCompositorTiming(
David Sodman2b406362017-12-15 13:33:47 -08001743 vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001744 CompositorTiming compositorTiming;
1745 {
David Sodman99974d22017-11-28 12:04:33 -08001746 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1747 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001748 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001749
Robert Carr2047fae2016-11-28 14:09:09 -08001750 mDrawingState.traverseInZOrder([&](Layer* layer) {
1751 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001752 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001753 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001754 recordBufferingStats(layer->getName().string(),
1755 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001756 }
Robert Carr2047fae2016-11-28 14:09:09 -08001757 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001758
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001759 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001760 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001761 enableHardwareVsync();
1762 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001763 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001764 }
1765 }
1766
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001767 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001768 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001769 enableHardwareVsync();
1770 }
1771 }
1772
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001773 if (mAnimCompositionPending) {
1774 mAnimCompositionPending = false;
1775
Brian Anderson4e606e32017-03-16 15:34:57 -07001776 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001777 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001778 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001779 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001780 // The HWC doesn't support present fences, so use the refresh
1781 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001782 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001783 mAnimFrameTracker.setActualPresentTime(presentTime);
1784 }
1785 mAnimFrameTracker.advanceFrame();
1786 }
Dan Stozab90cf072015-03-05 11:05:59 -08001787
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001788 mTimeStats.incrementTotalFrames();
1789 if (mHadClientComposition) {
1790 mTimeStats.incrementClientCompositionFrames();
1791 }
1792
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001793 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001794 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001795 return;
1796 }
1797
1798 nsecs_t currentTime = systemTime();
1799 if (mHasPoweredOff) {
1800 mHasPoweredOff = false;
1801 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001802 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001803 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001804 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1805 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001806 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001807 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001808 }
David Sodman4a36e932017-11-07 14:29:47 -08001809 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001810 }
David Sodman4a36e932017-11-07 14:29:47 -08001811 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001812
1813 {
1814 std::lock_guard lock(mTexturePoolMutex);
1815 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1816 if (refillCount > 0) {
1817 const size_t offset = mTexturePool.size();
1818 mTexturePool.resize(mTexturePoolSize);
1819 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1820 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1821 }
1822 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001823}
1824
1825void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001826 ATRACE_CALL();
1827 ALOGV("rebuildLayerStacks");
1828
Mathias Agopiancd60f992012-08-16 16:28:27 -07001829 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001830 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001831 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001832 mVisibleRegionsDirty = false;
1833 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001834
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001835 for (const auto& pair : mDisplays) {
1836 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001837 Region opaqueRegion;
1838 Region dirtyRegion;
1839 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001840 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001841 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001842 const Rect bounds = display->getBounds();
1843 if (display->isPoweredOn()) {
1844 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001845
Jeff Sharkey76488112017-02-27 14:15:18 -07001846 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001847 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001848 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001849 Region drawRegion(tr.transform(
1850 layer->visibleNonTransparentRegion));
1851 drawRegion.andSelf(bounds);
1852 if (!drawRegion.isEmpty()) {
1853 layersSortedByZ.add(layer);
1854 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001855 // Clear out the HWC layer if this layer was
1856 // previously visible, but no longer is
1857 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001858 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001859 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001860 // WM changes display->layerStack upon sleep/awake.
1861 // Here we make sure we delete the HWC layers even if
1862 // WM changed their layer stack.
1863 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001864 }
1865
1866 // If a layer is not going to get a release fence because
1867 // it is invisible, but it is also going to release its
1868 // old buffer, add it to the list of layers needing
1869 // fences.
1870 if (hwcLayerDestroyed) {
1871 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1872 mLayersWithQueuedFrames.cend(), layer);
1873 if (found != mLayersWithQueuedFrames.cend()) {
1874 layersNeedingFences.add(layer);
1875 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001876 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001877 });
1878 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001879 display->setVisibleLayersSortedByZ(layersSortedByZ);
1880 display->setLayersNeedingFences(layersNeedingFences);
1881 display->undefinedRegion.set(bounds);
1882 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1883 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001884 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001885 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001886}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001887
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001888// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001889// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001890// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001891// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001892// The returned HDR data space is one of
1893// - Dataspace::UNKNOWN
1894// - Dataspace::BT2020_HLG
1895// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001896Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1897 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001898 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001899 *outHdrDataSpace = Dataspace::UNKNOWN;
1900
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001901 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001902 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001903 case Dataspace::V0_SCRGB:
1904 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001905 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001906 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001907 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001908 case Dataspace::BT2020_PQ:
1909 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001910 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001911 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001912 case Dataspace::BT2020_HLG:
1913 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001914 // When there's mixed PQ content and HLG content, we set the HDR
1915 // data space to be BT2020_PQ and convert HLG to PQ.
1916 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1917 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001918 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001919 break;
1920 default:
1921 break;
1922 }
Romain Guy54f154a2017-10-24 21:40:32 +01001923 }
1924
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001925 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001926}
1927
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001928// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001929void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1930 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001931 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1932 *outMode = ColorMode::NATIVE;
1933 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001934 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001935 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001936 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001937
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001938 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001939 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001940
Peiyong Lindfde5112018-06-05 10:58:41 -07001941 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001942 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001943 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001944 if (isHdr) {
1945 bestDataSpace = hdrDataSpace;
1946 }
1947
Chia-I Wu0d711262018-05-21 15:19:35 -07001948 RenderIntent intent;
1949 switch (mDisplayColorSetting) {
1950 case DisplayColorSetting::MANAGED:
1951 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001952 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001953 break;
1954 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001955 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001956 break;
1957 default: // vendor display color setting
1958 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1959 break;
1960 }
Chia-I Wube02ec02018-05-18 10:59:36 -07001961
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001962 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001963}
1964
David Sodmanfa9b2af2017-12-24 13:28:59 -08001965void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08001966{
David Sodmanfa9b2af2017-12-24 13:28:59 -08001967 bool dirty = !display->getDirtyRegion(false).isEmpty();
1968 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
1969 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08001970
David Sodmanfa9b2af2017-12-24 13:28:59 -08001971 // If nothing has changed (!dirty), don't recompose.
1972 // If something changed, but we don't currently have any visible layers,
1973 // and didn't when we last did a composition, then skip it this time.
1974 // The second rule does two things:
1975 // - When all layers are removed from a display, we'll emit one black
1976 // frame, then nothing more until we get new layers.
1977 // - When a display is created with a private layer stack, we won't
1978 // emit any black frames until a layer is added to the layer stack.
1979 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08001980
David Sodmanfa9b2af2017-12-24 13:28:59 -08001981 ALOGV_IF(displayDevice->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1982 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1983 mustRecompose ? "doing" : "skipping",
1984 dirty ? "+" : "-",
1985 empty ? "+" : "-",
1986 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08001987
David Sodmanfa9b2af2017-12-24 13:28:59 -08001988 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08001989
David Sodmanfa9b2af2017-12-24 13:28:59 -08001990 if (mustRecompose) {
1991 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08001992 }
1993}
1994
David Sodmanfa9b2af2017-12-24 13:28:59 -08001995void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08001996{
David Sodmanfa9b2af2017-12-24 13:28:59 -08001997 if (!display->isPoweredOn()) {
1998 return;
David Sodman2b406362017-12-15 13:33:47 -08001999 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002000
2001 status_t result = display->prepareFrame(*getBE().mHwc);
2002 ALOGE_IF(result != NO_ERROR,
2003 "prepareFrame for display %d failed:"
2004 " %d (%s)",
2005 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002006}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002007
David Sodmanfa9b2af2017-12-24 13:28:59 -08002008void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002009 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002010 ALOGV("doComposition");
2011
David Sodmanfa9b2af2017-12-24 13:28:59 -08002012 if (display->isPoweredOn()) {
2013 // transform the dirty region into this screen's coordinate space
2014 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002015
David Sodmanfa9b2af2017-12-24 13:28:59 -08002016 // repaint the framebuffer (if needed)
2017 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002018
David Sodmanfa9b2af2017-12-24 13:28:59 -08002019 display->dirtyRegion.clear();
2020 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002021 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002022 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002023}
2024
David Sodmanfa9b2af2017-12-24 13:28:59 -08002025void SurfaceFlinger::postFrame()
2026{
2027 // |mStateLock| not needed as we are on the main thread
2028 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2029 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2030 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2031 logFrameStats();
2032 }
2033 }
2034}
2035
2036void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002037{
Mathias Agopian841cde52012-03-01 15:44:37 -08002038 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002039 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002040
David Sodmanfa9b2af2017-12-24 13:28:59 -08002041 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002042
David Sodmanfa9b2af2017-12-24 13:28:59 -08002043 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002044 const auto displayId = display->getId();
2045 if (displayId >= 0) {
2046 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002047 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002048 display->onSwapBuffersCompleted();
2049 display->makeCurrent();
2050 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002051 sp<Fence> releaseFence = Fence::NO_FENCE;
2052
Chia-I Wu7b549592017-11-15 09:14:57 -08002053 // The layer buffer from the previous frame (if any) is released
2054 // by HWC only when the release fence from this frame (if any) is
2055 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002056 auto hwcLayer = layer->getHwcLayer(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002057 if (displayId >= 0) {
2058 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
2059 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002060
2061 // If the layer was client composited in the previous frame, we
2062 // need to merge with the previous client target acquire fence.
2063 // Since we do not track that, always merge with the current
2064 // client target acquire fence when it is available, even though
2065 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002066 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002067 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002068 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002069 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002070
David Sodmanb8af7922017-12-21 15:17:55 -08002071 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002072 }
Chia-I Wu83806892017-11-16 10:50:20 -08002073
2074 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002075 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002076 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002077 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002078 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002079 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002080 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002081 }
2082 }
2083
Dominik Laskowski7e045462018-05-30 13:02:02 -07002084 if (displayId >= 0) {
2085 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002086 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002087 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002088}
2089
Mathias Agopian87baae12012-07-31 12:38:26 -07002090void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002091{
Mathias Agopian841cde52012-03-01 15:44:37 -08002092 ATRACE_CALL();
2093
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002094 // here we keep a copy of the drawing state (that is the state that's
2095 // going to be overwritten by handleTransactionLocked()) outside of
2096 // mStateLock so that the side-effects of the State assignment
2097 // don't happen with mStateLock held (which can cause deadlocks).
2098 State drawingState(mDrawingState);
2099
Mathias Agopianca4d3602011-05-19 15:38:14 -07002100 Mutex::Autolock _l(mStateLock);
2101 const nsecs_t now = systemTime();
2102 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002103
Mathias Agopianca4d3602011-05-19 15:38:14 -07002104 // Here we're guaranteed that some transaction flags are set
2105 // so we can call handleTransactionLocked() unconditionally.
2106 // We call getTransactionFlags(), which will also clear the flags,
2107 // with mStateLock held to guarantee that mCurrentState won't change
2108 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002109
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002110 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002111 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002112 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002113
Mathias Agopianca4d3602011-05-19 15:38:14 -07002114 mLastTransactionTime = systemTime() - now;
2115 mDebugInTransaction = 0;
2116 invalidateHwcGeometry();
2117 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002118}
2119
Dominik Laskowski7e045462018-05-30 13:02:02 -07002120DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002121 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002122 // Figure out whether the event is for the primary display or an
2123 // external display by matching the Hwc display id against one for a
2124 // connected display. If we did not find a match, we then check what
2125 // displays are not already connected to determine the type. If we don't
2126 // have a connected primary display, we assume the new display is meant to
2127 // be the primary display, and then if we don't have an external display,
2128 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002129 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2130 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002131 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002132 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002133 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002134 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002135 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002136 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002137 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002138 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002139 return DisplayDevice::DISPLAY_EXTERNAL;
2140 }
2141
2142 return DisplayDevice::DISPLAY_ID_INVALID;
2143}
2144
Lloyd Piqueba04e622017-12-14 17:11:26 -08002145void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2146 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002147 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002148 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002149 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002150 continue;
2151 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002152
2153 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2154 ALOGE("External displays are not supported by the vr hardware composer.");
2155 continue;
2156 }
2157
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002158 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002159 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002160 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002161 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002162 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002163
2164 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002165 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002166 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002167 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002168 DisplayDeviceState info;
2169 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002170 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2171 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002172 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002173 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002174 mInterceptor->saveDisplayCreation(info);
2175 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002176 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002177 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002178
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002179 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002180 if (idx >= 0) {
2181 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002182 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002183 mCurrentState.displays.removeItemsAt(idx);
2184 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002185 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002186 }
2187
2188 processDisplayChangesLocked();
2189 }
2190
2191 mPendingHotplugEvents.clear();
2192}
2193
Lloyd Pique99d3da52018-01-22 17:48:03 -08002194sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002195 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002196 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002197 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002198 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002199 HdrCapabilities hdrCapabilities;
2200 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002201
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002202 if (hasWideColorDisplay && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002203 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002204 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002205 if (isWideColorMode(colorMode)) {
2206 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002207 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002208
Dominik Laskowski7e045462018-05-30 13:02:02 -07002209 std::vector<RenderIntent> renderIntents =
2210 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002211 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002212 }
tangrobin6753a022018-08-10 10:58:54 +08002213 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002214
tangrobin6753a022018-08-10 10:58:54 +08002215 if (displayId >= 0) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002216 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2217 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2218 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002219
2220 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2221 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2222
2223 /*
2224 * Create our display's surface
2225 */
2226 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2227 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002228 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002229 renderSurface->setNativeWindow(nativeWindow.get());
2230 const int displayWidth = renderSurface->queryWidth();
2231 const int displayHeight = renderSurface->queryHeight();
2232
2233 // Make sure that composition can never be stalled by a virtual display
2234 // consumer that isn't processing buffers fast enough. We have to do this
2235 // in two places:
2236 // * Here, in case the display is composed entirely by HWC.
2237 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2238 // window's swap interval in eglMakeCurrent, so they'll override the
2239 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002240 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002241 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2242 }
2243
2244 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002245 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002246
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002247 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002248 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2249 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2250 displayHeight, hasWideColorGamut, hdrCapabilities,
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002251 supportedPerFrameMetadata, hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002252
2253 if (maxFrameBufferAcquiredBuffers >= 3) {
2254 nativeWindowSurface->preallocateBuffers();
2255 }
2256
2257 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002258 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2259 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002260 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002261 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002262 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002263 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002264 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002265 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002266 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002267 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002268 display->setLayerStack(state.layerStack);
2269 display->setProjection(state.orientation, state.viewport, state.frame);
2270 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002271
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002272 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002273}
2274
Lloyd Pique347200f2017-12-14 17:00:15 -08002275void SurfaceFlinger::processDisplayChangesLocked() {
2276 // here we take advantage of Vector's copy-on-write semantics to
2277 // improve performance by skipping the transaction entirely when
2278 // know that the lists are identical
2279 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2280 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2281 if (!curr.isIdenticalTo(draw)) {
2282 mVisibleRegionsDirty = true;
2283 const size_t cc = curr.size();
2284 size_t dc = draw.size();
2285
2286 // find the displays that were removed
2287 // (ie: in drawing state but not in current state)
2288 // also handle displays that changed
2289 // (ie: displays that are in both lists)
2290 for (size_t i = 0; i < dc;) {
2291 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2292 if (j < 0) {
2293 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002294 // Call makeCurrent() on the primary display so we can
2295 // be sure that nothing associated with this display
2296 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002297 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2298 defaultDisplay->makeCurrent();
2299 }
2300 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2301 display->disconnect(getHwComposer());
2302 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002303 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2304 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2305 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2306 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2307 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002308 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002309 } else {
2310 // this display is in both lists. see if something changed.
2311 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002312 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002313 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2314 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2315 if (state_binder != draw_binder) {
2316 // changing the surface is like destroying and
2317 // recreating the DisplayDevice, so we just remove it
2318 // from the drawing state, so that it get re-added
2319 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002320 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2321 display->disconnect(getHwComposer());
2322 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002323 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002324 mDrawingState.displays.removeItemsAt(i);
2325 dc--;
2326 // at this point we must loop to the next item
2327 continue;
2328 }
2329
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002330 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002331 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002332 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002333 }
2334 if ((state.orientation != draw[i].orientation) ||
2335 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002336 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002337 }
2338 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002339 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002340 }
2341 }
2342 }
2343 ++i;
2344 }
2345
2346 // find displays that were added
2347 // (ie: in current state but not in drawing state)
2348 for (size_t i = 0; i < cc; i++) {
2349 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2350 const DisplayDeviceState& state(curr[i]);
2351
2352 sp<DisplaySurface> dispSurface;
2353 sp<IGraphicBufferProducer> producer;
2354 sp<IGraphicBufferProducer> bqProducer;
2355 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002356 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002357
Dominik Laskowski7e045462018-05-30 13:02:02 -07002358 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002359 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002360 // Virtual displays without a surface are dormant:
2361 // they have external state (layer stack, projection,
2362 // etc.) but no internal state (i.e. a DisplayDevice).
2363 if (state.surface != nullptr) {
2364 // Allow VR composer to use virtual displays.
2365 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2366 int width = 0;
2367 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2368 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2369 int height = 0;
2370 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2371 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2372 int intFormat = 0;
2373 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2374 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002375 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002376
Dominik Laskowski7e045462018-05-30 13:02:02 -07002377 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2378 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002379 }
2380
2381 // TODO: Plumb requested format back up to consumer
2382
2383 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002384 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002385 bqProducer, bqConsumer,
2386 state.displayName);
2387
2388 dispSurface = vds;
2389 producer = vds;
2390 }
2391 } else {
2392 ALOGE_IF(state.surface != nullptr,
2393 "adding a supported display, but rendering "
2394 "surface is provided (%p), ignoring it",
2395 state.surface.get());
2396
Dominik Laskowski7e045462018-05-30 13:02:02 -07002397 displayId = state.type;
2398 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002399 producer = bqProducer;
2400 }
2401
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002402 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002403 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002404 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002405 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002406 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002407 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002408 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2409 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2410 true);
2411 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2412 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2413 true);
2414 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002415 }
2416 }
2417 }
2418 }
2419 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002420
2421 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002422}
2423
Mathias Agopian87baae12012-07-31 12:38:26 -07002424void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002425{
Dan Stoza7dde5992015-05-22 09:51:44 -07002426 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002427 mCurrentState.traverseInZOrder([](Layer* layer) {
2428 layer->notifyAvailableFrames();
2429 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002430
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002431 /*
2432 * Traversal of the children
2433 * (perform the transaction for each of them if needed)
2434 */
2435
Mathias Agopian3559b072012-08-15 13:46:03 -07002436 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002437 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002438 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002439 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002440
2441 const uint32_t flags = layer->doTransaction(0);
2442 if (flags & Layer::eVisibleRegion)
2443 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002444 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002445 }
2446
2447 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002448 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002449 */
2450
Mathias Agopiane57f2922012-08-09 16:29:12 -07002451 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002452 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002453 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002454 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002455
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002456 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002457 // The transform hint might have changed for some layers
2458 // (either because a display has changed, or because a layer
2459 // as changed).
2460 //
2461 // Walk through all the layers in currentLayers,
2462 // and update their transform hint.
2463 //
2464 // If a layer is visible only on a single display, then that
2465 // display is used to calculate the hint, otherwise we use the
2466 // default display.
2467 //
2468 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2469 // the hint is set before we acquire a buffer from the surface texture.
2470 //
2471 // NOTE: layer transactions have taken place already, so we use their
2472 // drawing state. However, SurfaceFlinger's own transaction has not
2473 // happened yet, so we must use the current state layer list
2474 // (soon to become the drawing state list).
2475 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002476 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002477 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002478 bool first = true;
2479 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002480 // NOTE: we rely on the fact that layers are sorted by
2481 // layerStack first (so we don't have to traverse the list
2482 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002483 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002484 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002485 currentlayerStack = layerStack;
2486 // figure out if this layerstack is mirrored
2487 // (more than one display) if so, pick the default display,
2488 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002489 hintDisplay = nullptr;
2490 for (const auto& [token, display] : mDisplays) {
2491 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2492 if (hintDisplay) {
2493 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002494 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002495 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002496 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002497 }
2498 }
2499 }
2500 }
Chet Haase91d25932013-04-11 15:24:55 -07002501
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002502 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002503 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2504 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002505
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002506 // could be null when this layer is using a layerStack
2507 // that is not visible on any display. Also can occur at
2508 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002509 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002510 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002511
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002512 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002513 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002514 if (hintDisplay) {
2515 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002516 }
Robert Carr2047fae2016-11-28 14:09:09 -08002517
2518 first = false;
2519 });
Mathias Agopian84300952012-11-21 16:02:13 -08002520 }
2521
2522
Mathias Agopian3559b072012-08-15 13:46:03 -07002523 /*
2524 * Perform our own transaction if needed
2525 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002526
2527 if (mLayersAdded) {
2528 mLayersAdded = false;
2529 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002530 mVisibleRegionsDirty = true;
2531 }
2532
2533 // some layers might have been removed, so
2534 // we need to update the regions they're exposing.
2535 if (mLayersRemoved) {
2536 mLayersRemoved = false;
2537 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002538 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002539 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002540 // this layer is not visible anymore
2541 // TODO: we could traverse the tree from front to back and
2542 // compute the actual visible region
2543 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002544 Region visibleReg;
2545 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002546 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002547 }
Robert Carr2047fae2016-11-28 14:09:09 -08002548 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002549 }
2550
2551 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002552
2553 updateCursorAsync();
2554}
2555
2556void SurfaceFlinger::updateCursorAsync()
2557{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002558 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002559 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002560 continue;
2561 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002562
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002563 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2564 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002565 }
2566 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002567}
2568
2569void SurfaceFlinger::commitTransaction()
2570{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002571 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002572 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002573 for (const auto& l : mLayersPendingRemoval) {
2574 recordBufferingStats(l->getName().string(),
2575 l->getOccupancyHistory(true));
2576 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002577 }
2578 mLayersPendingRemoval.clear();
2579 }
2580
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002581 // If this transaction is part of a window animation then the next frame
2582 // we composite should be considered an animation as well.
2583 mAnimCompositionPending = mAnimTransactionPending;
2584
Mathias Agopian4fec8732012-06-29 14:12:52 -07002585 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002586 // clear the "changed" flags in current state
2587 mCurrentState.colorMatrixChanged = false;
2588
Robert Carr1f0a16a2016-10-24 16:27:39 -07002589 mDrawingState.traverseInZOrder([](Layer* layer) {
2590 layer->commitChildList();
2591 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002592 mTransactionPending = false;
2593 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002594 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002595}
2596
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002597void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2598 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002599 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002600 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002601
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002602 Region aboveOpaqueLayers;
2603 Region aboveCoveredLayers;
2604 Region dirty;
2605
Mathias Agopian87baae12012-07-31 12:38:26 -07002606 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002607
Robert Carr2047fae2016-11-28 14:09:09 -08002608 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002609 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002610 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002611
Jesse Hall01e29052013-02-19 16:13:35 -08002612 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002613 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002614 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002615 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002616
Mathias Agopianab028732010-03-16 16:41:46 -07002617 /*
2618 * opaqueRegion: area of a surface that is fully opaque.
2619 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002620 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002621
2622 /*
2623 * visibleRegion: area of a surface that is visible on screen
2624 * and not fully transparent. This is essentially the layer's
2625 * footprint minus the opaque regions above it.
2626 * Areas covered by a translucent surface are considered visible.
2627 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002628 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002629
2630 /*
2631 * coveredRegion: area of a surface that is covered by all
2632 * visible regions above it (which includes the translucent areas).
2633 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002634 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002635
Jesse Halla8026d22012-09-25 13:25:04 -07002636 /*
2637 * transparentRegion: area of a surface that is hinted to be completely
2638 * transparent. This is only used to tell when the layer has no visible
2639 * non-transparent regions and can be removed from the layer list. It
2640 * does not affect the visibleRegion of this layer or any layers
2641 * beneath it. The hint may not be correct if apps don't respect the
2642 * SurfaceView restrictions (which, sadly, some don't).
2643 */
2644 Region transparentRegion;
2645
Mathias Agopianab028732010-03-16 16:41:46 -07002646
2647 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002648 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002649 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002650 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002651 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002652 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002653 if (!visibleRegion.isEmpty()) {
2654 // Remove the transparent area from the visible region
2655 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002656 if (tr.preserveRects()) {
2657 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002658 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002659 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002660 // transformation too complex, can't do the
2661 // transparent region optimization.
2662 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002663 }
Mathias Agopianab028732010-03-16 16:41:46 -07002664 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002665
Mathias Agopianab028732010-03-16 16:41:46 -07002666 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002667 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002668 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002669 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002670 // the opaque region is the layer's footprint
2671 opaqueRegion = visibleRegion;
2672 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002673 }
2674 }
2675
Robert Carre5f4f692018-01-12 13:12:28 -08002676 if (visibleRegion.isEmpty()) {
2677 layer->clearVisibilityRegions();
2678 return;
2679 }
2680
Mathias Agopianab028732010-03-16 16:41:46 -07002681 // Clip the covered region to the visible region
2682 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2683
2684 // Update aboveCoveredLayers for next (lower) layer
2685 aboveCoveredLayers.orSelf(visibleRegion);
2686
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002687 // subtract the opaque region covered by the layers above us
2688 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002689
2690 // compute this layer's dirty region
2691 if (layer->contentDirty) {
2692 // we need to invalidate the whole region
2693 dirty = visibleRegion;
2694 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002695 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002696 layer->contentDirty = false;
2697 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002698 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002699 * the exposed region consists of two components:
2700 * 1) what's VISIBLE now and was COVERED before
2701 * 2) what's EXPOSED now less what was EXPOSED before
2702 *
2703 * note that (1) is conservative, we start with the whole
2704 * visible region but only keep what used to be covered by
2705 * something -- which mean it may have been exposed.
2706 *
2707 * (2) handles areas that were not covered by anything but got
2708 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002709 */
Mathias Agopianab028732010-03-16 16:41:46 -07002710 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002711 const Region oldVisibleRegion = layer->visibleRegion;
2712 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002713 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2714 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002715 }
2716 dirty.subtractSelf(aboveOpaqueLayers);
2717
2718 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002719 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002720
Mathias Agopianab028732010-03-16 16:41:46 -07002721 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002722 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002723
Jesse Halla8026d22012-09-25 13:25:04 -07002724 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002725 layer->setVisibleRegion(visibleRegion);
2726 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002727 layer->setVisibleNonTransparentRegion(
2728 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002729 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002730
Mathias Agopian87baae12012-07-31 12:38:26 -07002731 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002732}
2733
Chia-I Wuab0c3192017-08-01 11:29:00 -07002734void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002735 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002736 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2737 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002738 }
2739 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002740}
2741
Dan Stoza6b9454d2014-11-07 16:00:59 -08002742bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002743{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002744 ALOGV("handlePageFlip");
2745
Brian Andersond6927fb2016-07-23 23:37:30 -07002746 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002747
Mathias Agopian4fec8732012-06-29 14:12:52 -07002748 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002749 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002750 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002751
2752 // Store the set of layers that need updates. This set must not change as
2753 // buffers are being latched, as this could result in a deadlock.
2754 // Example: Two producers share the same command stream and:
2755 // 1.) Layer 0 is latched
2756 // 2.) Layer 0 gets a new frame
2757 // 2.) Layer 1 gets a new frame
2758 // 3.) Layer 1 is latched.
2759 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2760 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002761 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002762 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002763 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07002764 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002765 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002766 } else {
2767 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002768 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002769 } else {
2770 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002771 }
Robert Carr2047fae2016-11-28 14:09:09 -08002772 });
2773
Dan Stoza9e56aa02015-11-02 13:00:03 -08002774 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002775 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002776 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002777 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002778 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002779 newDataLatched = true;
2780 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002781 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002782
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002783 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002784
2785 // If we will need to wake up at some time in the future to deal with a
2786 // queued frame that shouldn't be displayed during this vsync period, wake
2787 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002788 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002789 signalLayerUpdate();
2790 }
2791
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002792 // enter boot animation on first buffer latch
2793 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2794 ALOGI("Enter boot animation");
2795 mBootStage = BootStage::BOOTANIMATION;
2796 }
2797
Dan Stoza6b9454d2014-11-07 16:00:59 -08002798 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002799 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002800}
2801
Mathias Agopianad456f92011-01-13 17:53:01 -08002802void SurfaceFlinger::invalidateHwcGeometry()
2803{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002804 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002805}
2806
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002807void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2808 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002809 // We only need to actually compose the display if:
2810 // 1) It is being handled by hardware composer, which may need this to
2811 // keep its virtual display state machine in sync, or
2812 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002813 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002814 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002815 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002816 return;
2817 }
2818
Dan Stoza9e56aa02015-11-02 13:00:03 -08002819 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002820 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002821
2822 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002823 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002824}
2825
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002826bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002827 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002828
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002829 const Region bounds(display->bounds());
2830 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002831 const auto displayId = display->getId();
2832 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002833 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002834
Chia-I Wu8e50e692018-05-04 10:12:37 -07002835 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002836 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002837
Dan Stoza9e56aa02015-11-02 13:00:03 -08002838 if (hasClientComposition) {
2839 ALOGV("hasClientComposition");
2840
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002841 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002842 if (display->hasWideColorGamut()) {
2843 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002844 }
2845 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002846 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002847 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002848
Dominik Laskowski7e045462018-05-30 13:02:02 -07002849 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002850 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2851 HWC2::Capability::SkipClientColorTransform);
2852
Chia-I Wud49d6692018-06-27 07:17:41 +08002853 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002854 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2855 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08002856 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002857 }
2858
Chia-I Wud49d6692018-06-27 07:17:41 +08002859 // The current enhanced saturation matrix is designed to enhance Display P3,
2860 // thus we only apply this matrix when the render intent is not colorimetric
2861 // and the output color space is Display P3.
2862 needsEnhancedColorMatrix =
2863 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2864 outputDataspace == Dataspace::DISPLAY_P3);
2865 if (needsEnhancedColorMatrix) {
2866 colorMatrix *= mEnhancedSaturationMatrix;
2867 }
2868
2869 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002870
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002871 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002872 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002873 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002874 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002875
2876 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002877 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
2878 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
2879 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07002880 }
2881 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002882 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002883
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002884 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002885 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002886 // when using overlays, we assume a fully transparent framebuffer
2887 // NOTE: we could reduce how much we need to clear, for instance
2888 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002889 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002890 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002891 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002892 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002893 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002894 // we're left with the letterbox region
2895 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002896 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07002897
2898 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002899 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07002900
Mathias Agopianb9494d52012-04-18 02:28:45 -07002901 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002902 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002903 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002904 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002905 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002906 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002907
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002908 if (!display->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002909 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002910 // scissor on the main display. It should never be needed
2911 // anyways (though in theory it could since the API allows it).
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002912 const Rect& bounds = display->getBounds();
2913 const Rect& scissor = display->getScissor();
Mathias Agopianf45c5102012-10-24 16:29:17 -07002914 if (scissor != bounds) {
2915 // scissor doesn't match the screen's dimensions, so we
2916 // need to clear everything outside of it and enable
2917 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002918
Mathias Agopianf45c5102012-10-24 16:29:17 -07002919 // enable scissor for this frame
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002920 const uint32_t height = display->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002921 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002922 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002923 }
2924 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002925 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002926
Mathias Agopian85d751c2012-08-29 16:59:24 -07002927 /*
2928 * and then, render the layers targeted at the framebuffer
2929 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002930
Dan Stoza9e56aa02015-11-02 13:00:03 -08002931 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07002932 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002933 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002934 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002935 const Region clip(bounds.intersect(
2936 displayTransform.transform(layer->visibleRegion)));
2937 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002938 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002939 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002940 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002941 case HWC2::Composition::Cursor:
2942 case HWC2::Composition::Device:
2943 case HWC2::Composition::Sideband:
2944 case HWC2::Composition::SolidColor: {
2945 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002946 if (layer->getClearClientTarget(displayId) && !firstLayer &&
Rajavenu Kyatham2eae6d32018-04-10 12:34:05 +05302947 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
2948 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002949 // never clear the very first layer since we're
2950 // guaranteed the FB is already cleared
2951 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002952 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002953 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002954 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002955 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002956 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002957 break;
2958 }
2959 default:
2960 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002961 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002962 } else {
2963 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002964 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002965 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002966 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002967
Chia-I Wud49d6692018-06-27 07:17:41 +08002968 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07002969 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002970 }
2971
Mathias Agopianf45c5102012-10-24 16:29:17 -07002972 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002973 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002974 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002975}
2976
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002977void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
2978 const Region& region) const {
2979 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002980 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002981 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002982}
2983
Dan Stoza7d89d062015-04-30 13:29:25 -07002984status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002985 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002986 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002987 const sp<Layer>& lbc,
2988 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002989{
Dan Stoza7d89d062015-04-30 13:29:25 -07002990 // add this layer to the current state list
2991 {
2992 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002993 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002994 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2995 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002996 return NO_MEMORY;
2997 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002998 if (parent == nullptr) {
2999 mCurrentState.layersSortedByZ.add(lbc);
3000 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003001 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003002 ALOGE("addClientLayer called with a removed parent");
3003 return NAME_NOT_FOUND;
3004 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003005 parent->addChild(lbc);
3006 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003007
Yiwei Zhang243b3782018-05-15 17:40:04 -07003008 if (gbc != nullptr) {
3009 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3010 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3011 mMaxGraphicBufferProducerListSize,
3012 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3013 mGraphicBufferProducerList.size(),
3014 mMaxGraphicBufferProducerListSize, mNumLayers);
3015 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003016 mLayersAdded = true;
3017 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003018 }
3019
Mathias Agopian96f08192010-06-02 23:28:45 -07003020 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003021 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003022
Dan Stoza7d89d062015-04-30 13:29:25 -07003023 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003024}
3025
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003026status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003027 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003028 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3029}
Robert Carr7f9b8992017-03-10 11:08:39 -08003030
chaviwca27f252018-02-06 16:46:39 -08003031status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3032 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003033 if (layer->isPendingRemoval()) {
3034 return NO_ERROR;
3035 }
3036
Robert Carr1f0a16a2016-10-24 16:27:39 -07003037 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003038 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003039 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003040 if (topLevelOnly) {
3041 return NO_ERROR;
3042 }
3043
Chia-I Wu98f1c102017-05-30 14:54:08 -07003044 sp<Layer> ancestor = p;
3045 while (ancestor->getParent() != nullptr) {
3046 ancestor = ancestor->getParent();
3047 }
3048 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3049 ALOGE("removeLayer called with a layer whose parent has been removed");
3050 return NAME_NOT_FOUND;
3051 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003052
3053 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003054 } else {
3055 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003056 }
3057
Robert Carr136e2f62017-02-08 17:54:29 -08003058 // As a matter of normal operation, the LayerCleaner will produce a second
3059 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3060 // so we will succeed in promoting it, but it's already been removed
3061 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3062 // otherwise something has gone wrong and we are leaking the layer.
3063 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003064 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3065 layer->getName().string(),
3066 (p != nullptr) ? p->getName().string() : "no-parent");
3067 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003068 } else if (index < 0) {
3069 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003070 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003071
Chia-I Wuc6657022017-08-15 11:18:17 -07003072 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003073 mLayersPendingRemoval.add(layer);
3074 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003075 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003076 setTransactionFlags(eTransactionNeeded);
3077 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003078}
3079
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003080uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003081 return android_atomic_release_load(&mTransactionFlags);
3082}
3083
Mathias Agopian3f844832013-08-07 21:24:32 -07003084uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003085 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3086}
3087
Mathias Agopian3f844832013-08-07 21:24:32 -07003088uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003089 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3090}
3091
3092uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3093 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003094 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003095 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003096 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003097 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003098 }
3099 return old;
3100}
3101
chaviwca27f252018-02-06 16:46:39 -08003102bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3103 for (const ComposerState& state : states) {
3104 // Here we need to check that the interface we're given is indeed
3105 // one of our own. A malicious client could give us a nullptr
3106 // IInterface, or one of its own or even one of our own but a
3107 // different type. All these situations would cause us to crash.
3108 if (state.client == nullptr) {
3109 return true;
3110 }
3111
3112 sp<IBinder> binder = IInterface::asBinder(state.client);
3113 if (binder == nullptr) {
3114 return true;
3115 }
3116
3117 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3118 return true;
3119 }
3120 }
3121 return false;
3122}
3123
Mathias Agopian8b33f032012-07-24 20:43:54 -07003124void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003125 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003126 const Vector<DisplayState>& displays,
3127 uint32_t flags)
3128{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003129 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003130 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003131 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003132
chaviwca27f252018-02-06 16:46:39 -08003133 if (containsAnyInvalidClientState(states)) {
3134 return;
3135 }
3136
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003137 if (flags & eAnimation) {
3138 // For window updates that are part of an animation we must wait for
3139 // previous animation "frames" to be handled.
3140 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003141 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003142 if (CC_UNLIKELY(err != NO_ERROR)) {
3143 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003144 // caller after a few seconds.
3145 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3146 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003147 mAnimTransactionPending = false;
3148 break;
3149 }
3150 }
3151 }
3152
chaviwca27f252018-02-06 16:46:39 -08003153 for (const DisplayState& display : displays) {
3154 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003155 }
3156
chaviwca27f252018-02-06 16:46:39 -08003157 for (const ComposerState& state : states) {
3158 transactionFlags |= setClientStateLocked(state);
3159 }
3160
3161 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3162 // as destroyed should only occur after setting all other states. This is to allow for a
3163 // child re-parent to happen before marking its original parent as destroyed (which would
3164 // then mark the child as destroyed).
3165 for (const ComposerState& state : states) {
3166 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003167 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003168
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003169 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3170 // anyway. This can be used as a flush mechanism for previous async transactions.
3171 // Empty animation transaction can be used to simulate back-pressure, so also force a
3172 // transaction for empty animation transactions.
3173 if (transactionFlags == 0 &&
3174 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003175 transactionFlags = eTransactionNeeded;
3176 }
3177
Mathias Agopian386aa982011-11-07 21:58:03 -08003178 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003179 if (mInterceptor->isEnabled()) {
3180 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003181 }
Irvel468051e2016-06-13 16:44:44 -07003182
Mathias Agopian386aa982011-11-07 21:58:03 -08003183 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003184 const auto start = (flags & eEarlyWakeup)
3185 ? VSyncModulator::TransactionStart::EARLY
3186 : VSyncModulator::TransactionStart::NORMAL;
3187 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003188
3189 // if this is a synchronous transaction, wait for it to take effect
3190 // before returning.
3191 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003192 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003193 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003194 if (flags & eAnimation) {
3195 mAnimTransactionPending = true;
3196 }
3197 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003198 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3199 if (CC_UNLIKELY(err != NO_ERROR)) {
3200 // just in case something goes wrong in SF, return to the
3201 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003202 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3203 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003204 break;
3205 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003206 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003207 }
3208}
3209
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003210uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3211 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3212 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003213
Mathias Agopiane57f2922012-08-09 16:29:12 -07003214 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003215 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3216
3217 const uint32_t what = s.what;
3218 if (what & DisplayState::eSurfaceChanged) {
3219 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3220 state.surface = s.surface;
3221 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003222 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003223 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003224 if (what & DisplayState::eLayerStackChanged) {
3225 if (state.layerStack != s.layerStack) {
3226 state.layerStack = s.layerStack;
3227 flags |= eDisplayTransactionNeeded;
3228 }
3229 }
3230 if (what & DisplayState::eDisplayProjectionChanged) {
3231 if (state.orientation != s.orientation) {
3232 state.orientation = s.orientation;
3233 flags |= eDisplayTransactionNeeded;
3234 }
3235 if (state.frame != s.frame) {
3236 state.frame = s.frame;
3237 flags |= eDisplayTransactionNeeded;
3238 }
3239 if (state.viewport != s.viewport) {
3240 state.viewport = s.viewport;
3241 flags |= eDisplayTransactionNeeded;
3242 }
3243 }
3244 if (what & DisplayState::eDisplaySizeChanged) {
3245 if (state.width != s.width) {
3246 state.width = s.width;
3247 flags |= eDisplayTransactionNeeded;
3248 }
3249 if (state.height != s.height) {
3250 state.height = s.height;
3251 flags |= eDisplayTransactionNeeded;
3252 }
3253 }
3254
Mathias Agopiane57f2922012-08-09 16:29:12 -07003255 return flags;
3256}
3257
Robert Carrd4ae7f32018-06-07 16:10:57 -07003258bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3259 IPCThreadState* ipc = IPCThreadState::self();
3260 const int pid = ipc->getCallingPid();
3261 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003262 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003263 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003264 return false;
3265 }
3266 return true;
3267}
3268
chaviwca27f252018-02-06 16:46:39 -08003269uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3270 const layer_state_t& s = composerState.state;
3271 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3272
Mathias Agopian13127d82013-03-05 17:47:11 -08003273 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003274 if (layer == nullptr) {
3275 return 0;
3276 }
3277
3278 if (layer->isPendingRemoval()) {
3279 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3280 return 0;
3281 }
3282
3283 uint32_t flags = 0;
3284
3285 const uint32_t what = s.what;
3286 bool geometryAppliesWithResize =
3287 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003288
3289 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3290 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003291 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003292 layer->pushPendingState();
3293 }
3294
chaviw8b3871a2017-11-01 17:41:01 -07003295 if (what & layer_state_t::ePositionChanged) {
3296 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3297 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003298 }
chaviw8b3871a2017-11-01 17:41:01 -07003299 }
3300 if (what & layer_state_t::eLayerChanged) {
3301 // NOTE: index needs to be calculated before we update the state
3302 const auto& p = layer->getParent();
3303 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003304 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003305 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003306 mCurrentState.layersSortedByZ.removeAt(idx);
3307 mCurrentState.layersSortedByZ.add(layer);
3308 // we need traversal (state changed)
3309 // AND transaction (list changed)
3310 flags |= eTransactionNeeded|eTraversalNeeded;
3311 }
chaviw8b3871a2017-11-01 17:41:01 -07003312 } else {
3313 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003314 flags |= eTransactionNeeded|eTraversalNeeded;
3315 }
3316 }
chaviw8b3871a2017-11-01 17:41:01 -07003317 }
3318 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003319 // NOTE: index needs to be calculated before we update the state
3320 const auto& p = layer->getParent();
3321 if (p == nullptr) {
3322 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3323 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3324 mCurrentState.layersSortedByZ.removeAt(idx);
3325 mCurrentState.layersSortedByZ.add(layer);
3326 // we need traversal (state changed)
3327 // AND transaction (list changed)
3328 flags |= eTransactionNeeded|eTraversalNeeded;
3329 }
3330 } else {
3331 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3332 flags |= eTransactionNeeded|eTraversalNeeded;
3333 }
chaviw8b3871a2017-11-01 17:41:01 -07003334 }
3335 }
3336 if (what & layer_state_t::eSizeChanged) {
3337 if (layer->setSize(s.w, s.h)) {
3338 flags |= eTraversalNeeded;
3339 }
3340 }
3341 if (what & layer_state_t::eAlphaChanged) {
3342 if (layer->setAlpha(s.alpha))
3343 flags |= eTraversalNeeded;
3344 }
3345 if (what & layer_state_t::eColorChanged) {
3346 if (layer->setColor(s.color))
3347 flags |= eTraversalNeeded;
3348 }
3349 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003350 // TODO: b/109894387
3351 //
3352 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3353 // rotation. To see the problem observe that if we have a square parent, and a child
3354 // of the same size, then we rotate the child 45 degrees around it's center, the child
3355 // must now be cropped to a non rectangular 8 sided region.
3356 //
3357 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3358 // private API, and the WindowManager only uses rotation in one case, which is on a top
3359 // level layer in which cropping is not an issue.
3360 //
3361 // However given that abuse of rotation matrices could lead to surfaces extending outside
3362 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3363 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3364 // transformations.
3365 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003366 flags |= eTraversalNeeded;
3367 }
3368 if (what & layer_state_t::eTransparentRegionChanged) {
3369 if (layer->setTransparentRegionHint(s.transparentRegion))
3370 flags |= eTraversalNeeded;
3371 }
3372 if (what & layer_state_t::eFlagsChanged) {
3373 if (layer->setFlags(s.flags, s.mask))
3374 flags |= eTraversalNeeded;
3375 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003376 if (what & layer_state_t::eCropChanged_legacy) {
3377 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003378 flags |= eTraversalNeeded;
3379 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003380 if (what & layer_state_t::eFinalCropChanged_legacy) {
3381 if (layer->setFinalCrop_legacy(s.finalCrop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003382 flags |= eTraversalNeeded;
3383 }
3384 if (what & layer_state_t::eLayerStackChanged) {
3385 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3386 // We only allow setting layer stacks for top level layers,
3387 // everything else inherits layer stack from its parent.
3388 if (layer->hasParent()) {
3389 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3390 layer->getName().string());
3391 } else if (idx < 0) {
3392 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3393 "that also does not appear in the top level layer list. Something"
3394 " has gone wrong.", layer->getName().string());
3395 } else if (layer->setLayerStack(s.layerStack)) {
3396 mCurrentState.layersSortedByZ.removeAt(idx);
3397 mCurrentState.layersSortedByZ.add(layer);
3398 // we need traversal (state changed)
3399 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003400 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003401 }
3402 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003403 if (what & layer_state_t::eDeferTransaction_legacy) {
3404 if (s.barrierHandle_legacy != nullptr) {
3405 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3406 } else if (s.barrierGbp_legacy != nullptr) {
3407 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003408 if (authenticateSurfaceTextureLocked(gbp)) {
3409 const auto& otherLayer =
3410 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003411 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003412 } else {
3413 ALOGE("Attempt to defer transaction to to an"
3414 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003415 }
3416 }
chaviw8b3871a2017-11-01 17:41:01 -07003417 // We don't trigger a traversal here because if no other state is
3418 // changed, we don't want this to cause any more work
3419 }
3420 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003421 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003422 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003423 if (!hadParent) {
3424 mCurrentState.layersSortedByZ.remove(layer);
3425 }
chaviw8b3871a2017-11-01 17:41:01 -07003426 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003427 }
chaviw8b3871a2017-11-01 17:41:01 -07003428 }
3429 if (what & layer_state_t::eReparentChildren) {
3430 if (layer->reparentChildren(s.reparentHandle)) {
3431 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003432 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003433 }
chaviw8b3871a2017-11-01 17:41:01 -07003434 if (what & layer_state_t::eDetachChildren) {
3435 layer->detachChildren();
3436 }
3437 if (what & layer_state_t::eOverrideScalingModeChanged) {
3438 layer->setOverrideScalingMode(s.overrideScalingMode);
3439 // We don't trigger a traversal here because if no other state is
3440 // changed, we don't want this to cause any more work
3441 }
Marissa Wall61c58622018-07-18 10:12:20 -07003442 if (what & layer_state_t::eTransformChanged) {
3443 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3444 }
3445 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3446 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3447 flags |= eTraversalNeeded;
3448 }
3449 if (what & layer_state_t::eCropChanged) {
3450 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3451 }
3452 if (what & layer_state_t::eBufferChanged) {
3453 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3454 }
3455 if (what & layer_state_t::eAcquireFenceChanged) {
3456 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3457 }
3458 if (what & layer_state_t::eDataspaceChanged) {
3459 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3460 }
3461 if (what & layer_state_t::eHdrMetadataChanged) {
3462 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3463 }
3464 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3465 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3466 }
3467 if (what & layer_state_t::eApiChanged) {
3468 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3469 }
3470 if (what & layer_state_t::eSidebandStreamChanged) {
3471 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3472 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003473 return flags;
3474}
3475
chaviwca27f252018-02-06 16:46:39 -08003476void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3477 const layer_state_t& state = composerState.state;
3478 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3479
3480 sp<Layer> layer(client->getLayerUser(state.surface));
3481 if (layer == nullptr) {
3482 return;
3483 }
3484
3485 if (layer->isPendingRemoval()) {
3486 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3487 return;
3488 }
3489
3490 if (state.what & layer_state_t::eDestroySurface) {
3491 removeLayerLocked(mStateLock, layer);
3492 }
3493}
3494
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003495status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003496 const String8& name,
3497 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003498 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003499 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003500 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003501{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003502 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003503 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003504 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003505 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003506 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003507
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003508 status_t result = NO_ERROR;
3509
3510 sp<Layer> layer;
3511
Cody Northropbc755282017-03-31 12:00:08 -06003512 String8 uniqueName = getUniqueLayerName(name);
3513
Mathias Agopian3165cc22012-08-08 19:42:09 -07003514 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003515 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003516 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3517 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003518
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003519 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003520 case ISurfaceComposerClient::eFXSurfaceBufferState:
3521 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3522 break;
chaviw13fdc492017-06-27 12:40:18 -07003523 case ISurfaceComposerClient::eFXSurfaceColor:
3524 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003525 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003526 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003527 break;
3528 default:
3529 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003530 break;
3531 }
3532
Dan Stoza7d89d062015-04-30 13:29:25 -07003533 if (result != NO_ERROR) {
3534 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003535 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003536
Chia-I Wuab0c3192017-08-01 11:29:00 -07003537 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3538 // TODO b/64227542
3539 if (windowType == 441731) {
3540 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3541 layer->setPrimaryDisplayOnly();
3542 }
3543
Albert Chaulk479c60c2017-01-27 14:21:34 -05003544 layer->setInfo(windowType, ownerUid);
3545
Robert Carr1f0a16a2016-10-24 16:27:39 -07003546 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003547 if (result != NO_ERROR) {
3548 return result;
3549 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003550 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003551
3552 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003553 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003554}
3555
Cody Northropbc755282017-03-31 12:00:08 -06003556String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3557{
3558 bool matchFound = true;
3559 uint32_t dupeCounter = 0;
3560
3561 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3562 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3563
Dan Stoza436ccf32018-06-21 12:10:12 -07003564 // Grab the state lock since we're accessing mCurrentState
3565 Mutex::Autolock lock(mStateLock);
3566
Cody Northropbc755282017-03-31 12:00:08 -06003567 // Loop over layers until we're sure there is no matching name
3568 while (matchFound) {
3569 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003570 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003571 if (layer->getName() == uniqueName) {
3572 matchFound = true;
3573 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3574 }
3575 });
3576 }
3577
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003578 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3579 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003580
3581 return uniqueName;
3582}
3583
Marissa Wallfd668622018-05-10 10:21:13 -07003584status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3585 uint32_t w, uint32_t h, uint32_t flags,
3586 PixelFormat& format, sp<IBinder>* handle,
3587 sp<IGraphicBufferProducer>* gbp,
3588 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003589 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003590 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003591 case PIXEL_FORMAT_TRANSPARENT:
3592 case PIXEL_FORMAT_TRANSLUCENT:
3593 format = PIXEL_FORMAT_RGBA_8888;
3594 break;
3595 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003596 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003597 break;
3598 }
3599
Marissa Wallfd668622018-05-10 10:21:13 -07003600 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3601 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003602 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003603 *handle = layer->getHandle();
3604 *gbp = layer->getProducer();
3605 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003606 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003607
Marissa Wallfd668622018-05-10 10:21:13 -07003608 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003609 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003610}
3611
Marissa Wall61c58622018-07-18 10:12:20 -07003612status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3613 uint32_t w, uint32_t h, uint32_t flags,
3614 sp<IBinder>* handle, sp<Layer>* outLayer) {
3615 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3616 *handle = layer->getHandle();
3617 *outLayer = layer;
3618
3619 return NO_ERROR;
3620}
3621
chaviw13fdc492017-06-27 12:40:18 -07003622status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003623 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003624 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003625{
chaviw13fdc492017-06-27 12:40:18 -07003626 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003627 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003628 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003629}
3630
Mathias Agopianac9fa422013-02-11 16:40:36 -08003631status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003632{
Robert Carr9524cb32017-02-13 11:32:32 -08003633 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003634 status_t err = NO_ERROR;
3635 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003636 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003637 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003638 err = removeLayer(l);
3639 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3640 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003641 }
3642 return err;
3643}
3644
Mathias Agopian13127d82013-03-05 17:47:11 -08003645status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003646{
Mathias Agopian67106042013-03-14 19:18:13 -07003647 // called by ~LayerCleaner() when all references to the IBinder (handle)
3648 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003649 sp<Layer> l = layer.promote();
3650 if (l == nullptr) {
3651 // The layer has already been removed, carry on
3652 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003653 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003654 // If we have a parent, then we can continue to live as long as it does.
3655 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003656}
3657
Mathias Agopianb60314a2012-04-10 22:09:54 -07003658// ---------------------------------------------------------------------------
3659
Andy McFadden13a082e2012-08-24 10:16:42 -07003660void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003661 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3662 if (!displayToken) return;
3663
Jesse Hall01e29052013-02-19 16:13:35 -08003664 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003665 Vector<ComposerState> state;
3666 Vector<DisplayState> displays;
3667 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003668 d.what = DisplayState::eDisplayProjectionChanged |
3669 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003670 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003671 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003672 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003673 d.frame.makeInvalid();
3674 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003675 d.width = 0;
3676 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003677 displays.add(d);
3678 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003679
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003680 const auto display = getDisplayDevice(displayToken);
3681 if (!display) return;
3682
3683 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3684
3685 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003686 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003687 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003688
Brian Andersond0010582017-03-07 13:20:31 -08003689 // Use phase of 0 since phase is not known.
3690 // Use latency of 0, which will snap to the ideal latency.
3691 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003692}
3693
3694void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003695 // Async since we may be called from the main thread.
3696 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003697}
3698
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003699void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3700 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003701 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003702 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003703
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003704 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003705 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003706 return;
3707 }
3708
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003709 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003710 ALOGW("Trying to set power mode for virtual display");
3711 return;
3712 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003713
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003714 display->setPowerMode(mode);
3715
Lloyd Pique4dccc412018-01-22 17:21:36 -08003716 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003717 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003718 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003719 if (idx < 0) {
3720 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3721 return;
3722 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003723 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003724 }
3725
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003726 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003727 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003728 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003729 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003730 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003731 // FIXME: eventthread only knows about the main display right now
3732 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003733 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003734 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003735
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003736 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003737 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003738 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003739
3740 struct sched_param param = {0};
3741 param.sched_priority = 1;
3742 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3743 ALOGW("Couldn't set SCHED_FIFO on display on");
3744 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003745 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003746 // Turn off the display
3747 struct sched_param param = {0};
3748 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3749 ALOGW("Couldn't set SCHED_OTHER on display off");
3750 }
3751
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003752 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003753 disableHardwareVsync(true); // also cancels any in-progress resync
3754
Mathias Agopiancde87a32012-09-13 14:09:01 -07003755 // FIXME: eventthread only knows about the main display right now
3756 mEventThread->onScreenReleased();
3757 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003758
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003759 getHwComposer().setPowerMode(type, mode);
3760 mVisibleRegionsDirty = true;
3761 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003762 } else if (mode == HWC_POWER_MODE_DOZE ||
3763 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003764 // Update display while dozing
3765 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003766 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003767 // FIXME: eventthread only knows about the main display right now
3768 mEventThread->onScreenAcquired();
3769 resyncToHardwareVsync(true);
3770 }
3771 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3772 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003773 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003774 disableHardwareVsync(true); // also cancels any in-progress resync
3775 // FIXME: eventthread only knows about the main display right now
3776 mEventThread->onScreenReleased();
3777 }
3778 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003779 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003780 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003781 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003782 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003783
3784 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003785}
3786
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003787void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003788 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003789 const auto display = getDisplayDevice(displayToken);
3790 if (!display) {
3791 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3792 displayToken.get());
3793 } else if (display->isVirtual()) {
3794 ALOGW("Attempt to set power mode %d for virtual display", mode);
3795 } else {
3796 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003797 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003798 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003799}
3800
3801// ---------------------------------------------------------------------------
3802
Lloyd Pique755e3192018-01-31 16:46:15 -08003803status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3804 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003805 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003806
Mathias Agopianbd115332013-04-18 16:41:04 -07003807 IPCThreadState* ipc = IPCThreadState::self();
3808 const int pid = ipc->getCallingPid();
3809 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003810
Mathias Agopianbd115332013-04-18 16:41:04 -07003811 if ((uid != AID_SHELL) &&
3812 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003813 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003814 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003815 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003816 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003817 // (this would indicate SF is stuck, but we want to be able to
3818 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003819 status_t err = mStateLock.timedLock(s2ns(1));
3820 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003821 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003822 result.appendFormat(
3823 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3824 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003825 }
3826
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003827 bool dumpAll = true;
3828 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003829 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003830
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003831 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003832 if ((index < numArgs) &&
3833 (args[index] == String16("--list"))) {
3834 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003835 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003836 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003837 }
3838
3839 if ((index < numArgs) &&
3840 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003841 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003842 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003843 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003844 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003845
3846 if ((index < numArgs) &&
3847 (args[index] == String16("--latency-clear"))) {
3848 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003849 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003850 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003851 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003852
3853 if ((index < numArgs) &&
3854 (args[index] == String16("--dispsync"))) {
3855 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07003856 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07003857 dumpAll = false;
3858 }
Dan Stozab90cf072015-03-05 11:05:59 -08003859
3860 if ((index < numArgs) &&
3861 (args[index] == String16("--static-screen"))) {
3862 index++;
3863 dumpStaticScreenStats(result);
3864 dumpAll = false;
3865 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003866
3867 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003868 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003869 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003870 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003871 dumpAll = false;
3872 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003873
3874 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3875 index++;
3876 dumpWideColorInfo(result);
3877 dumpAll = false;
3878 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003879
3880 if ((index < numArgs) &&
3881 (args[index] == String16("--enable-layer-stats"))) {
3882 index++;
3883 mLayerStats.enable();
3884 dumpAll = false;
3885 }
3886
3887 if ((index < numArgs) &&
3888 (args[index] == String16("--disable-layer-stats"))) {
3889 index++;
3890 mLayerStats.disable();
3891 dumpAll = false;
3892 }
3893
3894 if ((index < numArgs) &&
3895 (args[index] == String16("--clear-layer-stats"))) {
3896 index++;
3897 mLayerStats.clear();
3898 dumpAll = false;
3899 }
3900
3901 if ((index < numArgs) &&
3902 (args[index] == String16("--dump-layer-stats"))) {
3903 index++;
3904 mLayerStats.dump(result);
3905 dumpAll = false;
3906 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003907
3908 if ((index < numArgs) &&
3909 (args[index] == String16("--display-identification"))) {
3910 index++;
3911 dumpDisplayIdentificationData(result);
3912 dumpAll = false;
3913 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003914
3915 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3916 index++;
3917 mTimeStats.parseArgs(asProto, args, index, result);
3918 dumpAll = false;
3919 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003920 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003921
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003922 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003923 if (asProto) {
3924 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3925 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3926 } else {
3927 dumpAllLocked(args, index, result);
3928 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003929 }
3930
Mathias Agopian9795c422009-08-26 16:36:26 -07003931 if (locked) {
3932 mStateLock.unlock();
3933 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003934 }
3935 write(fd, result.string(), result.size());
3936 return NO_ERROR;
3937}
3938
Dan Stozac7014012014-02-14 15:03:43 -08003939void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3940 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003941{
Robert Carr2047fae2016-11-28 14:09:09 -08003942 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003943 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003944 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003945}
3946
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003947void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003948 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003949{
3950 String8 name;
3951 if (index < args.size()) {
3952 name = String8(args[index]);
3953 index++;
3954 }
3955
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003956 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
3957 getHwComposer().isConnected(displayId)) {
3958 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
3959 const nsecs_t period = activeConfig->getVsyncPeriod();
3960 result.appendFormat("%" PRId64 "\n", period);
3961 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003962
3963 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003964 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003965 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003966 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003967 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003968 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003969 }
Robert Carr2047fae2016-11-28 14:09:09 -08003970 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003971 }
3972}
3973
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003974void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003975 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003976{
3977 String8 name;
3978 if (index < args.size()) {
3979 name = String8(args[index]);
3980 index++;
3981 }
3982
Robert Carr2047fae2016-11-28 14:09:09 -08003983 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003984 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003985 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003986 }
Robert Carr2047fae2016-11-28 14:09:09 -08003987 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003988
Svetoslavd85084b2014-03-20 10:28:31 -07003989 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003990}
3991
Jamie Gennis6547ff42013-07-16 20:12:42 -07003992// This should only be called from the main thread. Otherwise it would need
3993// the lock and should use mCurrentState rather than mDrawingState.
3994void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003995 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003996 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003997 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003998
3999 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4000}
4001
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004002void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004003{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004004 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004005
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004006 if (isLayerTripleBufferingDisabled())
4007 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004008
4009 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004010 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004011 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004012 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004013 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4014 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004015 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004016}
4017
Dan Stozab90cf072015-03-05 11:05:59 -08004018void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4019{
4020 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004021 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4022 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004023 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004024 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004025 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4026 b + 1, bucketTimeSec, percent);
4027 }
David Sodman4a36e932017-11-07 14:29:47 -08004028 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004029 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004030 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004031 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004032 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004033}
4034
Dan Stozae77c7662016-05-13 11:37:28 -07004035void SurfaceFlinger::recordBufferingStats(const char* layerName,
4036 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004037 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4038 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004039 for (const auto& segment : history) {
4040 if (!segment.usedThirdBuffer) {
4041 stats.twoBufferTime += segment.totalTime;
4042 }
4043 if (segment.occupancyAverage < 1.0f) {
4044 stats.doubleBufferedTime += segment.totalTime;
4045 } else if (segment.occupancyAverage < 2.0f) {
4046 stats.tripleBufferedTime += segment.totalTime;
4047 }
4048 ++stats.numSegments;
4049 stats.totalTime += segment.totalTime;
4050 }
4051}
4052
Brian Andersond6927fb2016-07-23 23:37:30 -07004053void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4054 result.appendFormat("Layer frame timestamps:\n");
4055
4056 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4057 const size_t count = currentLayers.size();
4058 for (size_t i=0 ; i<count ; i++) {
4059 currentLayers[i]->dumpFrameEvents(result);
4060 }
4061}
4062
Dan Stozae77c7662016-05-13 11:37:28 -07004063void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4064 result.append("Buffering stats:\n");
4065 result.append(" [Layer name] <Active time> <Two buffer> "
4066 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004067 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004068 typedef std::tuple<std::string, float, float, float> BufferTuple;
4069 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004070 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004071 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004072 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004073 if (stats.numSegments == 0) {
4074 continue;
4075 }
4076 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4077 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4078 stats.totalTime;
4079 float doubleBufferRatio = static_cast<float>(
4080 stats.doubleBufferedTime) / stats.totalTime;
4081 float tripleBufferRatio = static_cast<float>(
4082 stats.tripleBufferedTime) / stats.totalTime;
4083 sorted.insert({activeTime, {name, twoBufferRatio,
4084 doubleBufferRatio, tripleBufferRatio}});
4085 }
4086 for (const auto& sortedPair : sorted) {
4087 float activeTime = sortedPair.first;
4088 const BufferTuple& values = sortedPair.second;
4089 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4090 std::get<0>(values).c_str(), activeTime,
4091 std::get<1>(values), std::get<2>(values),
4092 std::get<3>(values));
4093 }
4094 result.append("\n");
4095}
4096
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004097void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004098 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004099 const int32_t displayId = display->getId();
4100 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4101 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004102 continue;
4103 }
4104
Dominik Laskowski7e045462018-05-30 13:02:02 -07004105 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004106 uint8_t port;
4107 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004108 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004109 result.append("no identification data\n");
4110 continue;
4111 }
4112
4113 if (!isEdid(data)) {
4114 result.append("unknown identification data: ");
4115 for (uint8_t byte : data) {
4116 result.appendFormat("%x ", byte);
4117 }
4118 result.append("\n");
4119 continue;
4120 }
4121
4122 const auto edid = parseEdid(data);
4123 if (!edid) {
4124 result.append("invalid EDID: ");
4125 for (uint8_t byte : data) {
4126 result.appendFormat("%x ", byte);
4127 }
4128 result.append("\n");
4129 continue;
4130 }
4131
4132 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4133 result.append(edid->displayName.data(), edid->displayName.length());
4134 result.append("\"\n");
4135 }
4136 result.append("\n");
4137}
4138
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004139void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4140 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004141 result.appendFormat("DisplayColorSetting: %s\n",
4142 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004143
4144 // TODO: print out if wide-color mode is active or not
4145
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004146 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004147 const int32_t displayId = display->getId();
4148 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004149 continue;
4150 }
4151
Dominik Laskowski7e045462018-05-30 13:02:02 -07004152 result.appendFormat("Display %d color modes:\n", displayId);
4153 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004154 for (auto&& mode : modes) {
4155 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4156 }
4157
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004158 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004159 result.appendFormat(" Current color mode: %s (%d)\n",
4160 decodeColorMode(currentMode).c_str(), currentMode);
4161 }
4162 result.append("\n");
4163}
4164
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004165LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004166 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004167 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4168 const State& state = useDrawing ? mDrawingState : mCurrentState;
4169 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004170 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004171 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004172 });
4173
4174 return layersProto;
4175}
4176
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004177LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004178 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004179
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004180 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004181 resolution->set_w(display.getWidth());
4182 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004183
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004184 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4185 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4186 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004187
Dominik Laskowski7e045462018-05-30 13:02:02 -07004188 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004189 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004190 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004191 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004192 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004193 }
4194 });
4195
4196 return layersProto;
4197}
4198
Mathias Agopian74d211a2013-04-22 16:55:35 +02004199void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4200 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004201{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004202 bool colorize = false;
4203 if (index < args.size()
4204 && (args[index] == String16("--color"))) {
4205 colorize = true;
4206 index++;
4207 }
4208
4209 Colorizer colorizer(colorize);
4210
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004211 // figure out if we're stuck somewhere
4212 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004213 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004214 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4215
4216 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004217 * Dump library configuration.
4218 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004219
4220 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004221 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004222 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004223 appendSfConfigString(result);
4224 appendUiConfigString(result);
4225 appendGuiConfigString(result);
4226 result.append("\n");
4227
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004228 result.append("\nDisplay identification data:\n");
4229 dumpDisplayIdentificationData(result);
4230
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004231 result.append("\nWide-Color information:\n");
4232 dumpWideColorInfo(result);
4233
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004234 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004235 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004236 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004237 result.append(SyncFeatures::getInstance().toString());
4238 result.append("\n");
4239
Andy McFadden41d67d72014-04-25 16:58:34 -07004240 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004241 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004242 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004243
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004244 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4245 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004246 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4247 getHwComposer().isConnected(displayId)) {
4248 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004249 result.appendFormat("Display %d: "
4250 "app phase %" PRId64 " ns, "
4251 "sf phase %" PRId64 " ns, "
4252 "early app phase %" PRId64 " ns, "
4253 "early sf phase %" PRId64 " ns, "
4254 "early app gl phase %" PRId64 " ns, "
4255 "early sf gl phase %" PRId64 " ns, "
4256 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4257 displayId,
4258 vsyncPhaseOffsetNs,
4259 sfVsyncPhaseOffsetNs,
4260 appEarlyOffset,
4261 sfEarlyOffset,
4262 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004263 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004264 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004265 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004266 result.append("\n");
4267
Dan Stozab90cf072015-03-05 11:05:59 -08004268 // Dump static screen stats
4269 result.append("\n");
4270 dumpStaticScreenStats(result);
4271 result.append("\n");
4272
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004273 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4274
Dan Stozae77c7662016-05-13 11:37:28 -07004275 dumpBufferingStats(result);
4276
Andy McFadden4803b742012-09-24 19:07:20 -07004277 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004278 * Dump the visible layer list
4279 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004280 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004281 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004282 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4283 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004284 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004285
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004286 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004287 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004288 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004289 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004290
4291 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004292 * Dump Display state
4293 */
4294
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004295 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004296 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004297 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004298 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004299 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004300 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004301 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004302
4303 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004304 * Dump SurfaceFlinger global state
4305 */
4306
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004307 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004308 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004309 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004310
Mathias Agopian888c8222012-08-04 21:10:38 -07004311 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004312 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004313
David Sodmanbc815282017-11-05 18:57:52 -08004314 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004315
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004316 if (display) {
4317 display->undefinedRegion.dump(result, "undefinedRegion");
4318 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4319 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004320 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004321 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004322 " gpu_to_cpu_unsupported : %d\n",
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004323 mTransactionFlags, !mGpuToCpuSupported);
4324
4325 if (display) {
4326 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4327 result.appendFormat(" refresh-rate : %f fps\n"
4328 " x-dpi : %f\n"
4329 " y-dpi : %f\n",
4330 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4331 activeConfig->getDpiY());
4332 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004333
Mathias Agopian74d211a2013-04-22 16:55:35 +02004334 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004335 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004336
4337 /*
4338 * VSYNC state
4339 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004340 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004341 result.append("\n");
4342
4343 /*
4344 * HWC layer minidump
4345 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004346 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004347 const int32_t displayId = display->getId();
4348 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004349 continue;
4350 }
4351
Dominik Laskowski7e045462018-05-30 13:02:02 -07004352 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004353 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004354 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004355 result.append("\n");
4356 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004357
4358 /*
4359 * Dump HWComposer state
4360 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004361 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004362 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004363 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004364 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004365 result.appendFormat(" h/w composer %s\n",
4366 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004367 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004368
4369 /*
4370 * Dump gralloc state
4371 */
4372 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4373 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004374
4375 /*
4376 * Dump VrFlinger state if in use.
4377 */
4378 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4379 result.append("VrFlinger state:\n");
4380 result.append(mVrFlinger->Dump().c_str());
4381 result.append("\n");
4382 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004383}
4384
Dominik Laskowski7e045462018-05-30 13:02:02 -07004385const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004386 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004387 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004388 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004389 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004390 }
4391 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004392
4393 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4394 static const Vector<sp<Layer>> empty;
4395 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004396}
4397
Keun young Park63f165f2012-08-31 10:53:36 -07004398bool SurfaceFlinger::startDdmConnection()
4399{
4400 void* libddmconnection_dso =
4401 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4402 if (!libddmconnection_dso) {
4403 return false;
4404 }
4405 void (*DdmConnection_start)(const char* name);
4406 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004407 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004408 if (!DdmConnection_start) {
4409 dlclose(libddmconnection_dso);
4410 return false;
4411 }
4412 (*DdmConnection_start)(getServiceName());
4413 return true;
4414}
4415
Chia-I Wu28f320b2018-05-03 11:02:56 -07004416void SurfaceFlinger::updateColorMatrixLocked() {
4417 mat4 colorMatrix;
4418 if (mGlobalSaturationFactor != 1.0f) {
4419 // Rec.709 luma coefficients
4420 float3 luminance{0.213f, 0.715f, 0.072f};
4421 luminance *= 1.0f - mGlobalSaturationFactor;
4422 mat4 saturationMatrix = mat4(
4423 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4424 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4425 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4426 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4427 );
4428 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4429 } else {
4430 colorMatrix = mClientColorMatrix * mDaltonizer();
4431 }
4432
4433 if (mCurrentState.colorMatrix != colorMatrix) {
4434 mCurrentState.colorMatrix = colorMatrix;
4435 mCurrentState.colorMatrixChanged = true;
4436 setTransactionFlags(eTransactionNeeded);
4437 }
4438}
4439
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004440status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004441#pragma clang diagnostic push
4442#pragma clang diagnostic error "-Wswitch-enum"
4443 switch (static_cast<ISurfaceComposerTag>(code)) {
4444 // These methods should at minimum make sure that the client requested
4445 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004446 case BOOT_FINISHED:
4447 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004448 case CREATE_CONNECTION:
4449 case CREATE_DISPLAY:
4450 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004451 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004452 case GET_ACTIVE_COLOR_MODE:
4453 case GET_ANIMATION_FRAME_STATS:
4454 case GET_HDR_CAPABILITIES:
4455 case SET_ACTIVE_CONFIG:
4456 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004457 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004458 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004459 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4460 IPCThreadState* ipc = IPCThreadState::self();
4461 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4462 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004463 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004464 }
Robert Carr1db73f62016-12-21 12:58:51 -08004465 return OK;
4466 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004467 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004468 IPCThreadState* ipc = IPCThreadState::self();
4469 const int pid = ipc->getCallingPid();
4470 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004471 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4472 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004473 return PERMISSION_DENIED;
4474 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004475 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004476 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004477 // Used by apps to hook Choreographer to SurfaceFlinger.
4478 case CREATE_DISPLAY_EVENT_CONNECTION:
4479 // The following calls are currently used by clients that do not
4480 // request necessary permissions. However, they do not expose any secret
4481 // information, so it is OK to pass them.
4482 case AUTHENTICATE_SURFACE:
4483 case GET_ACTIVE_CONFIG:
4484 case GET_BUILT_IN_DISPLAY:
4485 case GET_DISPLAY_COLOR_MODES:
4486 case GET_DISPLAY_CONFIGS:
4487 case GET_DISPLAY_STATS:
4488 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4489 // Calling setTransactionState is safe, because you need to have been
4490 // granted a reference to Client* and Handle* to do anything with it.
4491 case SET_TRANSACTION_STATE:
4492 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4493 case CREATE_SCOPED_CONNECTION: {
4494 return OK;
4495 }
4496 case CAPTURE_LAYERS:
4497 case CAPTURE_SCREEN: {
4498 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004499 IPCThreadState* ipc = IPCThreadState::self();
4500 const int pid = ipc->getCallingPid();
4501 const int uid = ipc->getCallingUid();
4502 if ((uid != AID_GRAPHICS) &&
4503 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4504 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4505 return PERMISSION_DENIED;
4506 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004507 return OK;
4508 }
4509 // The following codes are deprecated and should never be allowed to access SF.
4510 case CONNECT_DISPLAY_UNUSED:
4511 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4512 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4513 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004514 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004515 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004516
4517 // These codes are used for the IBinder protocol to either interrogate the recipient
4518 // side of the transaction for its canonical interface descriptor or to dump its state.
4519 // We let them pass by default.
4520 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4521 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4522 code == IBinder::SYSPROPS_TRANSACTION) {
4523 return OK;
4524 }
4525 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4526 // in onTransact verifies that the user is root, and has access to use SF.
4527 if (code >= 1000 && code <= 1029) {
4528 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4529 return OK;
4530 }
4531 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4532 return PERMISSION_DENIED;
4533#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004534}
4535
Ana Krulec13be8ad2018-08-21 02:43:56 +00004536status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4537 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004538 status_t credentialCheck = CheckTransactCodeCredentials(code);
4539 if (credentialCheck != OK) {
4540 return credentialCheck;
4541 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004542
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004543 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4544 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004545 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004546 IPCThreadState* ipc = IPCThreadState::self();
4547 const int uid = ipc->getCallingUid();
4548 if (CC_UNLIKELY(uid != AID_SYSTEM
4549 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004550 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004551 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004552 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004553 return PERMISSION_DENIED;
4554 }
4555 int n;
4556 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004557 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004558 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004559 return NO_ERROR;
4560 case 1002: // SHOW_UPDATES
4561 n = data.readInt32();
4562 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004563 invalidateHwcGeometry();
4564 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004565 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004566 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004567 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004568 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004569 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004570 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004571 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004572 setTransactionFlags(
4573 eTransactionNeeded|
4574 eDisplayTransactionNeeded|
4575 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004576 return NO_ERROR;
4577 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004578 case 1006:{ // send empty update
4579 signalRefresh();
4580 return NO_ERROR;
4581 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004582 case 1008: // toggle use of hw composer
4583 n = data.readInt32();
4584 mDebugDisableHWC = n ? 1 : 0;
4585 invalidateHwcGeometry();
4586 repaintEverything();
4587 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004588 case 1009: // toggle use of transform hint
4589 n = data.readInt32();
4590 mDebugDisableTransformHint = n ? 1 : 0;
4591 invalidateHwcGeometry();
4592 repaintEverything();
4593 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004594 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004595 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004596 reply->writeInt32(0);
4597 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004598 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004599 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004600 return NO_ERROR;
4601 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004602 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004603 if (!display) {
4604 return NAME_NOT_FOUND;
4605 }
4606
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004607 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004608 return NO_ERROR;
4609 }
4610 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004611 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004612 // daltonize
4613 n = data.readInt32();
4614 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004615 case 1:
4616 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4617 break;
4618 case 2:
4619 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4620 break;
4621 case 3:
4622 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4623 break;
4624 default:
4625 mDaltonizer.setType(ColorBlindnessType::None);
4626 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004627 }
4628 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004629 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004630 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004631 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004632 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004633
4634 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004635 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004636 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004637 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004638 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004639 // apply a color matrix
4640 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004641 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004642 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004643 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004644 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004645 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004646 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004647 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004648 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004649 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004650 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004651
4652 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4653 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004654 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004655 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4656 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4657 }
4658
Chia-I Wu28f320b2018-05-03 11:02:56 -07004659 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004660 return NO_ERROR;
4661 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004662 // This is an experimental interface
4663 // Needs to be shifted to proper binder interface when we productize
4664 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004665 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07004666 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004667 return NO_ERROR;
4668 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004669 case 1017: {
4670 n = data.readInt32();
4671 mForceFullDamage = static_cast<bool>(n);
4672 return NO_ERROR;
4673 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004674 case 1018: { // Modify Choreographer's phase offset
4675 n = data.readInt32();
4676 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4677 return NO_ERROR;
4678 }
4679 case 1019: { // Modify SurfaceFlinger's phase offset
4680 n = data.readInt32();
4681 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4682 return NO_ERROR;
4683 }
Irvel468051e2016-06-13 16:44:44 -07004684 case 1020: { // Layer updates interceptor
4685 n = data.readInt32();
4686 if (n) {
4687 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004688 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004689 }
4690 else{
4691 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004692 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004693 }
4694 return NO_ERROR;
4695 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004696 case 1021: { // Disable HWC virtual displays
4697 n = data.readInt32();
4698 mUseHwcVirtualDisplays = !n;
4699 return NO_ERROR;
4700 }
Romain Guy0147a172017-06-01 13:53:56 -07004701 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004702 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004703 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004704
Chia-I Wu28f320b2018-05-03 11:02:56 -07004705 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004706 return NO_ERROR;
4707 }
Romain Guy54f154a2017-10-24 21:40:32 +01004708 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004709 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004710 invalidateHwcGeometry();
4711 repaintEverything();
4712 return NO_ERROR;
4713 }
4714 case 1024: { // Is wide color gamut rendering/color management supported?
4715 reply->writeBool(hasWideColorDisplay);
4716 return NO_ERROR;
4717 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004718 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004719 n = data.readInt32();
4720 if (n) {
4721 ALOGV("LayerTracing enabled");
4722 mTracing.enable();
4723 doTracing("tracing.enable");
4724 reply->writeInt32(NO_ERROR);
4725 } else {
4726 ALOGV("LayerTracing disabled");
4727 status_t err = mTracing.disable();
4728 reply->writeInt32(err);
4729 }
4730 return NO_ERROR;
4731 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004732 case 1026: { // Get layer tracing status
4733 reply->writeBool(mTracing.isEnabled());
4734 return NO_ERROR;
4735 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004736 // Is a DisplayColorSetting supported?
4737 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004738 const auto display = getDefaultDisplayDevice();
4739 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004740 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004741 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004742
4743 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4744 switch (setting) {
4745 case DisplayColorSetting::MANAGED:
4746 reply->writeBool(hasWideColorDisplay);
4747 break;
4748 case DisplayColorSetting::UNMANAGED:
4749 reply->writeBool(true);
4750 break;
4751 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004752 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004753 break;
4754 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004755 reply->writeBool(
4756 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004757 break;
4758 }
4759 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004760 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004761 // Is VrFlinger active?
4762 case 1028: {
4763 Mutex::Autolock _l(mStateLock);
4764 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4765 return NO_ERROR;
4766 }
David Sodman6d46c1e2018-07-13 12:59:48 -07004767 case 1029: {
4768 // Code 1029 is an experimental feature that allows applications to
4769 // simulate a high frequency panel by setting a multiplier and divisor
4770 // on the VSYNC-sf clock. If either the multiplier or divisor are
4771 // 0, then the code will set both to 1 to return the VSYNC-sf clock
4772 // to it's normal frequency.
4773 int multiplier = data.readInt32();
4774 int divisor = data.readInt32();
4775
4776 if ((multiplier == 0) || (divisor == 0)) {
4777 multiplier = 1;
4778 divisor = 1;
4779 }
4780
4781 if ((multiplier == 1) && (divisor == 1)) {
4782 enableHardwareVsync();
4783 } else {
4784 disableHardwareVsync(true);
4785 }
4786 getBE().mHwc->getActiveConfig(DisplayDevice::DISPLAY_PRIMARY)
4787 ->scalePanelFrequency(multiplier, divisor);
4788 mPrimaryDispSync->scalePeriod(multiplier, divisor);
4789
4790 ATRACE_INT("PeriodMultiplier", multiplier);
4791 ATRACE_INT("PeriodDivisor", divisor);
4792 return NO_ERROR;
4793 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004794 }
4795 }
4796 return err;
4797}
4798
Steven Thomas6d8110b2017-08-31 18:24:21 -07004799void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004800 android_atomic_or(1, &mRepaintEverything);
4801 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004802}
4803
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004804// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4805class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004806public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004807 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4808 ~WindowDisconnector() {
4809 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004810 }
4811
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004812private:
4813 ANativeWindow* mWindow;
4814 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004815};
4816
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004817status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4818 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4819 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4820 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004821 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004822 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004823
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004824 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004825
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004826 const auto display = getDisplayDeviceLocked(displayToken);
4827 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004828
Yiwei Zhang06a58e22018-08-20 16:42:23 -07004829 const Rect& dispScissor = display->getScissor();
4830 if (!dispScissor.isEmpty()) {
4831 sourceCrop.set(dispScissor);
4832 // adb shell screencap will default reqWidth and reqHeight to zeros.
4833 if (reqWidth == 0 || reqHeight == 0) {
4834 reqWidth = uint32_t(dispScissor.width());
4835 reqHeight = uint32_t(dispScissor.height());
4836 }
4837 }
4838
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004839 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004840
4841 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004842 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004843 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004844}
4845
4846status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004847 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004848 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004849 ATRACE_CALL();
4850
4851 class LayerRenderArea : public RenderArea {
4852 public:
Robert Carr578038f2018-03-09 12:25:24 -08004853 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4854 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004855 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004856 mLayer(layer),
4857 mCrop(crop),
4858 mFlinger(flinger),
4859 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07004860 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004861 Rect getBounds() const override {
4862 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07004863 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07004864 }
Marissa Wall61c58622018-07-18 10:12:20 -07004865 int getHeight() const override {
4866 return mLayer->getActiveHeight(mLayer->getDrawingState());
4867 }
4868 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07004869 bool isSecure() const override { return false; }
4870 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004871 Rect getSourceCrop() const override {
4872 if (mCrop.isEmpty()) {
4873 return getBounds();
4874 } else {
4875 return mCrop;
4876 }
4877 }
Robert Carr578038f2018-03-09 12:25:24 -08004878 class ReparentForDrawing {
4879 public:
4880 const sp<Layer>& oldParent;
4881 const sp<Layer>& newParent;
4882
4883 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4884 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004885 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004886 }
Robert Carr15eae092018-03-23 13:43:53 -07004887 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004888 };
4889
4890 void render(std::function<void()> drawLayers) override {
4891 if (!mChildrenOnly) {
4892 mTransform = mLayer->getTransform().inverse();
4893 drawLayers();
4894 } else {
4895 Rect bounds = getBounds();
4896 screenshotParentLayer =
4897 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4898 bounds.getWidth(), bounds.getHeight(), 0);
4899
4900 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4901 drawLayers();
4902 }
4903 }
chaviwa76b2712017-09-20 12:02:26 -07004904
chaviwa76b2712017-09-20 12:02:26 -07004905 private:
chaviw7206d492017-11-10 16:16:12 -08004906 const sp<Layer> mLayer;
4907 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004908
4909 // In the "childrenOnly" case we reparent the children to a screenshot
4910 // layer which has no properties set and which does not draw.
4911 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07004912 ui::Transform mTransform;
Robert Carr578038f2018-03-09 12:25:24 -08004913
4914 SurfaceFlinger* mFlinger;
4915 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004916 };
4917
4918 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4919 auto parent = layerHandle->owner.promote();
4920
chaviw7206d492017-11-10 16:16:12 -08004921 if (parent == nullptr || parent->isPendingRemoval()) {
4922 ALOGE("captureLayers called with a removed parent");
4923 return NAME_NOT_FOUND;
4924 }
4925
Robert Carr578038f2018-03-09 12:25:24 -08004926 const int uid = IPCThreadState::self()->getCallingUid();
4927 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4928 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4929 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4930 return PERMISSION_DENIED;
4931 }
4932
chaviw7206d492017-11-10 16:16:12 -08004933 Rect crop(sourceCrop);
4934 if (sourceCrop.width() <= 0) {
4935 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07004936 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08004937 }
4938
4939 if (sourceCrop.height() <= 0) {
4940 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07004941 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08004942 }
4943
4944 int32_t reqWidth = crop.width() * frameScale;
4945 int32_t reqHeight = crop.height() * frameScale;
4946
Robert Carr578038f2018-03-09 12:25:24 -08004947 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004948
Robert Carr578038f2018-03-09 12:25:24 -08004949 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004950 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4951 if (!layer->isVisible()) {
4952 return;
Robert Carr578038f2018-03-09 12:25:24 -08004953 } else if (childrenOnly && layer == parent.get()) {
4954 return;
chaviwa76b2712017-09-20 12:02:26 -07004955 }
4956 visitor(layer);
4957 });
4958 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004959 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004960}
4961
4962status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4963 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004964 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004965 bool useIdentityTransform) {
4966 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004967
Iris Chang7501ed62018-04-30 14:45:42 +08004968 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004969
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004970 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4971 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4972 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4973 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004974
4975 // This mutex protects syncFd and captureResult for communication of the return values from the
4976 // main thread back to this Binder thread
4977 std::mutex captureMutex;
4978 std::condition_variable captureCondition;
4979 std::unique_lock<std::mutex> captureLock(captureMutex);
4980 int syncFd = -1;
4981 std::optional<status_t> captureResult;
4982
Robert Carr03480e22018-01-04 16:02:06 -08004983 const int uid = IPCThreadState::self()->getCallingUid();
4984 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4985
Dominik Laskowski8c001672018-05-30 16:52:06 -07004986 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004987 // If there is a refresh pending, bug out early and tell the binder thread to try again
4988 // after the refresh.
4989 if (mRefreshPending) {
4990 ATRACE_NAME("Skipping screenshot for now");
4991 std::unique_lock<std::mutex> captureLock(captureMutex);
4992 captureResult = std::make_optional<status_t>(EAGAIN);
4993 captureCondition.notify_one();
4994 return;
4995 }
4996
4997 status_t result = NO_ERROR;
4998 int fd = -1;
4999 {
5000 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005001 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005002 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5003 useIdentityTransform, forSystem, &fd);
5004 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005005 }
5006
5007 {
5008 std::unique_lock<std::mutex> captureLock(captureMutex);
5009 syncFd = fd;
5010 captureResult = std::make_optional<status_t>(result);
5011 captureCondition.notify_one();
5012 }
5013 });
5014
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005015 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005016 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005017 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005018 while (*captureResult == EAGAIN) {
5019 captureResult.reset();
5020 result = postMessageAsync(message);
5021 if (result != NO_ERROR) {
5022 return result;
5023 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005024 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005025 }
5026 result = *captureResult;
5027 }
5028
5029 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005030 sync_wait(syncFd, -1);
5031 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005032 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005033
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005034 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005035}
5036
chaviwa76b2712017-09-20 12:02:26 -07005037void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5038 TraverseLayersFunction traverseLayers, bool yswap,
5039 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005040 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005041
Lloyd Pique144e1162017-12-20 16:44:52 -08005042 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005043
5044 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005045 const auto raWidth = renderArea.getWidth();
5046 const auto raHeight = renderArea.getHeight();
5047
5048 const auto reqWidth = renderArea.getReqWidth();
5049 const auto reqHeight = renderArea.getReqHeight();
5050 Rect sourceCrop = renderArea.getSourceCrop();
5051
Iris Chang7501ed62018-04-30 14:45:42 +08005052 bool filtering = false;
5053 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5054 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5055 static_cast<int32_t>(reqHeight) != raWidth;
5056 } else {
5057 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5058 static_cast<int32_t>(reqHeight) != raHeight;
5059 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005060
Dan Stozac1879002014-05-22 15:59:05 -07005061 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005062 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005063 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005064 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005065 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
Peiyong Linefefaac2018-08-17 12:27:51 -07005066 ui::Transform tr;
Iris Chang7501ed62018-04-30 14:45:42 +08005067 uint32_t flags = 0x00;
5068 switch (mPrimaryDisplayOrientation) {
5069 case DisplayState::eOrientation90:
Peiyong Linefefaac2018-08-17 12:27:51 -07005070 flags = ui::Transform::ROT_90;
Iris Chang7501ed62018-04-30 14:45:42 +08005071 break;
5072 case DisplayState::eOrientation180:
Peiyong Linefefaac2018-08-17 12:27:51 -07005073 flags = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005074 break;
5075 case DisplayState::eOrientation270:
Peiyong Linefefaac2018-08-17 12:27:51 -07005076 flags = ui::Transform::ROT_270;
Iris Chang7501ed62018-04-30 14:45:42 +08005077 break;
5078 }
5079 tr.set(flags, raWidth, raHeight);
5080 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005081 }
5082
5083 // ensure that sourceCrop is inside screen
5084 if (sourceCrop.left < 0) {
5085 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5086 }
chaviwa76b2712017-09-20 12:02:26 -07005087 if (sourceCrop.right > raWidth) {
5088 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005089 }
5090 if (sourceCrop.top < 0) {
5091 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5092 }
chaviwa76b2712017-09-20 12:02:26 -07005093 if (sourceCrop.bottom > raHeight) {
5094 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005095 }
5096
Chia-I Wu36574d92018-05-16 10:54:36 -07005097 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5098 engine.setOutputDataSpace(Dataspace::SRGB);
5099 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005100
Mathias Agopian180f10d2013-04-10 22:55:41 -07005101 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005102 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005103
Peiyong Linefefaac2018-08-17 12:27:51 -07005104 ui::Transform::orientation_flags rotation = renderArea.getRotationFlags();
Iris Chang7501ed62018-04-30 14:45:42 +08005105 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5106 // convert hw orientation into flag presentation
5107 // here inverse transform needed
5108 uint8_t hw_rot_90 = 0x00;
5109 uint8_t hw_flip_hv = 0x00;
5110 switch (mPrimaryDisplayOrientation) {
5111 case DisplayState::eOrientation90:
Peiyong Linefefaac2018-08-17 12:27:51 -07005112 hw_rot_90 = ui::Transform::ROT_90;
5113 hw_flip_hv = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005114 break;
5115 case DisplayState::eOrientation180:
Peiyong Linefefaac2018-08-17 12:27:51 -07005116 hw_flip_hv = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005117 break;
5118 case DisplayState::eOrientation270:
Peiyong Linefefaac2018-08-17 12:27:51 -07005119 hw_rot_90 = ui::Transform::ROT_90;
Iris Chang7501ed62018-04-30 14:45:42 +08005120 break;
5121 }
5122
5123 // transform flags operation
5124 // 1) flip H V if both have ROT_90 flag
5125 // 2) XOR these flags
Peiyong Linefefaac2018-08-17 12:27:51 -07005126 uint8_t rotation_rot_90 = rotation & ui::Transform::ROT_90;
5127 uint8_t rotation_flip_hv = rotation & ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005128 if (rotation_rot_90 & hw_rot_90) {
Peiyong Linefefaac2018-08-17 12:27:51 -07005129 rotation_flip_hv = (~rotation_flip_hv) & ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005130 }
Peiyong Linefefaac2018-08-17 12:27:51 -07005131 rotation = static_cast<ui::Transform::orientation_flags>
Iris Chang7501ed62018-04-30 14:45:42 +08005132 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5133 }
5134
Mathias Agopian180f10d2013-04-10 22:55:41 -07005135 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005136 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005137 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005138 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005139
chaviw50da5042018-04-09 13:49:37 -07005140 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005141 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005142 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005143
chaviwa76b2712017-09-20 12:02:26 -07005144 traverseLayers([&](Layer* layer) {
5145 if (filtering) layer->setFiltering(true);
David Sodmanca10ed22018-04-16 14:10:25 -07005146 layer->drawNow(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005147 if (filtering) layer->setFiltering(false);
5148 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005149}
5150
chaviwa76b2712017-09-20 12:02:26 -07005151status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5152 TraverseLayersFunction traverseLayers,
5153 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005154 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005155 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005156 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005157 ATRACE_CALL();
5158
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005159 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005160
5161 traverseLayers([&](Layer* layer) {
5162 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5163 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005164
Robert Carr03480e22018-01-04 16:02:06 -08005165 // We allow the system server to take screenshots of secure layers for
5166 // use in situations like the Screen-rotation animation and place
5167 // the impetus on WindowManager to not persist them.
5168 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005169 ALOGW("FB is protected: PERMISSION_DENIED");
5170 return PERMISSION_DENIED;
5171 }
5172
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005173 // this binds the given EGLImage as a framebuffer for the
5174 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005175 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005176 if (bufferBond.getStatus() != NO_ERROR) {
5177 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005178 return INVALID_OPERATION;
5179 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005180
Dan Stozaabcda352017-06-01 14:37:39 -07005181 // this will in fact render into our dequeued buffer
5182 // via an FBO, which means we didn't have to create
5183 // an EGLSurface and therefore we're not
5184 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005185 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005186
Dan Stozaabcda352017-06-01 14:37:39 -07005187 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005188 getRenderEngine().finish();
5189 *outSyncFd = -1;
5190
chaviwa76b2712017-09-20 12:02:26 -07005191 const auto reqWidth = renderArea.getReqWidth();
5192 const auto reqHeight = renderArea.getReqHeight();
5193
Dan Stozaabcda352017-06-01 14:37:39 -07005194 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5195 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005196 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005197 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005198 } else {
5199 base::unique_fd syncFd = getRenderEngine().flush();
5200 if (syncFd < 0) {
5201 getRenderEngine().finish();
5202 }
5203 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005204 }
5205
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005206 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005207}
5208
Mathias Agopiand5556842013-09-19 17:08:37 -07005209void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005210 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005211 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005212 for (size_t y = 0; y < h; y++) {
5213 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5214 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005215 if (p[x] != 0xFF000000) return;
5216 }
5217 }
chaviwa76b2712017-09-20 12:02:26 -07005218 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005219
Robert Carr2047fae2016-11-28 14:09:09 -08005220 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005221 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005222 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005223 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5224 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5225 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5226 static_cast<float>(state.color.a));
5227 i++;
5228 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005229 }
5230}
5231
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005232// ---------------------------------------------------------------------------
5233
Dan Stoza412903f2017-04-27 13:42:17 -07005234void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5235 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005236}
5237
Dan Stoza412903f2017-04-27 13:42:17 -07005238void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5239 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005240}
5241
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005242void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5243 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005244 const LayerVector::Visitor& visitor) {
5245 // We loop through the first level of layers without traversing,
5246 // as we need to interpret min/max layer Z in the top level Z space.
5247 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005248 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005249 continue;
5250 }
5251 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005252 // relative layers are traversed in Layer::traverseInZOrder
5253 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005254 continue;
5255 }
5256 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005257 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005258 return;
5259 }
chaviwa76b2712017-09-20 12:02:26 -07005260 if (!layer->isVisible()) {
5261 return;
5262 }
5263 visitor(layer);
5264 });
5265 }
5266}
5267
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005268}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005269
Lloyd Pique074e8122018-07-26 12:57:23 -07005270
Mathias Agopian3f844832013-08-07 21:24:32 -07005271#if defined(__gl_h_)
5272#error "don't include gl/gl.h in this file"
5273#endif
5274
5275#if defined(__gl2_h_)
5276#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005277#endif