blob: 2538945f4d4501221ef1cbff197b988e7bdabd4d [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 {
Dan Stozae3344402018-08-20 19:53:42 +00001092 IPCThreadState* ipc = IPCThreadState::self();
1093 const int pid = ipc->getCallingPid();
1094 const int uid = ipc->getCallingUid();
1095 if ((uid != AID_SHELL) &&
1096 !PermissionCache::checkPermission(sDump, pid, uid)) {
1097 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1098 return PERMISSION_DENIED;
1099 }
1100
Kalle Raitaa099a242017-01-11 11:17:29 -08001101 // Try to acquire a lock for 1s, fail gracefully
1102 const status_t err = mStateLock.timedLock(s2ns(1));
1103 const bool locked = (err == NO_ERROR);
1104 if (!locked) {
1105 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1106 return TIMED_OUT;
1107 }
1108
1109 outLayers->clear();
1110 mCurrentState.traverseInZOrder([&](Layer* layer) {
1111 outLayers->push_back(layer->getLayerDebugInfo());
1112 });
1113
1114 mStateLock.unlock();
1115 return NO_ERROR;
1116}
1117
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001118// ----------------------------------------------------------------------------
1119
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001120sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1121 ISurfaceComposer::VsyncSource vsyncSource) {
1122 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1123 return mSFEventThread->createEventConnection();
1124 } else {
1125 return mEventThread->createEventConnection();
1126 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001127}
1128
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001129// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001130
1131void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001132 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001133}
1134
1135void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001136 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001137}
1138
1139void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001140 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001141}
1142
1143void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001144 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001145 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001146}
1147
1148status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001149 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001150 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001151}
1152
1153status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001154 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001155 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001156 if (res == NO_ERROR) {
1157 msg->wait();
1158 }
1159 return res;
1160}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001161
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001162void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001163 do {
1164 waitForEvent();
1165 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001166}
1167
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001168void SurfaceFlinger::enableHardwareVsync() {
1169 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001170 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001171 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001172 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001173 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001174 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001175}
1176
Jesse Hall948fe0c2013-10-14 12:56:09 -07001177void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001178 Mutex::Autolock _l(mHWVsyncLock);
1179
Jesse Hall948fe0c2013-10-14 12:56:09 -07001180 if (makeAvailable) {
1181 mHWVsyncAvailable = true;
1182 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001183 // Hardware vsync is not currently available, so abort the resync
1184 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001185 return;
1186 }
1187
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001188 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1189 if (!getHwComposer().isConnected(displayId)) {
1190 return;
1191 }
1192
1193 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001194 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001195
Lloyd Pique41be5d22018-06-21 13:11:48 -07001196 mPrimaryDispSync->reset();
1197 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001198
1199 if (!mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001200 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001201 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001202 mPrimaryHWVsyncEnabled = true;
1203 }
1204}
1205
Jesse Hall948fe0c2013-10-14 12:56:09 -07001206void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001207 Mutex::Autolock _l(mHWVsyncLock);
1208 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001209 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001210 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001211 mPrimaryHWVsyncEnabled = false;
1212 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001213 if (makeUnavailable) {
1214 mHWVsyncAvailable = false;
1215 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001216}
1217
Tim Murray4a4e4a22016-04-19 16:29:23 +00001218void SurfaceFlinger::resyncWithRateLimit() {
1219 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001220
1221 // No explicit locking is needed here since EventThread holds a lock while calling this method
1222 static nsecs_t sLastResyncAttempted = 0;
1223 const nsecs_t now = systemTime();
1224 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001225 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001226 }
Dan Stoza57164302017-05-08 14:03:54 -07001227 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001228}
1229
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001230void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1231 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001232 ATRACE_NAME("SF onVsync");
1233
Steven Thomas3cfac282017-02-06 12:29:30 -08001234 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001235 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001236 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001237 return;
1238 }
1239
1240 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001241 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001242 return;
1243 }
1244
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001245 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1246 // For now, we don't do anything with external display vsyncs.
1247 return;
1248 }
1249
Jamie Gennisd1700752013-10-14 12:22:52 -07001250 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001251
Jamie Gennisd1700752013-10-14 12:22:52 -07001252 { // Scope for the lock
1253 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001254 if (mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001255 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001256 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001257 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001258
1259 if (needsHwVsync) {
1260 enableHardwareVsync();
1261 } else {
1262 disableHardwareVsync(false);
1263 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001264}
1265
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001266void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001267 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1268 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001269}
1270
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001271void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001272 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001273 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001274 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001275
Lloyd Piqueba04e622017-12-14 17:11:26 -08001276 // Ignore events that do not have the right sequenceId.
1277 if (sequenceId != getBE().mComposerSequenceId) {
1278 return;
1279 }
1280
Steven Thomasb02664d2017-07-26 18:48:28 -07001281 // Only lock if we're not on the main thread. This function is normally
1282 // called on a hwbinder thread, but for the primary display it's called on
1283 // the main thread with the state lock already held, so don't attempt to
1284 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001285 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001286
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001287 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001288
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001289 if (std::this_thread::get_id() == mMainThreadId) {
1290 // Process all pending hot plug events immediately if we are on the main thread.
1291 processDisplayHotplugEventsLocked();
1292 }
1293
Lloyd Piqueba04e622017-12-14 17:11:26 -08001294 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001295}
1296
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001297void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001298 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001299 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001300 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001301 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001302 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001303}
1304
Dan Stoza9e56aa02015-11-02 13:00:03 -08001305void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001306 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001307 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001308 getHwComposer().setVsyncEnabled(disp,
1309 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001310}
1311
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001312// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001313void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001314 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001315 // Clear the drawing state so that the logic inside of
1316 // handleTransactionLocked will fire. It will determine the delta between
1317 // mCurrentState and mDrawingState and re-apply all changes when we make the
1318 // transition.
1319 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001320 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001321 mDisplays.clear();
1322}
1323
Steven Thomas050b2c82017-03-06 11:45:16 -08001324void SurfaceFlinger::updateVrFlinger() {
1325 if (!mVrFlinger)
1326 return;
1327 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001328 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001329 return;
1330 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001331
David Sodman105b7dc2017-11-04 20:28:14 -07001332 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001333 ALOGE("Vr flinger is only supported for remote hardware composer"
1334 " service connections. Ignoring request to transition to vr"
1335 " flinger.");
1336 mVrFlingerRequestsDisplay = false;
1337 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001338 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001339
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001340 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001341
Steven Thomas0123ac62018-07-12 11:32:34 -07001342 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001343 LOG_ALWAYS_FATAL_IF(!display);
1344 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001345 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1346 // called below. Clear the reference now so we don't accidentally use it
1347 // later.
1348 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001349
Steven Thomasb02664d2017-07-26 18:48:28 -07001350 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001351 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001352 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001353
Steven Thomasb02664d2017-07-26 18:48:28 -07001354 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001355 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001356 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1357 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001358 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001359
David Sodman105b7dc2017-11-04 20:28:14 -07001360 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1361 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001362
1363 if (vrFlingerRequestsDisplay) {
1364 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001365 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001366
1367 mVisibleRegionsDirty = true;
1368 invalidateHwcGeometry();
1369
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001370 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001371 display = getDefaultDisplayDeviceLocked();
1372 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001373 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001374
Steven Thomasb02664d2017-07-26 18:48:28 -07001375 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001376 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001377 const nsecs_t period = activeConfig->getVsyncPeriod();
1378 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001379
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001380 // The present fences returned from vr_hwc are not an accurate
1381 // representation of vsync times.
Lloyd Pique41be5d22018-06-21 13:11:48 -07001382 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1383 !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001384
Steven Thomasb02664d2017-07-26 18:48:28 -07001385 // Use phase of 0 since phase is not known.
1386 // Use latency of 0, which will snap to the ideal latency.
1387 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001388
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001389 resyncToHardwareVsync(false);
1390
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001391 android_atomic_or(1, &mRepaintEverything);
1392 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001393}
1394
Mathias Agopian4fec8732012-06-29 14:12:52 -07001395void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001396 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001397 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001398 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001399 bool frameMissed = !mHadClientComposition &&
1400 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001401 (mPreviousPresentFence->getSignalTime() ==
1402 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001403 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001404 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001405 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001406 mTimeStats.incrementMissedFrames();
1407 if (mPropagateBackpressure) {
1408 signalLayerUpdate();
1409 break;
1410 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001411 }
Dan Stoza50182882016-07-08 12:02:20 -07001412
Steven Thomas050b2c82017-03-06 11:45:16 -08001413 // Now that we're going to make it to the handleMessageTransaction()
1414 // call below it's safe to call updateVrFlinger(), which will
1415 // potentially trigger a display handoff.
1416 updateVrFlinger();
1417
Dan Stoza6b9454d2014-11-07 16:00:59 -08001418 bool refreshNeeded = handleMessageTransaction();
1419 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001420 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001421 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001422 // Signal a refresh if a transaction modified the window state,
1423 // a new buffer was latched, or if HWC has requested a full
1424 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001425 signalRefresh();
1426 }
1427 break;
1428 }
1429 case MessageQueue::REFRESH: {
1430 handleMessageRefresh();
1431 break;
1432 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001433 }
1434}
1435
Dan Stoza6b9454d2014-11-07 16:00:59 -08001436bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001437 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001438 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001439 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001440 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001441 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001442 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001443}
1444
Mathias Agopian4fec8732012-06-29 14:12:52 -07001445void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001446 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001447
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001448 mRefreshPending = false;
1449
David Sodmanfa9b2af2017-12-24 13:28:59 -08001450 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
David Sodman2b406362017-12-15 13:33:47 -08001451 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001452 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001453 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001454 for (const auto& [token, display] : mDisplays) {
1455 beginFrame(display);
1456 prepareFrame(display);
1457 doDebugFlashRegions(display, repaintEverything);
1458 doComposition(display, repaintEverything);
1459 }
1460
Adrian Roos1e1a1282017-11-01 19:05:31 +01001461 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001462 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001463
1464 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001465 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001466
Dan Stozabfbffeb2016-07-21 14:49:33 -07001467 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001468 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001469 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001470 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001471 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001472
Jorim Jaggi90535212018-05-23 23:44:06 +02001473 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001474
Dan Stoza9e56aa02015-11-02 13:00:03 -08001475 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001476}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001477
David Sodmanfa9b2af2017-12-24 13:28:59 -08001478
1479bool SurfaceFlinger::handleMessageInvalidate() {
1480 ATRACE_CALL();
1481 return handlePageFlip();
1482}
1483
David Sodman79bba0e2018-08-05 18:07:49 -07001484void SurfaceFlinger::calculateWorkingSet() {
1485 ATRACE_CALL();
1486 ALOGV(__FUNCTION__);
1487
David Sodman79bba0e2018-08-05 18:07:49 -07001488 // build the h/w work list
1489 if (CC_UNLIKELY(mGeometryInvalid)) {
1490 mGeometryInvalid = false;
1491 for (const auto& [token, display] : mDisplays) {
1492 const auto displayId = display->getId();
1493 if (displayId >= 0) {
1494 const Vector<sp<Layer>>& currentLayers(
1495 display->getVisibleLayersSortedByZ());
1496 for (size_t i = 0; i < currentLayers.size(); i++) {
1497 const auto& layer = currentLayers[i];
1498
1499 if (!layer->hasHwcLayer(displayId)) {
1500 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1501 layer->forceClientComposition(displayId);
1502 continue;
1503 }
1504 }
1505
1506 layer->setGeometry(display, i);
1507 if (mDebugDisableHWC || mDebugRegion) {
1508 layer->forceClientComposition(displayId);
1509 }
1510 }
1511 }
1512 }
1513 }
1514
1515 // Set the per-frame data
1516 for (const auto& [token, display] : mDisplays) {
1517 const auto displayId = display->getId();
1518 if (displayId < 0) {
1519 continue;
1520 }
1521
1522 if (mDrawingState.colorMatrixChanged) {
1523 display->setColorTransform(mDrawingState.colorMatrix);
1524 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1525 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1526 "display %d: %d", displayId, result);
1527 }
1528 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1529 if (layer->isHdrY410()) {
1530 layer->forceClientComposition(displayId);
1531 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1532 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1533 !display->hasHDR10Support()) {
1534 layer->forceClientComposition(displayId);
1535 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1536 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1537 !display->hasHLGSupport()) {
1538 layer->forceClientComposition(displayId);
1539 }
1540
1541 if (layer->getForceClientComposition(displayId)) {
1542 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1543 layer->setCompositionType(displayId, HWC2::Composition::Client);
1544 continue;
1545 }
1546
1547 layer->setPerFrameData(display);
1548 }
1549
1550 if (hasWideColorDisplay) {
1551 ColorMode colorMode;
1552 Dataspace dataSpace;
1553 RenderIntent renderIntent;
1554 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1555 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1556 }
1557 }
1558
1559 mDrawingState.colorMatrixChanged = false;
David Sodman79bba0e2018-08-05 18:07:49 -07001560}
1561
David Sodmanfa9b2af2017-12-24 13:28:59 -08001562void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001563{
1564 // is debugging enabled
1565 if (CC_LIKELY(!mDebugRegion))
1566 return;
1567
David Sodmanfa9b2af2017-12-24 13:28:59 -08001568 if (display->isPoweredOn()) {
1569 // transform the dirty region into this screen's coordinate space
1570 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1571 if (!dirtyRegion.isEmpty()) {
1572 // redraw the whole screen
1573 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001574
David Sodmanfa9b2af2017-12-24 13:28:59 -08001575 // and draw the dirty region
1576 const int32_t height = display->getHeight();
1577 auto& engine(getRenderEngine());
1578 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001579
David Sodmanfa9b2af2017-12-24 13:28:59 -08001580 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001581 }
1582 }
1583
David Sodmanfa9b2af2017-12-24 13:28:59 -08001584 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001585
1586 if (mDebugRegion > 1) {
1587 usleep(mDebugRegion * 1000);
1588 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001589
David Sodmanfa9b2af2017-12-24 13:28:59 -08001590 if (display->isPoweredOn()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001591 status_t result = display->prepareFrame(*getBE().mHwc);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001592 ALOGE_IF(result != NO_ERROR,
1593 "prepareFrame for display %d failed:"
1594 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001595 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001596 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001597}
1598
Adrian Roos1e1a1282017-11-01 19:05:31 +01001599void SurfaceFlinger::doTracing(const char* where) {
1600 ATRACE_CALL();
1601 ATRACE_NAME(where);
1602 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001603 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001604 }
1605}
1606
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001607void SurfaceFlinger::logLayerStats() {
1608 ATRACE_CALL();
1609 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001610 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001611 if (display->isPrimary()) {
1612 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001613 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001614 }
1615 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001616
1617 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001618 }
1619}
1620
David Sodman2b406362017-12-15 13:33:47 -08001621void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001622{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001623 ATRACE_CALL();
1624 ALOGV("preComposition");
1625
David Sodman2b406362017-12-15 13:33:47 -08001626 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1627
Mathias Agopiancd60f992012-08-16 16:28:27 -07001628 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001629 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001630 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001631 needExtraInvalidate = true;
1632 }
Robert Carr2047fae2016-11-28 14:09:09 -08001633 });
1634
Mathias Agopiancd60f992012-08-16 16:28:27 -07001635 if (needExtraInvalidate) {
1636 signalLayerUpdate();
1637 }
1638}
1639
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001640void SurfaceFlinger::updateCompositorTiming(
1641 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1642 std::shared_ptr<FenceTime>& presentFenceTime) {
1643 // Update queue of past composite+present times and determine the
1644 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001645 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001646 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001647 while (!getBE().mCompositePresentTimes.empty()) {
1648 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001649 // Cached values should have been updated before calling this method,
1650 // which helps avoid duplicate syscalls.
1651 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1652 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1653 break;
1654 }
1655 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001656 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001657 }
1658
1659 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001660 while (getBE().mCompositePresentTimes.size() > 16) {
1661 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001662 }
1663
Brian Andersond0010582017-03-07 13:20:31 -08001664 setCompositorTimingSnapped(
1665 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1666}
1667
1668void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1669 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001670 // Integer division and modulo round toward 0 not -inf, so we need to
1671 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001672 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001673 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1674 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1675
Brian Andersond0010582017-03-07 13:20:31 -08001676 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1677 if (idealLatency <= 0) {
1678 idealLatency = vsyncInterval;
1679 }
1680
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001681 // Snap the latency to a value that removes scheduling jitter from the
1682 // composition and present times, which often have >1ms of jitter.
1683 // Reducing jitter is important if an app attempts to extrapolate
1684 // something (such as user input) to an accurate diasplay time.
1685 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1686 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001687 nsecs_t bias = vsyncInterval / 2;
1688 int64_t extraVsyncs =
1689 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1690 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1691 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001692
David Sodman99974d22017-11-28 12:04:33 -08001693 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1694 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1695 getBE().mCompositorTiming.interval = vsyncInterval;
1696 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001697}
1698
David Sodman2b406362017-12-15 13:33:47 -08001699void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001700{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001701 ATRACE_CALL();
1702 ALOGV("postComposition");
1703
Brian Anderson3546a3f2016-07-14 11:51:14 -07001704 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001705 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001706 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001707 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001708 }
1709
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001710 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001711 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001712
David Sodman73beded2017-11-15 11:56:06 -08001713 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001714 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001715 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001716 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001717 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001718 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001719 } else {
1720 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1721 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001722
David Sodman73beded2017-11-15 11:56:06 -08001723 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001724 mPreviousPresentFence =
1725 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1726 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001727 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001728
Lloyd Pique41be5d22018-06-21 13:11:48 -07001729 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1730 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001731
David Sodman2b406362017-12-15 13:33:47 -08001732 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001733 // when we started doing work for this frame, but that should be okay
1734 // since updateCompositorTiming has snapping logic.
1735 updateCompositorTiming(
David Sodman2b406362017-12-15 13:33:47 -08001736 vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001737 CompositorTiming compositorTiming;
1738 {
David Sodman99974d22017-11-28 12:04:33 -08001739 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1740 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001741 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001742
Robert Carr2047fae2016-11-28 14:09:09 -08001743 mDrawingState.traverseInZOrder([&](Layer* layer) {
1744 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001745 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001746 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001747 recordBufferingStats(layer->getName().string(),
1748 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001749 }
Robert Carr2047fae2016-11-28 14:09:09 -08001750 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001751
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001752 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001753 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001754 enableHardwareVsync();
1755 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001756 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001757 }
1758 }
1759
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001760 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001761 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001762 enableHardwareVsync();
1763 }
1764 }
1765
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001766 if (mAnimCompositionPending) {
1767 mAnimCompositionPending = false;
1768
Brian Anderson4e606e32017-03-16 15:34:57 -07001769 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001770 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001771 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001772 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001773 // The HWC doesn't support present fences, so use the refresh
1774 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001775 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001776 mAnimFrameTracker.setActualPresentTime(presentTime);
1777 }
1778 mAnimFrameTracker.advanceFrame();
1779 }
Dan Stozab90cf072015-03-05 11:05:59 -08001780
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001781 mTimeStats.incrementTotalFrames();
1782 if (mHadClientComposition) {
1783 mTimeStats.incrementClientCompositionFrames();
1784 }
1785
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001786 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001787 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001788 return;
1789 }
1790
1791 nsecs_t currentTime = systemTime();
1792 if (mHasPoweredOff) {
1793 mHasPoweredOff = false;
1794 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001795 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001796 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001797 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1798 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001799 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001800 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001801 }
David Sodman4a36e932017-11-07 14:29:47 -08001802 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001803 }
David Sodman4a36e932017-11-07 14:29:47 -08001804 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001805
1806 {
1807 std::lock_guard lock(mTexturePoolMutex);
1808 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1809 if (refillCount > 0) {
1810 const size_t offset = mTexturePool.size();
1811 mTexturePool.resize(mTexturePoolSize);
1812 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1813 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1814 }
1815 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001816}
1817
1818void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001819 ATRACE_CALL();
1820 ALOGV("rebuildLayerStacks");
1821
Mathias Agopiancd60f992012-08-16 16:28:27 -07001822 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001823 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001824 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001825 mVisibleRegionsDirty = false;
1826 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001827
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001828 for (const auto& pair : mDisplays) {
1829 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001830 Region opaqueRegion;
1831 Region dirtyRegion;
1832 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001833 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001834 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001835 const Rect bounds = display->getBounds();
1836 if (display->isPoweredOn()) {
1837 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001838
Jeff Sharkey76488112017-02-27 14:15:18 -07001839 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001840 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001841 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001842 Region drawRegion(tr.transform(
1843 layer->visibleNonTransparentRegion));
1844 drawRegion.andSelf(bounds);
1845 if (!drawRegion.isEmpty()) {
1846 layersSortedByZ.add(layer);
1847 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001848 // Clear out the HWC layer if this layer was
1849 // previously visible, but no longer is
1850 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001851 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001852 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001853 // WM changes display->layerStack upon sleep/awake.
1854 // Here we make sure we delete the HWC layers even if
1855 // WM changed their layer stack.
1856 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001857 }
1858
1859 // If a layer is not going to get a release fence because
1860 // it is invisible, but it is also going to release its
1861 // old buffer, add it to the list of layers needing
1862 // fences.
1863 if (hwcLayerDestroyed) {
1864 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1865 mLayersWithQueuedFrames.cend(), layer);
1866 if (found != mLayersWithQueuedFrames.cend()) {
1867 layersNeedingFences.add(layer);
1868 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001869 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001870 });
1871 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001872 display->setVisibleLayersSortedByZ(layersSortedByZ);
1873 display->setLayersNeedingFences(layersNeedingFences);
1874 display->undefinedRegion.set(bounds);
1875 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1876 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001877 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001878 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001879}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001880
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001881// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001882// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001883// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001884// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001885// The returned HDR data space is one of
1886// - Dataspace::UNKNOWN
1887// - Dataspace::BT2020_HLG
1888// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001889Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1890 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001891 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001892 *outHdrDataSpace = Dataspace::UNKNOWN;
1893
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001894 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001895 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001896 case Dataspace::V0_SCRGB:
1897 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001898 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001899 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001900 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001901 case Dataspace::BT2020_PQ:
1902 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001903 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001904 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001905 case Dataspace::BT2020_HLG:
1906 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001907 // When there's mixed PQ content and HLG content, we set the HDR
1908 // data space to be BT2020_PQ and convert HLG to PQ.
1909 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1910 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001911 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001912 break;
1913 default:
1914 break;
1915 }
Romain Guy54f154a2017-10-24 21:40:32 +01001916 }
1917
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001918 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001919}
1920
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001921// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001922void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1923 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001924 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1925 *outMode = ColorMode::NATIVE;
1926 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001927 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001928 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001929 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001930
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001931 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001932 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001933
Peiyong Lindfde5112018-06-05 10:58:41 -07001934 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001935 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001936 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001937 if (isHdr) {
1938 bestDataSpace = hdrDataSpace;
1939 }
1940
Chia-I Wu0d711262018-05-21 15:19:35 -07001941 RenderIntent intent;
1942 switch (mDisplayColorSetting) {
1943 case DisplayColorSetting::MANAGED:
1944 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001945 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001946 break;
1947 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001948 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001949 break;
1950 default: // vendor display color setting
1951 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1952 break;
1953 }
Chia-I Wube02ec02018-05-18 10:59:36 -07001954
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001955 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001956}
1957
David Sodmanfa9b2af2017-12-24 13:28:59 -08001958void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08001959{
David Sodmanfa9b2af2017-12-24 13:28:59 -08001960 bool dirty = !display->getDirtyRegion(false).isEmpty();
1961 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
1962 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08001963
David Sodmanfa9b2af2017-12-24 13:28:59 -08001964 // If nothing has changed (!dirty), don't recompose.
1965 // If something changed, but we don't currently have any visible layers,
1966 // and didn't when we last did a composition, then skip it this time.
1967 // The second rule does two things:
1968 // - When all layers are removed from a display, we'll emit one black
1969 // frame, then nothing more until we get new layers.
1970 // - When a display is created with a private layer stack, we won't
1971 // emit any black frames until a layer is added to the layer stack.
1972 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08001973
David Sodmanfa9b2af2017-12-24 13:28:59 -08001974 ALOGV_IF(displayDevice->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1975 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1976 mustRecompose ? "doing" : "skipping",
1977 dirty ? "+" : "-",
1978 empty ? "+" : "-",
1979 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08001980
David Sodmanfa9b2af2017-12-24 13:28:59 -08001981 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08001982
David Sodmanfa9b2af2017-12-24 13:28:59 -08001983 if (mustRecompose) {
1984 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08001985 }
1986}
1987
David Sodmanfa9b2af2017-12-24 13:28:59 -08001988void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08001989{
David Sodmanfa9b2af2017-12-24 13:28:59 -08001990 if (!display->isPoweredOn()) {
1991 return;
David Sodman2b406362017-12-15 13:33:47 -08001992 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001993
1994 status_t result = display->prepareFrame(*getBE().mHwc);
1995 ALOGE_IF(result != NO_ERROR,
1996 "prepareFrame for display %d failed:"
1997 " %d (%s)",
1998 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08001999}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002000
David Sodmanfa9b2af2017-12-24 13:28:59 -08002001void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002002 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002003 ALOGV("doComposition");
2004
David Sodmanfa9b2af2017-12-24 13:28:59 -08002005 if (display->isPoweredOn()) {
2006 // transform the dirty region into this screen's coordinate space
2007 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002008
David Sodmanfa9b2af2017-12-24 13:28:59 -08002009 // repaint the framebuffer (if needed)
2010 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002011
David Sodmanfa9b2af2017-12-24 13:28:59 -08002012 display->dirtyRegion.clear();
2013 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002014 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002015 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002016}
2017
David Sodmanfa9b2af2017-12-24 13:28:59 -08002018void SurfaceFlinger::postFrame()
2019{
2020 // |mStateLock| not needed as we are on the main thread
2021 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2022 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2023 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2024 logFrameStats();
2025 }
2026 }
2027}
2028
2029void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002030{
Mathias Agopian841cde52012-03-01 15:44:37 -08002031 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002032 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002033
David Sodmanfa9b2af2017-12-24 13:28:59 -08002034 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002035
David Sodmanfa9b2af2017-12-24 13:28:59 -08002036 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002037 const auto displayId = display->getId();
2038 if (displayId >= 0) {
2039 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002040 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002041 display->onSwapBuffersCompleted();
2042 display->makeCurrent();
2043 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002044 sp<Fence> releaseFence = Fence::NO_FENCE;
2045
Chia-I Wu7b549592017-11-15 09:14:57 -08002046 // The layer buffer from the previous frame (if any) is released
2047 // by HWC only when the release fence from this frame (if any) is
2048 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002049 auto hwcLayer = layer->getHwcLayer(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002050 if (displayId >= 0) {
2051 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
2052 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002053
2054 // If the layer was client composited in the previous frame, we
2055 // need to merge with the previous client target acquire fence.
2056 // Since we do not track that, always merge with the current
2057 // client target acquire fence when it is available, even though
2058 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002059 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002060 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002061 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002062 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002063
David Sodmanb8af7922017-12-21 15:17:55 -08002064 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002065 }
Chia-I Wu83806892017-11-16 10:50:20 -08002066
2067 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002068 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002069 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002070 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002071 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002072 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002073 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002074 }
2075 }
2076
Dominik Laskowski7e045462018-05-30 13:02:02 -07002077 if (displayId >= 0) {
2078 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002079 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002080 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002081}
2082
Mathias Agopian87baae12012-07-31 12:38:26 -07002083void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002084{
Mathias Agopian841cde52012-03-01 15:44:37 -08002085 ATRACE_CALL();
2086
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002087 // here we keep a copy of the drawing state (that is the state that's
2088 // going to be overwritten by handleTransactionLocked()) outside of
2089 // mStateLock so that the side-effects of the State assignment
2090 // don't happen with mStateLock held (which can cause deadlocks).
2091 State drawingState(mDrawingState);
2092
Mathias Agopianca4d3602011-05-19 15:38:14 -07002093 Mutex::Autolock _l(mStateLock);
2094 const nsecs_t now = systemTime();
2095 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002096
Mathias Agopianca4d3602011-05-19 15:38:14 -07002097 // Here we're guaranteed that some transaction flags are set
2098 // so we can call handleTransactionLocked() unconditionally.
2099 // We call getTransactionFlags(), which will also clear the flags,
2100 // with mStateLock held to guarantee that mCurrentState won't change
2101 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002102
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002103 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002104 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002105 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002106
Mathias Agopianca4d3602011-05-19 15:38:14 -07002107 mLastTransactionTime = systemTime() - now;
2108 mDebugInTransaction = 0;
2109 invalidateHwcGeometry();
2110 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002111}
2112
Dominik Laskowski7e045462018-05-30 13:02:02 -07002113DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002114 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002115 // Figure out whether the event is for the primary display or an
2116 // external display by matching the Hwc display id against one for a
2117 // connected display. If we did not find a match, we then check what
2118 // displays are not already connected to determine the type. If we don't
2119 // have a connected primary display, we assume the new display is meant to
2120 // be the primary display, and then if we don't have an external display,
2121 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002122 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2123 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002124 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002125 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002126 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002127 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002128 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002129 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002130 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002131 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002132 return DisplayDevice::DISPLAY_EXTERNAL;
2133 }
2134
2135 return DisplayDevice::DISPLAY_ID_INVALID;
2136}
2137
Lloyd Piqueba04e622017-12-14 17:11:26 -08002138void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2139 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002140 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002141 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002142 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002143 continue;
2144 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002145
2146 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2147 ALOGE("External displays are not supported by the vr hardware composer.");
2148 continue;
2149 }
2150
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002151 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002152 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002153 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002154 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002155 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002156
2157 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002158 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002159 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002160 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002161 DisplayDeviceState info;
2162 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002163 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2164 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002165 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002166 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002167 mInterceptor->saveDisplayCreation(info);
2168 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002169 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002170 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002171
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002172 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002173 if (idx >= 0) {
2174 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002175 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002176 mCurrentState.displays.removeItemsAt(idx);
2177 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002178 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002179 }
2180
2181 processDisplayChangesLocked();
2182 }
2183
2184 mPendingHotplugEvents.clear();
2185}
2186
Lloyd Pique99d3da52018-01-22 17:48:03 -08002187sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002188 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002189 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002190 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002191 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002192 HdrCapabilities hdrCapabilities;
2193 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002194
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002195 if (hasWideColorDisplay && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002196 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002197 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002198 if (isWideColorMode(colorMode)) {
2199 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002200 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002201
Dominik Laskowski7e045462018-05-30 13:02:02 -07002202 std::vector<RenderIntent> renderIntents =
2203 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002204 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002205 }
tangrobin6753a022018-08-10 10:58:54 +08002206 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002207
tangrobin6753a022018-08-10 10:58:54 +08002208 if (displayId >= 0) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002209 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2210 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2211 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002212
2213 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2214 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2215
2216 /*
2217 * Create our display's surface
2218 */
2219 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2220 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002221 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002222 renderSurface->setNativeWindow(nativeWindow.get());
2223 const int displayWidth = renderSurface->queryWidth();
2224 const int displayHeight = renderSurface->queryHeight();
2225
2226 // Make sure that composition can never be stalled by a virtual display
2227 // consumer that isn't processing buffers fast enough. We have to do this
2228 // in two places:
2229 // * Here, in case the display is composed entirely by HWC.
2230 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2231 // window's swap interval in eglMakeCurrent, so they'll override the
2232 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002233 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002234 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2235 }
2236
2237 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002238 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002239
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002240 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002241 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2242 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2243 displayHeight, hasWideColorGamut, hdrCapabilities,
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002244 supportedPerFrameMetadata, hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002245
2246 if (maxFrameBufferAcquiredBuffers >= 3) {
2247 nativeWindowSurface->preallocateBuffers();
2248 }
2249
2250 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002251 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2252 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002253 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002254 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002255 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002256 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002257 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002258 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002259 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002260 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002261 display->setLayerStack(state.layerStack);
2262 display->setProjection(state.orientation, state.viewport, state.frame);
2263 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002264
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002265 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002266}
2267
Lloyd Pique347200f2017-12-14 17:00:15 -08002268void SurfaceFlinger::processDisplayChangesLocked() {
2269 // here we take advantage of Vector's copy-on-write semantics to
2270 // improve performance by skipping the transaction entirely when
2271 // know that the lists are identical
2272 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2273 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2274 if (!curr.isIdenticalTo(draw)) {
2275 mVisibleRegionsDirty = true;
2276 const size_t cc = curr.size();
2277 size_t dc = draw.size();
2278
2279 // find the displays that were removed
2280 // (ie: in drawing state but not in current state)
2281 // also handle displays that changed
2282 // (ie: displays that are in both lists)
2283 for (size_t i = 0; i < dc;) {
2284 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2285 if (j < 0) {
2286 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002287 // Call makeCurrent() on the primary display so we can
2288 // be sure that nothing associated with this display
2289 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002290 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2291 defaultDisplay->makeCurrent();
2292 }
2293 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2294 display->disconnect(getHwComposer());
2295 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002296 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2297 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2298 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2299 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2300 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002301 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002302 } else {
2303 // this display is in both lists. see if something changed.
2304 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002305 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002306 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2307 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2308 if (state_binder != draw_binder) {
2309 // changing the surface is like destroying and
2310 // recreating the DisplayDevice, so we just remove it
2311 // from the drawing state, so that it get re-added
2312 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002313 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2314 display->disconnect(getHwComposer());
2315 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002316 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002317 mDrawingState.displays.removeItemsAt(i);
2318 dc--;
2319 // at this point we must loop to the next item
2320 continue;
2321 }
2322
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002323 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002324 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002325 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002326 }
2327 if ((state.orientation != draw[i].orientation) ||
2328 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002329 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002330 }
2331 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002332 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002333 }
2334 }
2335 }
2336 ++i;
2337 }
2338
2339 // find displays that were added
2340 // (ie: in current state but not in drawing state)
2341 for (size_t i = 0; i < cc; i++) {
2342 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2343 const DisplayDeviceState& state(curr[i]);
2344
2345 sp<DisplaySurface> dispSurface;
2346 sp<IGraphicBufferProducer> producer;
2347 sp<IGraphicBufferProducer> bqProducer;
2348 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002349 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002350
Dominik Laskowski7e045462018-05-30 13:02:02 -07002351 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002352 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002353 // Virtual displays without a surface are dormant:
2354 // they have external state (layer stack, projection,
2355 // etc.) but no internal state (i.e. a DisplayDevice).
2356 if (state.surface != nullptr) {
2357 // Allow VR composer to use virtual displays.
2358 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2359 int width = 0;
2360 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2361 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2362 int height = 0;
2363 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2364 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2365 int intFormat = 0;
2366 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2367 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002368 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002369
Dominik Laskowski7e045462018-05-30 13:02:02 -07002370 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2371 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002372 }
2373
2374 // TODO: Plumb requested format back up to consumer
2375
2376 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002377 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002378 bqProducer, bqConsumer,
2379 state.displayName);
2380
2381 dispSurface = vds;
2382 producer = vds;
2383 }
2384 } else {
2385 ALOGE_IF(state.surface != nullptr,
2386 "adding a supported display, but rendering "
2387 "surface is provided (%p), ignoring it",
2388 state.surface.get());
2389
Dominik Laskowski7e045462018-05-30 13:02:02 -07002390 displayId = state.type;
2391 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002392 producer = bqProducer;
2393 }
2394
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002395 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002396 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002397 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002398 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002399 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002400 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002401 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2402 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2403 true);
2404 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2405 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2406 true);
2407 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002408 }
2409 }
2410 }
2411 }
2412 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002413
2414 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002415}
2416
Mathias Agopian87baae12012-07-31 12:38:26 -07002417void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002418{
Dan Stoza7dde5992015-05-22 09:51:44 -07002419 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002420 mCurrentState.traverseInZOrder([](Layer* layer) {
2421 layer->notifyAvailableFrames();
2422 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002423
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002424 /*
2425 * Traversal of the children
2426 * (perform the transaction for each of them if needed)
2427 */
2428
Mathias Agopian3559b072012-08-15 13:46:03 -07002429 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002430 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002431 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002432 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002433
2434 const uint32_t flags = layer->doTransaction(0);
2435 if (flags & Layer::eVisibleRegion)
2436 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002437 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002438 }
2439
2440 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002441 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002442 */
2443
Mathias Agopiane57f2922012-08-09 16:29:12 -07002444 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002445 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002446 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002447 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002448
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002449 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002450 // The transform hint might have changed for some layers
2451 // (either because a display has changed, or because a layer
2452 // as changed).
2453 //
2454 // Walk through all the layers in currentLayers,
2455 // and update their transform hint.
2456 //
2457 // If a layer is visible only on a single display, then that
2458 // display is used to calculate the hint, otherwise we use the
2459 // default display.
2460 //
2461 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2462 // the hint is set before we acquire a buffer from the surface texture.
2463 //
2464 // NOTE: layer transactions have taken place already, so we use their
2465 // drawing state. However, SurfaceFlinger's own transaction has not
2466 // happened yet, so we must use the current state layer list
2467 // (soon to become the drawing state list).
2468 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002469 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002470 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002471 bool first = true;
2472 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002473 // NOTE: we rely on the fact that layers are sorted by
2474 // layerStack first (so we don't have to traverse the list
2475 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002476 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002477 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002478 currentlayerStack = layerStack;
2479 // figure out if this layerstack is mirrored
2480 // (more than one display) if so, pick the default display,
2481 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002482 hintDisplay = nullptr;
2483 for (const auto& [token, display] : mDisplays) {
2484 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2485 if (hintDisplay) {
2486 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002487 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002488 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002489 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002490 }
2491 }
2492 }
2493 }
Chet Haase91d25932013-04-11 15:24:55 -07002494
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002495 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002496 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2497 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002498
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002499 // could be null when this layer is using a layerStack
2500 // that is not visible on any display. Also can occur at
2501 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002502 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002503 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002504
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002505 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002506 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002507 if (hintDisplay) {
2508 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002509 }
Robert Carr2047fae2016-11-28 14:09:09 -08002510
2511 first = false;
2512 });
Mathias Agopian84300952012-11-21 16:02:13 -08002513 }
2514
2515
Mathias Agopian3559b072012-08-15 13:46:03 -07002516 /*
2517 * Perform our own transaction if needed
2518 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002519
2520 if (mLayersAdded) {
2521 mLayersAdded = false;
2522 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002523 mVisibleRegionsDirty = true;
2524 }
2525
2526 // some layers might have been removed, so
2527 // we need to update the regions they're exposing.
2528 if (mLayersRemoved) {
2529 mLayersRemoved = false;
2530 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002531 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002532 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002533 // this layer is not visible anymore
2534 // TODO: we could traverse the tree from front to back and
2535 // compute the actual visible region
2536 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002537 Region visibleReg;
2538 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002539 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002540 }
Robert Carr2047fae2016-11-28 14:09:09 -08002541 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002542 }
2543
2544 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002545
2546 updateCursorAsync();
2547}
2548
2549void SurfaceFlinger::updateCursorAsync()
2550{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002551 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002552 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002553 continue;
2554 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002555
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002556 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2557 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002558 }
2559 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002560}
2561
2562void SurfaceFlinger::commitTransaction()
2563{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002564 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002565 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002566 for (const auto& l : mLayersPendingRemoval) {
2567 recordBufferingStats(l->getName().string(),
2568 l->getOccupancyHistory(true));
2569 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002570 }
2571 mLayersPendingRemoval.clear();
2572 }
2573
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002574 // If this transaction is part of a window animation then the next frame
2575 // we composite should be considered an animation as well.
2576 mAnimCompositionPending = mAnimTransactionPending;
2577
Mathias Agopian4fec8732012-06-29 14:12:52 -07002578 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002579 // clear the "changed" flags in current state
2580 mCurrentState.colorMatrixChanged = false;
2581
Robert Carr1f0a16a2016-10-24 16:27:39 -07002582 mDrawingState.traverseInZOrder([](Layer* layer) {
2583 layer->commitChildList();
2584 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002585 mTransactionPending = false;
2586 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002587 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002588}
2589
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002590void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2591 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002592 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002593 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002594
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002595 Region aboveOpaqueLayers;
2596 Region aboveCoveredLayers;
2597 Region dirty;
2598
Mathias Agopian87baae12012-07-31 12:38:26 -07002599 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002600
Robert Carr2047fae2016-11-28 14:09:09 -08002601 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002602 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002603 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002604
Jesse Hall01e29052013-02-19 16:13:35 -08002605 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002606 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002607 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002608 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002609
Mathias Agopianab028732010-03-16 16:41:46 -07002610 /*
2611 * opaqueRegion: area of a surface that is fully opaque.
2612 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002613 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002614
2615 /*
2616 * visibleRegion: area of a surface that is visible on screen
2617 * and not fully transparent. This is essentially the layer's
2618 * footprint minus the opaque regions above it.
2619 * Areas covered by a translucent surface are considered visible.
2620 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002621 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002622
2623 /*
2624 * coveredRegion: area of a surface that is covered by all
2625 * visible regions above it (which includes the translucent areas).
2626 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002627 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002628
Jesse Halla8026d22012-09-25 13:25:04 -07002629 /*
2630 * transparentRegion: area of a surface that is hinted to be completely
2631 * transparent. This is only used to tell when the layer has no visible
2632 * non-transparent regions and can be removed from the layer list. It
2633 * does not affect the visibleRegion of this layer or any layers
2634 * beneath it. The hint may not be correct if apps don't respect the
2635 * SurfaceView restrictions (which, sadly, some don't).
2636 */
2637 Region transparentRegion;
2638
Mathias Agopianab028732010-03-16 16:41:46 -07002639
2640 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002641 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002642 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002643 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002644 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002645 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002646 if (!visibleRegion.isEmpty()) {
2647 // Remove the transparent area from the visible region
2648 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002649 if (tr.preserveRects()) {
2650 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002651 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002652 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002653 // transformation too complex, can't do the
2654 // transparent region optimization.
2655 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002656 }
Mathias Agopianab028732010-03-16 16:41:46 -07002657 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002658
Mathias Agopianab028732010-03-16 16:41:46 -07002659 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002660 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002661 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002662 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002663 // the opaque region is the layer's footprint
2664 opaqueRegion = visibleRegion;
2665 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002666 }
2667 }
2668
Robert Carre5f4f692018-01-12 13:12:28 -08002669 if (visibleRegion.isEmpty()) {
2670 layer->clearVisibilityRegions();
2671 return;
2672 }
2673
Mathias Agopianab028732010-03-16 16:41:46 -07002674 // Clip the covered region to the visible region
2675 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2676
2677 // Update aboveCoveredLayers for next (lower) layer
2678 aboveCoveredLayers.orSelf(visibleRegion);
2679
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002680 // subtract the opaque region covered by the layers above us
2681 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002682
2683 // compute this layer's dirty region
2684 if (layer->contentDirty) {
2685 // we need to invalidate the whole region
2686 dirty = visibleRegion;
2687 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002688 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002689 layer->contentDirty = false;
2690 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002691 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002692 * the exposed region consists of two components:
2693 * 1) what's VISIBLE now and was COVERED before
2694 * 2) what's EXPOSED now less what was EXPOSED before
2695 *
2696 * note that (1) is conservative, we start with the whole
2697 * visible region but only keep what used to be covered by
2698 * something -- which mean it may have been exposed.
2699 *
2700 * (2) handles areas that were not covered by anything but got
2701 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002702 */
Mathias Agopianab028732010-03-16 16:41:46 -07002703 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002704 const Region oldVisibleRegion = layer->visibleRegion;
2705 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002706 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2707 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002708 }
2709 dirty.subtractSelf(aboveOpaqueLayers);
2710
2711 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002712 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002713
Mathias Agopianab028732010-03-16 16:41:46 -07002714 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002715 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002716
Jesse Halla8026d22012-09-25 13:25:04 -07002717 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002718 layer->setVisibleRegion(visibleRegion);
2719 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002720 layer->setVisibleNonTransparentRegion(
2721 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002722 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002723
Mathias Agopian87baae12012-07-31 12:38:26 -07002724 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002725}
2726
Chia-I Wuab0c3192017-08-01 11:29:00 -07002727void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002728 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002729 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2730 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002731 }
2732 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002733}
2734
Dan Stoza6b9454d2014-11-07 16:00:59 -08002735bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002736{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002737 ALOGV("handlePageFlip");
2738
Brian Andersond6927fb2016-07-23 23:37:30 -07002739 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002740
Mathias Agopian4fec8732012-06-29 14:12:52 -07002741 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002742 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002743 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002744
2745 // Store the set of layers that need updates. This set must not change as
2746 // buffers are being latched, as this could result in a deadlock.
2747 // Example: Two producers share the same command stream and:
2748 // 1.) Layer 0 is latched
2749 // 2.) Layer 0 gets a new frame
2750 // 2.) Layer 1 gets a new frame
2751 // 3.) Layer 1 is latched.
2752 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2753 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002754 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002755 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002756 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07002757 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002758 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002759 } else {
2760 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002761 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002762 } else {
2763 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002764 }
Robert Carr2047fae2016-11-28 14:09:09 -08002765 });
2766
Dan Stoza9e56aa02015-11-02 13:00:03 -08002767 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002768 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002769 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002770 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002771 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002772 newDataLatched = true;
2773 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002774 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002775
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002776 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002777
2778 // If we will need to wake up at some time in the future to deal with a
2779 // queued frame that shouldn't be displayed during this vsync period, wake
2780 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002781 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002782 signalLayerUpdate();
2783 }
2784
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002785 // enter boot animation on first buffer latch
2786 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2787 ALOGI("Enter boot animation");
2788 mBootStage = BootStage::BOOTANIMATION;
2789 }
2790
Dan Stoza6b9454d2014-11-07 16:00:59 -08002791 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002792 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002793}
2794
Mathias Agopianad456f92011-01-13 17:53:01 -08002795void SurfaceFlinger::invalidateHwcGeometry()
2796{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002797 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002798}
2799
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002800void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2801 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002802 // We only need to actually compose the display if:
2803 // 1) It is being handled by hardware composer, which may need this to
2804 // keep its virtual display state machine in sync, or
2805 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002806 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002807 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002808 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002809 return;
2810 }
2811
Dan Stoza9e56aa02015-11-02 13:00:03 -08002812 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002813 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002814
2815 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002816 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002817}
2818
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002819bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002820 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002821
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002822 const Region bounds(display->bounds());
2823 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002824 const auto displayId = display->getId();
2825 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002826 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002827
Chia-I Wu8e50e692018-05-04 10:12:37 -07002828 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002829 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002830
Dan Stoza9e56aa02015-11-02 13:00:03 -08002831 if (hasClientComposition) {
2832 ALOGV("hasClientComposition");
2833
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002834 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002835 if (display->hasWideColorGamut()) {
2836 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002837 }
2838 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002839 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002840 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002841
Dominik Laskowski7e045462018-05-30 13:02:02 -07002842 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002843 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2844 HWC2::Capability::SkipClientColorTransform);
2845
Chia-I Wud49d6692018-06-27 07:17:41 +08002846 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002847 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2848 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08002849 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002850 }
2851
Chia-I Wud49d6692018-06-27 07:17:41 +08002852 // The current enhanced saturation matrix is designed to enhance Display P3,
2853 // thus we only apply this matrix when the render intent is not colorimetric
2854 // and the output color space is Display P3.
2855 needsEnhancedColorMatrix =
2856 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2857 outputDataspace == Dataspace::DISPLAY_P3);
2858 if (needsEnhancedColorMatrix) {
2859 colorMatrix *= mEnhancedSaturationMatrix;
2860 }
2861
2862 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002863
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002864 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002865 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002866 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002867 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002868
2869 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002870 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
2871 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
2872 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07002873 }
2874 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002875 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002876
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002877 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002878 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002879 // when using overlays, we assume a fully transparent framebuffer
2880 // NOTE: we could reduce how much we need to clear, for instance
2881 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002882 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002883 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002884 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002885 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002886 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002887 // we're left with the letterbox region
2888 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002889 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07002890
2891 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002892 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07002893
Mathias Agopianb9494d52012-04-18 02:28:45 -07002894 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002895 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002896 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002897 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002898 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002899 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002900
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002901 if (!display->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002902 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002903 // scissor on the main display. It should never be needed
2904 // anyways (though in theory it could since the API allows it).
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002905 const Rect& bounds = display->getBounds();
2906 const Rect& scissor = display->getScissor();
Mathias Agopianf45c5102012-10-24 16:29:17 -07002907 if (scissor != bounds) {
2908 // scissor doesn't match the screen's dimensions, so we
2909 // need to clear everything outside of it and enable
2910 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002911
Mathias Agopianf45c5102012-10-24 16:29:17 -07002912 // enable scissor for this frame
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002913 const uint32_t height = display->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002914 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002915 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002916 }
2917 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002918 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002919
Mathias Agopian85d751c2012-08-29 16:59:24 -07002920 /*
2921 * and then, render the layers targeted at the framebuffer
2922 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002923
Dan Stoza9e56aa02015-11-02 13:00:03 -08002924 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07002925 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002926 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002927 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002928 const Region clip(bounds.intersect(
2929 displayTransform.transform(layer->visibleRegion)));
2930 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002931 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002932 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002933 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002934 case HWC2::Composition::Cursor:
2935 case HWC2::Composition::Device:
2936 case HWC2::Composition::Sideband:
2937 case HWC2::Composition::SolidColor: {
2938 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002939 if (layer->getClearClientTarget(displayId) && !firstLayer &&
Rajavenu Kyatham2eae6d32018-04-10 12:34:05 +05302940 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
2941 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002942 // never clear the very first layer since we're
2943 // guaranteed the FB is already cleared
2944 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002945 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002946 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002947 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002948 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002949 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002950 break;
2951 }
2952 default:
2953 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002954 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002955 } else {
2956 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002957 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002958 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002959 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002960
Chia-I Wud49d6692018-06-27 07:17:41 +08002961 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07002962 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002963 }
2964
Mathias Agopianf45c5102012-10-24 16:29:17 -07002965 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002966 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002967 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002968}
2969
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002970void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
2971 const Region& region) const {
2972 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002973 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002974 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002975}
2976
Dan Stoza7d89d062015-04-30 13:29:25 -07002977status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002978 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002979 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002980 const sp<Layer>& lbc,
2981 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002982{
Dan Stoza7d89d062015-04-30 13:29:25 -07002983 // add this layer to the current state list
2984 {
2985 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002986 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002987 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2988 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002989 return NO_MEMORY;
2990 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002991 if (parent == nullptr) {
2992 mCurrentState.layersSortedByZ.add(lbc);
2993 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002994 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002995 ALOGE("addClientLayer called with a removed parent");
2996 return NAME_NOT_FOUND;
2997 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002998 parent->addChild(lbc);
2999 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003000
Yiwei Zhang243b3782018-05-15 17:40:04 -07003001 if (gbc != nullptr) {
3002 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3003 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3004 mMaxGraphicBufferProducerListSize,
3005 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3006 mGraphicBufferProducerList.size(),
3007 mMaxGraphicBufferProducerListSize, mNumLayers);
3008 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003009 mLayersAdded = true;
3010 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003011 }
3012
Mathias Agopian96f08192010-06-02 23:28:45 -07003013 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003014 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003015
Dan Stoza7d89d062015-04-30 13:29:25 -07003016 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003017}
3018
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003019status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003020 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003021 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3022}
Robert Carr7f9b8992017-03-10 11:08:39 -08003023
chaviwca27f252018-02-06 16:46:39 -08003024status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3025 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003026 if (layer->isPendingRemoval()) {
3027 return NO_ERROR;
3028 }
3029
Robert Carr1f0a16a2016-10-24 16:27:39 -07003030 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003031 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003032 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003033 if (topLevelOnly) {
3034 return NO_ERROR;
3035 }
3036
Chia-I Wu98f1c102017-05-30 14:54:08 -07003037 sp<Layer> ancestor = p;
3038 while (ancestor->getParent() != nullptr) {
3039 ancestor = ancestor->getParent();
3040 }
3041 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3042 ALOGE("removeLayer called with a layer whose parent has been removed");
3043 return NAME_NOT_FOUND;
3044 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003045
3046 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003047 } else {
3048 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003049 }
3050
Robert Carr136e2f62017-02-08 17:54:29 -08003051 // As a matter of normal operation, the LayerCleaner will produce a second
3052 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3053 // so we will succeed in promoting it, but it's already been removed
3054 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3055 // otherwise something has gone wrong and we are leaking the layer.
3056 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003057 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3058 layer->getName().string(),
3059 (p != nullptr) ? p->getName().string() : "no-parent");
3060 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003061 } else if (index < 0) {
3062 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003063 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003064
Chia-I Wuc6657022017-08-15 11:18:17 -07003065 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003066 mLayersPendingRemoval.add(layer);
3067 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003068 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003069 setTransactionFlags(eTransactionNeeded);
3070 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003071}
3072
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003073uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003074 return android_atomic_release_load(&mTransactionFlags);
3075}
3076
Mathias Agopian3f844832013-08-07 21:24:32 -07003077uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003078 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3079}
3080
Mathias Agopian3f844832013-08-07 21:24:32 -07003081uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003082 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3083}
3084
3085uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3086 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003087 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003088 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003089 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003090 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003091 }
3092 return old;
3093}
3094
chaviwca27f252018-02-06 16:46:39 -08003095bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3096 for (const ComposerState& state : states) {
3097 // Here we need to check that the interface we're given is indeed
3098 // one of our own. A malicious client could give us a nullptr
3099 // IInterface, or one of its own or even one of our own but a
3100 // different type. All these situations would cause us to crash.
3101 if (state.client == nullptr) {
3102 return true;
3103 }
3104
3105 sp<IBinder> binder = IInterface::asBinder(state.client);
3106 if (binder == nullptr) {
3107 return true;
3108 }
3109
3110 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3111 return true;
3112 }
3113 }
3114 return false;
3115}
3116
Mathias Agopian8b33f032012-07-24 20:43:54 -07003117void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003118 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003119 const Vector<DisplayState>& displays,
3120 uint32_t flags)
3121{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003122 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003123 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003124 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003125
chaviwca27f252018-02-06 16:46:39 -08003126 if (containsAnyInvalidClientState(states)) {
3127 return;
3128 }
3129
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003130 if (flags & eAnimation) {
3131 // For window updates that are part of an animation we must wait for
3132 // previous animation "frames" to be handled.
3133 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003134 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003135 if (CC_UNLIKELY(err != NO_ERROR)) {
3136 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003137 // caller after a few seconds.
3138 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3139 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003140 mAnimTransactionPending = false;
3141 break;
3142 }
3143 }
3144 }
3145
chaviwca27f252018-02-06 16:46:39 -08003146 for (const DisplayState& display : displays) {
3147 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003148 }
3149
chaviwca27f252018-02-06 16:46:39 -08003150 for (const ComposerState& state : states) {
3151 transactionFlags |= setClientStateLocked(state);
3152 }
3153
3154 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3155 // as destroyed should only occur after setting all other states. This is to allow for a
3156 // child re-parent to happen before marking its original parent as destroyed (which would
3157 // then mark the child as destroyed).
3158 for (const ComposerState& state : states) {
3159 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003160 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003161
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003162 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3163 // anyway. This can be used as a flush mechanism for previous async transactions.
3164 // Empty animation transaction can be used to simulate back-pressure, so also force a
3165 // transaction for empty animation transactions.
3166 if (transactionFlags == 0 &&
3167 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003168 transactionFlags = eTransactionNeeded;
3169 }
3170
Mathias Agopian386aa982011-11-07 21:58:03 -08003171 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003172 if (mInterceptor->isEnabled()) {
3173 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003174 }
Irvel468051e2016-06-13 16:44:44 -07003175
Mathias Agopian386aa982011-11-07 21:58:03 -08003176 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003177 const auto start = (flags & eEarlyWakeup)
3178 ? VSyncModulator::TransactionStart::EARLY
3179 : VSyncModulator::TransactionStart::NORMAL;
3180 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003181
3182 // if this is a synchronous transaction, wait for it to take effect
3183 // before returning.
3184 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003185 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003186 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003187 if (flags & eAnimation) {
3188 mAnimTransactionPending = true;
3189 }
3190 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003191 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3192 if (CC_UNLIKELY(err != NO_ERROR)) {
3193 // just in case something goes wrong in SF, return to the
3194 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003195 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3196 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003197 break;
3198 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003199 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003200 }
3201}
3202
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003203uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3204 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3205 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003206
Mathias Agopiane57f2922012-08-09 16:29:12 -07003207 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003208 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3209
3210 const uint32_t what = s.what;
3211 if (what & DisplayState::eSurfaceChanged) {
3212 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3213 state.surface = s.surface;
3214 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003215 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003216 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003217 if (what & DisplayState::eLayerStackChanged) {
3218 if (state.layerStack != s.layerStack) {
3219 state.layerStack = s.layerStack;
3220 flags |= eDisplayTransactionNeeded;
3221 }
3222 }
3223 if (what & DisplayState::eDisplayProjectionChanged) {
3224 if (state.orientation != s.orientation) {
3225 state.orientation = s.orientation;
3226 flags |= eDisplayTransactionNeeded;
3227 }
3228 if (state.frame != s.frame) {
3229 state.frame = s.frame;
3230 flags |= eDisplayTransactionNeeded;
3231 }
3232 if (state.viewport != s.viewport) {
3233 state.viewport = s.viewport;
3234 flags |= eDisplayTransactionNeeded;
3235 }
3236 }
3237 if (what & DisplayState::eDisplaySizeChanged) {
3238 if (state.width != s.width) {
3239 state.width = s.width;
3240 flags |= eDisplayTransactionNeeded;
3241 }
3242 if (state.height != s.height) {
3243 state.height = s.height;
3244 flags |= eDisplayTransactionNeeded;
3245 }
3246 }
3247
Mathias Agopiane57f2922012-08-09 16:29:12 -07003248 return flags;
3249}
3250
Robert Carrd4ae7f32018-06-07 16:10:57 -07003251bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3252 IPCThreadState* ipc = IPCThreadState::self();
3253 const int pid = ipc->getCallingPid();
3254 const int uid = ipc->getCallingUid();
Dan Stozae3344402018-08-20 19:53:42 +00003255
Robert Carrd4ae7f32018-06-07 16:10:57 -07003256 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Dan Stozae3344402018-08-20 19:53:42 +00003257 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003258 return false;
3259 }
3260 return true;
3261}
3262
chaviwca27f252018-02-06 16:46:39 -08003263uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3264 const layer_state_t& s = composerState.state;
3265 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3266
Mathias Agopian13127d82013-03-05 17:47:11 -08003267 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003268 if (layer == nullptr) {
3269 return 0;
3270 }
3271
3272 if (layer->isPendingRemoval()) {
3273 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3274 return 0;
3275 }
3276
3277 uint32_t flags = 0;
3278
3279 const uint32_t what = s.what;
3280 bool geometryAppliesWithResize =
3281 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003282
3283 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3284 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003285 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003286 layer->pushPendingState();
3287 }
3288
chaviw8b3871a2017-11-01 17:41:01 -07003289 if (what & layer_state_t::ePositionChanged) {
3290 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3291 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003292 }
chaviw8b3871a2017-11-01 17:41:01 -07003293 }
3294 if (what & layer_state_t::eLayerChanged) {
3295 // NOTE: index needs to be calculated before we update the state
3296 const auto& p = layer->getParent();
3297 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003298 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003299 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003300 mCurrentState.layersSortedByZ.removeAt(idx);
3301 mCurrentState.layersSortedByZ.add(layer);
3302 // we need traversal (state changed)
3303 // AND transaction (list changed)
3304 flags |= eTransactionNeeded|eTraversalNeeded;
3305 }
chaviw8b3871a2017-11-01 17:41:01 -07003306 } else {
3307 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003308 flags |= eTransactionNeeded|eTraversalNeeded;
3309 }
3310 }
chaviw8b3871a2017-11-01 17:41:01 -07003311 }
3312 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003313 // NOTE: index needs to be calculated before we update the state
3314 const auto& p = layer->getParent();
3315 if (p == nullptr) {
3316 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3317 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3318 mCurrentState.layersSortedByZ.removeAt(idx);
3319 mCurrentState.layersSortedByZ.add(layer);
3320 // we need traversal (state changed)
3321 // AND transaction (list changed)
3322 flags |= eTransactionNeeded|eTraversalNeeded;
3323 }
3324 } else {
3325 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3326 flags |= eTransactionNeeded|eTraversalNeeded;
3327 }
chaviw8b3871a2017-11-01 17:41:01 -07003328 }
3329 }
3330 if (what & layer_state_t::eSizeChanged) {
3331 if (layer->setSize(s.w, s.h)) {
3332 flags |= eTraversalNeeded;
3333 }
3334 }
3335 if (what & layer_state_t::eAlphaChanged) {
3336 if (layer->setAlpha(s.alpha))
3337 flags |= eTraversalNeeded;
3338 }
3339 if (what & layer_state_t::eColorChanged) {
3340 if (layer->setColor(s.color))
3341 flags |= eTraversalNeeded;
3342 }
3343 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003344 // TODO: b/109894387
3345 //
3346 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3347 // rotation. To see the problem observe that if we have a square parent, and a child
3348 // of the same size, then we rotate the child 45 degrees around it's center, the child
3349 // must now be cropped to a non rectangular 8 sided region.
3350 //
3351 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3352 // private API, and the WindowManager only uses rotation in one case, which is on a top
3353 // level layer in which cropping is not an issue.
3354 //
3355 // However given that abuse of rotation matrices could lead to surfaces extending outside
3356 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3357 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3358 // transformations.
3359 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003360 flags |= eTraversalNeeded;
3361 }
3362 if (what & layer_state_t::eTransparentRegionChanged) {
3363 if (layer->setTransparentRegionHint(s.transparentRegion))
3364 flags |= eTraversalNeeded;
3365 }
3366 if (what & layer_state_t::eFlagsChanged) {
3367 if (layer->setFlags(s.flags, s.mask))
3368 flags |= eTraversalNeeded;
3369 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003370 if (what & layer_state_t::eCropChanged_legacy) {
3371 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003372 flags |= eTraversalNeeded;
3373 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003374 if (what & layer_state_t::eFinalCropChanged_legacy) {
3375 if (layer->setFinalCrop_legacy(s.finalCrop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003376 flags |= eTraversalNeeded;
3377 }
3378 if (what & layer_state_t::eLayerStackChanged) {
3379 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3380 // We only allow setting layer stacks for top level layers,
3381 // everything else inherits layer stack from its parent.
3382 if (layer->hasParent()) {
3383 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3384 layer->getName().string());
3385 } else if (idx < 0) {
3386 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3387 "that also does not appear in the top level layer list. Something"
3388 " has gone wrong.", layer->getName().string());
3389 } else if (layer->setLayerStack(s.layerStack)) {
3390 mCurrentState.layersSortedByZ.removeAt(idx);
3391 mCurrentState.layersSortedByZ.add(layer);
3392 // we need traversal (state changed)
3393 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003394 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003395 }
3396 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003397 if (what & layer_state_t::eDeferTransaction_legacy) {
3398 if (s.barrierHandle_legacy != nullptr) {
3399 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3400 } else if (s.barrierGbp_legacy != nullptr) {
3401 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003402 if (authenticateSurfaceTextureLocked(gbp)) {
3403 const auto& otherLayer =
3404 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003405 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003406 } else {
3407 ALOGE("Attempt to defer transaction to to an"
3408 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003409 }
3410 }
chaviw8b3871a2017-11-01 17:41:01 -07003411 // We don't trigger a traversal here because if no other state is
3412 // changed, we don't want this to cause any more work
3413 }
3414 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003415 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003416 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003417 if (!hadParent) {
3418 mCurrentState.layersSortedByZ.remove(layer);
3419 }
chaviw8b3871a2017-11-01 17:41:01 -07003420 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003421 }
chaviw8b3871a2017-11-01 17:41:01 -07003422 }
3423 if (what & layer_state_t::eReparentChildren) {
3424 if (layer->reparentChildren(s.reparentHandle)) {
3425 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003426 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003427 }
chaviw8b3871a2017-11-01 17:41:01 -07003428 if (what & layer_state_t::eDetachChildren) {
3429 layer->detachChildren();
3430 }
3431 if (what & layer_state_t::eOverrideScalingModeChanged) {
3432 layer->setOverrideScalingMode(s.overrideScalingMode);
3433 // We don't trigger a traversal here because if no other state is
3434 // changed, we don't want this to cause any more work
3435 }
Marissa Wall61c58622018-07-18 10:12:20 -07003436 if (what & layer_state_t::eTransformChanged) {
3437 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3438 }
3439 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3440 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3441 flags |= eTraversalNeeded;
3442 }
3443 if (what & layer_state_t::eCropChanged) {
3444 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3445 }
3446 if (what & layer_state_t::eBufferChanged) {
3447 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3448 }
3449 if (what & layer_state_t::eAcquireFenceChanged) {
3450 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3451 }
3452 if (what & layer_state_t::eDataspaceChanged) {
3453 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3454 }
3455 if (what & layer_state_t::eHdrMetadataChanged) {
3456 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3457 }
3458 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3459 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3460 }
3461 if (what & layer_state_t::eApiChanged) {
3462 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3463 }
3464 if (what & layer_state_t::eSidebandStreamChanged) {
3465 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3466 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003467 return flags;
3468}
3469
chaviwca27f252018-02-06 16:46:39 -08003470void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3471 const layer_state_t& state = composerState.state;
3472 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3473
3474 sp<Layer> layer(client->getLayerUser(state.surface));
3475 if (layer == nullptr) {
3476 return;
3477 }
3478
3479 if (layer->isPendingRemoval()) {
3480 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3481 return;
3482 }
3483
3484 if (state.what & layer_state_t::eDestroySurface) {
3485 removeLayerLocked(mStateLock, layer);
3486 }
3487}
3488
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003489status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003490 const String8& name,
3491 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003492 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003493 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003494 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003495{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003496 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003497 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003498 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003499 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003500 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003501
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003502 status_t result = NO_ERROR;
3503
3504 sp<Layer> layer;
3505
Cody Northropbc755282017-03-31 12:00:08 -06003506 String8 uniqueName = getUniqueLayerName(name);
3507
Mathias Agopian3165cc22012-08-08 19:42:09 -07003508 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003509 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003510 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3511 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003512
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003513 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003514 case ISurfaceComposerClient::eFXSurfaceBufferState:
3515 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3516 break;
chaviw13fdc492017-06-27 12:40:18 -07003517 case ISurfaceComposerClient::eFXSurfaceColor:
3518 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003519 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003520 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003521 break;
3522 default:
3523 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003524 break;
3525 }
3526
Dan Stoza7d89d062015-04-30 13:29:25 -07003527 if (result != NO_ERROR) {
3528 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003529 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003530
Chia-I Wuab0c3192017-08-01 11:29:00 -07003531 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3532 // TODO b/64227542
3533 if (windowType == 441731) {
3534 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3535 layer->setPrimaryDisplayOnly();
3536 }
3537
Albert Chaulk479c60c2017-01-27 14:21:34 -05003538 layer->setInfo(windowType, ownerUid);
3539
Robert Carr1f0a16a2016-10-24 16:27:39 -07003540 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003541 if (result != NO_ERROR) {
3542 return result;
3543 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003544 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003545
3546 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003547 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003548}
3549
Cody Northropbc755282017-03-31 12:00:08 -06003550String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3551{
3552 bool matchFound = true;
3553 uint32_t dupeCounter = 0;
3554
3555 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3556 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3557
Dan Stoza436ccf32018-06-21 12:10:12 -07003558 // Grab the state lock since we're accessing mCurrentState
3559 Mutex::Autolock lock(mStateLock);
3560
Cody Northropbc755282017-03-31 12:00:08 -06003561 // Loop over layers until we're sure there is no matching name
3562 while (matchFound) {
3563 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003564 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003565 if (layer->getName() == uniqueName) {
3566 matchFound = true;
3567 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3568 }
3569 });
3570 }
3571
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003572 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3573 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003574
3575 return uniqueName;
3576}
3577
Marissa Wallfd668622018-05-10 10:21:13 -07003578status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3579 uint32_t w, uint32_t h, uint32_t flags,
3580 PixelFormat& format, sp<IBinder>* handle,
3581 sp<IGraphicBufferProducer>* gbp,
3582 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003583 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003584 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003585 case PIXEL_FORMAT_TRANSPARENT:
3586 case PIXEL_FORMAT_TRANSLUCENT:
3587 format = PIXEL_FORMAT_RGBA_8888;
3588 break;
3589 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003590 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003591 break;
3592 }
3593
Marissa Wallfd668622018-05-10 10:21:13 -07003594 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3595 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003596 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003597 *handle = layer->getHandle();
3598 *gbp = layer->getProducer();
3599 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003600 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003601
Marissa Wallfd668622018-05-10 10:21:13 -07003602 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003603 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003604}
3605
Marissa Wall61c58622018-07-18 10:12:20 -07003606status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3607 uint32_t w, uint32_t h, uint32_t flags,
3608 sp<IBinder>* handle, sp<Layer>* outLayer) {
3609 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3610 *handle = layer->getHandle();
3611 *outLayer = layer;
3612
3613 return NO_ERROR;
3614}
3615
chaviw13fdc492017-06-27 12:40:18 -07003616status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003617 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003618 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003619{
chaviw13fdc492017-06-27 12:40:18 -07003620 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003621 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003622 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003623}
3624
Mathias Agopianac9fa422013-02-11 16:40:36 -08003625status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003626{
Robert Carr9524cb32017-02-13 11:32:32 -08003627 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003628 status_t err = NO_ERROR;
3629 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003630 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003631 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003632 err = removeLayer(l);
3633 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3634 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003635 }
3636 return err;
3637}
3638
Mathias Agopian13127d82013-03-05 17:47:11 -08003639status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003640{
Mathias Agopian67106042013-03-14 19:18:13 -07003641 // called by ~LayerCleaner() when all references to the IBinder (handle)
3642 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003643 sp<Layer> l = layer.promote();
3644 if (l == nullptr) {
3645 // The layer has already been removed, carry on
3646 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003647 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003648 // If we have a parent, then we can continue to live as long as it does.
3649 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003650}
3651
Mathias Agopianb60314a2012-04-10 22:09:54 -07003652// ---------------------------------------------------------------------------
3653
Andy McFadden13a082e2012-08-24 10:16:42 -07003654void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003655 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3656 if (!displayToken) return;
3657
Jesse Hall01e29052013-02-19 16:13:35 -08003658 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003659 Vector<ComposerState> state;
3660 Vector<DisplayState> displays;
3661 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003662 d.what = DisplayState::eDisplayProjectionChanged |
3663 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003664 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003665 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003666 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003667 d.frame.makeInvalid();
3668 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003669 d.width = 0;
3670 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003671 displays.add(d);
3672 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003673
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003674 const auto display = getDisplayDevice(displayToken);
3675 if (!display) return;
3676
3677 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3678
3679 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003680 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003681 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003682
Brian Andersond0010582017-03-07 13:20:31 -08003683 // Use phase of 0 since phase is not known.
3684 // Use latency of 0, which will snap to the ideal latency.
3685 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003686}
3687
3688void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003689 // Async since we may be called from the main thread.
3690 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003691}
3692
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003693void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3694 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003695 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003696 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003697
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003698 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003699 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003700 return;
3701 }
3702
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003703 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003704 ALOGW("Trying to set power mode for virtual display");
3705 return;
3706 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003707
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003708 display->setPowerMode(mode);
3709
Lloyd Pique4dccc412018-01-22 17:21:36 -08003710 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003711 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003712 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003713 if (idx < 0) {
3714 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3715 return;
3716 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003717 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003718 }
3719
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003720 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003721 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003722 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003723 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003724 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003725 // FIXME: eventthread only knows about the main display right now
3726 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003727 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003728 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003729
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003730 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003731 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003732 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003733
3734 struct sched_param param = {0};
3735 param.sched_priority = 1;
3736 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3737 ALOGW("Couldn't set SCHED_FIFO on display on");
3738 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003739 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003740 // Turn off the display
3741 struct sched_param param = {0};
3742 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3743 ALOGW("Couldn't set SCHED_OTHER on display off");
3744 }
3745
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003746 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003747 disableHardwareVsync(true); // also cancels any in-progress resync
3748
Mathias Agopiancde87a32012-09-13 14:09:01 -07003749 // FIXME: eventthread only knows about the main display right now
3750 mEventThread->onScreenReleased();
3751 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003752
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003753 getHwComposer().setPowerMode(type, mode);
3754 mVisibleRegionsDirty = true;
3755 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003756 } else if (mode == HWC_POWER_MODE_DOZE ||
3757 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003758 // Update display while dozing
3759 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003760 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003761 // FIXME: eventthread only knows about the main display right now
3762 mEventThread->onScreenAcquired();
3763 resyncToHardwareVsync(true);
3764 }
3765 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3766 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003767 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003768 disableHardwareVsync(true); // also cancels any in-progress resync
3769 // FIXME: eventthread only knows about the main display right now
3770 mEventThread->onScreenReleased();
3771 }
3772 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003773 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003774 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003775 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003776 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003777
3778 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003779}
3780
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003781void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003782 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003783 const auto display = getDisplayDevice(displayToken);
3784 if (!display) {
3785 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3786 displayToken.get());
3787 } else if (display->isVirtual()) {
3788 ALOGW("Attempt to set power mode %d for virtual display", mode);
3789 } else {
3790 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003791 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003792 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003793}
3794
3795// ---------------------------------------------------------------------------
3796
Lloyd Pique755e3192018-01-31 16:46:15 -08003797status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3798 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003799 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003800
Mathias Agopianbd115332013-04-18 16:41:04 -07003801 IPCThreadState* ipc = IPCThreadState::self();
3802 const int pid = ipc->getCallingPid();
3803 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003804
Mathias Agopianbd115332013-04-18 16:41:04 -07003805 if ((uid != AID_SHELL) &&
3806 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003807 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003808 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003809 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003810 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003811 // (this would indicate SF is stuck, but we want to be able to
3812 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003813 status_t err = mStateLock.timedLock(s2ns(1));
3814 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003815 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003816 result.appendFormat(
3817 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3818 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003819 }
3820
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003821 bool dumpAll = true;
3822 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003823 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003824
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003825 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003826 if ((index < numArgs) &&
3827 (args[index] == String16("--list"))) {
3828 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003829 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003830 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003831 }
3832
3833 if ((index < numArgs) &&
3834 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003835 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003836 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003837 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003838 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003839
3840 if ((index < numArgs) &&
3841 (args[index] == String16("--latency-clear"))) {
3842 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003843 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003844 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003845 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003846
3847 if ((index < numArgs) &&
3848 (args[index] == String16("--dispsync"))) {
3849 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07003850 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07003851 dumpAll = false;
3852 }
Dan Stozab90cf072015-03-05 11:05:59 -08003853
3854 if ((index < numArgs) &&
3855 (args[index] == String16("--static-screen"))) {
3856 index++;
3857 dumpStaticScreenStats(result);
3858 dumpAll = false;
3859 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003860
3861 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003862 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003863 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003864 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003865 dumpAll = false;
3866 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003867
3868 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3869 index++;
3870 dumpWideColorInfo(result);
3871 dumpAll = false;
3872 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003873
3874 if ((index < numArgs) &&
3875 (args[index] == String16("--enable-layer-stats"))) {
3876 index++;
3877 mLayerStats.enable();
3878 dumpAll = false;
3879 }
3880
3881 if ((index < numArgs) &&
3882 (args[index] == String16("--disable-layer-stats"))) {
3883 index++;
3884 mLayerStats.disable();
3885 dumpAll = false;
3886 }
3887
3888 if ((index < numArgs) &&
3889 (args[index] == String16("--clear-layer-stats"))) {
3890 index++;
3891 mLayerStats.clear();
3892 dumpAll = false;
3893 }
3894
3895 if ((index < numArgs) &&
3896 (args[index] == String16("--dump-layer-stats"))) {
3897 index++;
3898 mLayerStats.dump(result);
3899 dumpAll = false;
3900 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003901
3902 if ((index < numArgs) &&
3903 (args[index] == String16("--display-identification"))) {
3904 index++;
3905 dumpDisplayIdentificationData(result);
3906 dumpAll = false;
3907 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003908
3909 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3910 index++;
3911 mTimeStats.parseArgs(asProto, args, index, result);
3912 dumpAll = false;
3913 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003914 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003915
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003916 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003917 if (asProto) {
3918 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3919 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3920 } else {
3921 dumpAllLocked(args, index, result);
3922 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003923 }
3924
Mathias Agopian9795c422009-08-26 16:36:26 -07003925 if (locked) {
3926 mStateLock.unlock();
3927 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003928 }
3929 write(fd, result.string(), result.size());
3930 return NO_ERROR;
3931}
3932
Dan Stozac7014012014-02-14 15:03:43 -08003933void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3934 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003935{
Robert Carr2047fae2016-11-28 14:09:09 -08003936 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003937 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003938 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003939}
3940
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003941void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003942 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003943{
3944 String8 name;
3945 if (index < args.size()) {
3946 name = String8(args[index]);
3947 index++;
3948 }
3949
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003950 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
3951 getHwComposer().isConnected(displayId)) {
3952 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
3953 const nsecs_t period = activeConfig->getVsyncPeriod();
3954 result.appendFormat("%" PRId64 "\n", period);
3955 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003956
3957 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003958 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003959 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003960 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003961 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003962 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003963 }
Robert Carr2047fae2016-11-28 14:09:09 -08003964 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003965 }
3966}
3967
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003968void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003969 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003970{
3971 String8 name;
3972 if (index < args.size()) {
3973 name = String8(args[index]);
3974 index++;
3975 }
3976
Robert Carr2047fae2016-11-28 14:09:09 -08003977 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003978 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003979 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003980 }
Robert Carr2047fae2016-11-28 14:09:09 -08003981 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003982
Svetoslavd85084b2014-03-20 10:28:31 -07003983 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003984}
3985
Jamie Gennis6547ff42013-07-16 20:12:42 -07003986// This should only be called from the main thread. Otherwise it would need
3987// the lock and should use mCurrentState rather than mDrawingState.
3988void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003989 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003990 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003991 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003992
3993 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3994}
3995
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003996void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003997{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003998 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003999
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004000 if (isLayerTripleBufferingDisabled())
4001 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004002
4003 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004004 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004005 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004006 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004007 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4008 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004009 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004010}
4011
Dan Stozab90cf072015-03-05 11:05:59 -08004012void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4013{
4014 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004015 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4016 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004017 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004018 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004019 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4020 b + 1, bucketTimeSec, percent);
4021 }
David Sodman4a36e932017-11-07 14:29:47 -08004022 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 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[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004025 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004026 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004027}
4028
Dan Stozae77c7662016-05-13 11:37:28 -07004029void SurfaceFlinger::recordBufferingStats(const char* layerName,
4030 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004031 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4032 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004033 for (const auto& segment : history) {
4034 if (!segment.usedThirdBuffer) {
4035 stats.twoBufferTime += segment.totalTime;
4036 }
4037 if (segment.occupancyAverage < 1.0f) {
4038 stats.doubleBufferedTime += segment.totalTime;
4039 } else if (segment.occupancyAverage < 2.0f) {
4040 stats.tripleBufferedTime += segment.totalTime;
4041 }
4042 ++stats.numSegments;
4043 stats.totalTime += segment.totalTime;
4044 }
4045}
4046
Brian Andersond6927fb2016-07-23 23:37:30 -07004047void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4048 result.appendFormat("Layer frame timestamps:\n");
4049
4050 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4051 const size_t count = currentLayers.size();
4052 for (size_t i=0 ; i<count ; i++) {
4053 currentLayers[i]->dumpFrameEvents(result);
4054 }
4055}
4056
Dan Stozae77c7662016-05-13 11:37:28 -07004057void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4058 result.append("Buffering stats:\n");
4059 result.append(" [Layer name] <Active time> <Two buffer> "
4060 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004061 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004062 typedef std::tuple<std::string, float, float, float> BufferTuple;
4063 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004064 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004065 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004066 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004067 if (stats.numSegments == 0) {
4068 continue;
4069 }
4070 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4071 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4072 stats.totalTime;
4073 float doubleBufferRatio = static_cast<float>(
4074 stats.doubleBufferedTime) / stats.totalTime;
4075 float tripleBufferRatio = static_cast<float>(
4076 stats.tripleBufferedTime) / stats.totalTime;
4077 sorted.insert({activeTime, {name, twoBufferRatio,
4078 doubleBufferRatio, tripleBufferRatio}});
4079 }
4080 for (const auto& sortedPair : sorted) {
4081 float activeTime = sortedPair.first;
4082 const BufferTuple& values = sortedPair.second;
4083 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4084 std::get<0>(values).c_str(), activeTime,
4085 std::get<1>(values), std::get<2>(values),
4086 std::get<3>(values));
4087 }
4088 result.append("\n");
4089}
4090
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004091void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004092 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004093 const int32_t displayId = display->getId();
4094 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4095 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004096 continue;
4097 }
4098
Dominik Laskowski7e045462018-05-30 13:02:02 -07004099 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004100 uint8_t port;
4101 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004102 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004103 result.append("no identification data\n");
4104 continue;
4105 }
4106
4107 if (!isEdid(data)) {
4108 result.append("unknown identification data: ");
4109 for (uint8_t byte : data) {
4110 result.appendFormat("%x ", byte);
4111 }
4112 result.append("\n");
4113 continue;
4114 }
4115
4116 const auto edid = parseEdid(data);
4117 if (!edid) {
4118 result.append("invalid EDID: ");
4119 for (uint8_t byte : data) {
4120 result.appendFormat("%x ", byte);
4121 }
4122 result.append("\n");
4123 continue;
4124 }
4125
4126 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4127 result.append(edid->displayName.data(), edid->displayName.length());
4128 result.append("\"\n");
4129 }
4130 result.append("\n");
4131}
4132
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004133void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4134 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004135 result.appendFormat("DisplayColorSetting: %s\n",
4136 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004137
4138 // TODO: print out if wide-color mode is active or not
4139
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004140 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004141 const int32_t displayId = display->getId();
4142 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004143 continue;
4144 }
4145
Dominik Laskowski7e045462018-05-30 13:02:02 -07004146 result.appendFormat("Display %d color modes:\n", displayId);
4147 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004148 for (auto&& mode : modes) {
4149 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4150 }
4151
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004152 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004153 result.appendFormat(" Current color mode: %s (%d)\n",
4154 decodeColorMode(currentMode).c_str(), currentMode);
4155 }
4156 result.append("\n");
4157}
4158
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004159LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004160 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004161 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4162 const State& state = useDrawing ? mDrawingState : mCurrentState;
4163 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004164 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004165 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004166 });
4167
4168 return layersProto;
4169}
4170
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004171LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004172 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004173
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004174 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004175 resolution->set_w(display.getWidth());
4176 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004177
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004178 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4179 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4180 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004181
Dominik Laskowski7e045462018-05-30 13:02:02 -07004182 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004183 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004184 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004185 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004186 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004187 }
4188 });
4189
4190 return layersProto;
4191}
4192
Mathias Agopian74d211a2013-04-22 16:55:35 +02004193void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4194 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004195{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004196 bool colorize = false;
4197 if (index < args.size()
4198 && (args[index] == String16("--color"))) {
4199 colorize = true;
4200 index++;
4201 }
4202
4203 Colorizer colorizer(colorize);
4204
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004205 // figure out if we're stuck somewhere
4206 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004207 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004208 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4209
4210 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004211 * Dump library configuration.
4212 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004213
4214 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004215 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004216 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004217 appendSfConfigString(result);
4218 appendUiConfigString(result);
4219 appendGuiConfigString(result);
4220 result.append("\n");
4221
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004222 result.append("\nDisplay identification data:\n");
4223 dumpDisplayIdentificationData(result);
4224
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004225 result.append("\nWide-Color information:\n");
4226 dumpWideColorInfo(result);
4227
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004228 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004229 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004230 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004231 result.append(SyncFeatures::getInstance().toString());
4232 result.append("\n");
4233
Andy McFadden41d67d72014-04-25 16:58:34 -07004234 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004235 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004236 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004237
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004238 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4239 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004240 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4241 getHwComposer().isConnected(displayId)) {
4242 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004243 result.appendFormat("Display %d: "
4244 "app phase %" PRId64 " ns, "
4245 "sf phase %" PRId64 " ns, "
4246 "early app phase %" PRId64 " ns, "
4247 "early sf phase %" PRId64 " ns, "
4248 "early app gl phase %" PRId64 " ns, "
4249 "early sf gl phase %" PRId64 " ns, "
4250 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4251 displayId,
4252 vsyncPhaseOffsetNs,
4253 sfVsyncPhaseOffsetNs,
4254 appEarlyOffset,
4255 sfEarlyOffset,
4256 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004257 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004258 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004259 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004260 result.append("\n");
4261
Dan Stozab90cf072015-03-05 11:05:59 -08004262 // Dump static screen stats
4263 result.append("\n");
4264 dumpStaticScreenStats(result);
4265 result.append("\n");
4266
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004267 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4268
Dan Stozae77c7662016-05-13 11:37:28 -07004269 dumpBufferingStats(result);
4270
Andy McFadden4803b742012-09-24 19:07:20 -07004271 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004272 * Dump the visible layer list
4273 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004274 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004275 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004276 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4277 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004278 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004279
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004280 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004281 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004282 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004283 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004284
4285 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004286 * Dump Display state
4287 */
4288
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004289 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004290 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004291 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004292 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004293 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004294 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004295 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004296
4297 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004298 * Dump SurfaceFlinger global state
4299 */
4300
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004301 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004302 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004303 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004304
Mathias Agopian888c8222012-08-04 21:10:38 -07004305 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004306 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004307
David Sodmanbc815282017-11-05 18:57:52 -08004308 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004309
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004310 if (display) {
4311 display->undefinedRegion.dump(result, "undefinedRegion");
4312 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4313 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004314 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004315 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004316 " gpu_to_cpu_unsupported : %d\n",
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004317 mTransactionFlags, !mGpuToCpuSupported);
4318
4319 if (display) {
4320 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4321 result.appendFormat(" refresh-rate : %f fps\n"
4322 " x-dpi : %f\n"
4323 " y-dpi : %f\n",
4324 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4325 activeConfig->getDpiY());
4326 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004327
Mathias Agopian74d211a2013-04-22 16:55:35 +02004328 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004329 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004330
4331 /*
4332 * VSYNC state
4333 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004334 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004335 result.append("\n");
4336
4337 /*
4338 * HWC layer minidump
4339 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004340 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004341 const int32_t displayId = display->getId();
4342 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004343 continue;
4344 }
4345
Dominik Laskowski7e045462018-05-30 13:02:02 -07004346 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004347 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004348 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004349 result.append("\n");
4350 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004351
4352 /*
4353 * Dump HWComposer state
4354 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004355 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004356 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004357 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004358 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004359 result.appendFormat(" h/w composer %s\n",
4360 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004361 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004362
4363 /*
4364 * Dump gralloc state
4365 */
4366 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4367 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004368
4369 /*
4370 * Dump VrFlinger state if in use.
4371 */
4372 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4373 result.append("VrFlinger state:\n");
4374 result.append(mVrFlinger->Dump().c_str());
4375 result.append("\n");
4376 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004377}
4378
Dominik Laskowski7e045462018-05-30 13:02:02 -07004379const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004380 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004381 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004382 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004383 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004384 }
4385 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004386
4387 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4388 static const Vector<sp<Layer>> empty;
4389 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004390}
4391
Keun young Park63f165f2012-08-31 10:53:36 -07004392bool SurfaceFlinger::startDdmConnection()
4393{
4394 void* libddmconnection_dso =
4395 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4396 if (!libddmconnection_dso) {
4397 return false;
4398 }
4399 void (*DdmConnection_start)(const char* name);
4400 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004401 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004402 if (!DdmConnection_start) {
4403 dlclose(libddmconnection_dso);
4404 return false;
4405 }
4406 (*DdmConnection_start)(getServiceName());
4407 return true;
4408}
4409
Chia-I Wu28f320b2018-05-03 11:02:56 -07004410void SurfaceFlinger::updateColorMatrixLocked() {
4411 mat4 colorMatrix;
4412 if (mGlobalSaturationFactor != 1.0f) {
4413 // Rec.709 luma coefficients
4414 float3 luminance{0.213f, 0.715f, 0.072f};
4415 luminance *= 1.0f - mGlobalSaturationFactor;
4416 mat4 saturationMatrix = mat4(
4417 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4418 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4419 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4420 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4421 );
4422 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4423 } else {
4424 colorMatrix = mClientColorMatrix * mDaltonizer();
4425 }
4426
4427 if (mCurrentState.colorMatrix != colorMatrix) {
4428 mCurrentState.colorMatrix = colorMatrix;
4429 mCurrentState.colorMatrixChanged = true;
4430 setTransactionFlags(eTransactionNeeded);
4431 }
4432}
4433
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004434status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Dan Stozae3344402018-08-20 19:53:42 +00004435 switch (code) {
Ana Krulecfbe2c002018-08-09 22:32:45 +00004436 case CREATE_CONNECTION:
4437 case CREATE_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004438 case BOOT_FINISHED:
4439 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulecfbe2c002018-08-09 22:32:45 +00004440 case GET_ANIMATION_FRAME_STATS:
Dan Stozae3344402018-08-20 19:53:42 +00004441 case SET_POWER_MODE:
Ana Krulecfbe2c002018-08-09 22:32:45 +00004442 case GET_HDR_CAPABILITIES:
Dan Stozae3344402018-08-20 19:53:42 +00004443 case ENABLE_VSYNC_INJECTIONS:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004444 case INJECT_VSYNC:
Dan Stozae3344402018-08-20 19:53:42 +00004445 {
4446 // codes that require permission check
Robert Carrd4ae7f32018-06-07 16:10:57 -07004447 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4448 IPCThreadState* ipc = IPCThreadState::self();
4449 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4450 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004451 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004452 }
Dan Stozae3344402018-08-20 19:53:42 +00004453 break;
4454 }
4455 /*
4456 * Calling setTransactionState is safe, because you need to have been
4457 * granted a reference to Client* and Handle* to do anything with it.
4458 *
4459 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4460 */
4461 case SET_TRANSACTION_STATE:
4462 case CREATE_SCOPED_CONNECTION:
4463 {
Robert Carr1db73f62016-12-21 12:58:51 -08004464 return OK;
4465 }
Dan Stozae3344402018-08-20 19:53:42 +00004466 case CAPTURE_SCREEN:
4467 {
4468 // codes that require permission check
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004469 IPCThreadState* ipc = IPCThreadState::self();
4470 const int pid = ipc->getCallingPid();
4471 const int uid = ipc->getCallingUid();
Dan Stozae3344402018-08-20 19:53:42 +00004472 if ((uid != AID_GRAPHICS) &&
4473 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4474 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004475 return PERMISSION_DENIED;
4476 }
Dan Stozae3344402018-08-20 19:53:42 +00004477 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004478 }
Dan Stozae3344402018-08-20 19:53:42 +00004479 case CAPTURE_LAYERS: {
chaviwa76b2712017-09-20 12:02:26 -07004480 IPCThreadState* ipc = IPCThreadState::self();
4481 const int pid = ipc->getCallingPid();
4482 const int uid = ipc->getCallingUid();
4483 if ((uid != AID_GRAPHICS) &&
4484 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4485 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4486 return PERMISSION_DENIED;
4487 }
Dan Stozae3344402018-08-20 19:53:42 +00004488 break;
chaviwa76b2712017-09-20 12:02:26 -07004489 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004490 }
Dan Stozae3344402018-08-20 19:53:42 +00004491 return OK;
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004492}
4493
Dan Stozae3344402018-08-20 19:53:42 +00004494status_t SurfaceFlinger::onTransact(
4495 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4496{
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004497 status_t credentialCheck = CheckTransactCodeCredentials(code);
4498 if (credentialCheck != OK) {
4499 return credentialCheck;
4500 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004501
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004502 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4503 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004504 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004505 IPCThreadState* ipc = IPCThreadState::self();
4506 const int uid = ipc->getCallingUid();
4507 if (CC_UNLIKELY(uid != AID_SYSTEM
4508 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004509 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004510 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004511 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004512 return PERMISSION_DENIED;
4513 }
4514 int n;
4515 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004516 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004517 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004518 return NO_ERROR;
4519 case 1002: // SHOW_UPDATES
4520 n = data.readInt32();
4521 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004522 invalidateHwcGeometry();
4523 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004524 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004525 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004526 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004527 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004528 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004529 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004530 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004531 setTransactionFlags(
4532 eTransactionNeeded|
4533 eDisplayTransactionNeeded|
4534 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004535 return NO_ERROR;
4536 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004537 case 1006:{ // send empty update
4538 signalRefresh();
4539 return NO_ERROR;
4540 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004541 case 1008: // toggle use of hw composer
4542 n = data.readInt32();
4543 mDebugDisableHWC = n ? 1 : 0;
4544 invalidateHwcGeometry();
4545 repaintEverything();
4546 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004547 case 1009: // toggle use of transform hint
4548 n = data.readInt32();
4549 mDebugDisableTransformHint = n ? 1 : 0;
4550 invalidateHwcGeometry();
4551 repaintEverything();
4552 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004553 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004554 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004555 reply->writeInt32(0);
4556 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004557 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004558 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004559 return NO_ERROR;
4560 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004561 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004562 if (!display) {
4563 return NAME_NOT_FOUND;
4564 }
4565
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004566 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004567 return NO_ERROR;
4568 }
4569 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004570 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004571 // daltonize
4572 n = data.readInt32();
4573 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004574 case 1:
4575 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4576 break;
4577 case 2:
4578 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4579 break;
4580 case 3:
4581 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4582 break;
4583 default:
4584 mDaltonizer.setType(ColorBlindnessType::None);
4585 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004586 }
4587 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004588 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004589 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004590 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004591 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004592
4593 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004594 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004595 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004596 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004597 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004598 // apply a color matrix
4599 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004600 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004601 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004602 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004603 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004604 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004605 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004606 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004607 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004608 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004609 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004610
4611 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4612 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004613 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004614 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4615 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4616 }
4617
Chia-I Wu28f320b2018-05-03 11:02:56 -07004618 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004619 return NO_ERROR;
4620 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004621 // This is an experimental interface
4622 // Needs to be shifted to proper binder interface when we productize
4623 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004624 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07004625 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004626 return NO_ERROR;
4627 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004628 case 1017: {
4629 n = data.readInt32();
4630 mForceFullDamage = static_cast<bool>(n);
4631 return NO_ERROR;
4632 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004633 case 1018: { // Modify Choreographer's phase offset
4634 n = data.readInt32();
4635 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4636 return NO_ERROR;
4637 }
4638 case 1019: { // Modify SurfaceFlinger's phase offset
4639 n = data.readInt32();
4640 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4641 return NO_ERROR;
4642 }
Irvel468051e2016-06-13 16:44:44 -07004643 case 1020: { // Layer updates interceptor
4644 n = data.readInt32();
4645 if (n) {
4646 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004647 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004648 }
4649 else{
4650 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004651 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004652 }
4653 return NO_ERROR;
4654 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004655 case 1021: { // Disable HWC virtual displays
4656 n = data.readInt32();
4657 mUseHwcVirtualDisplays = !n;
4658 return NO_ERROR;
4659 }
Romain Guy0147a172017-06-01 13:53:56 -07004660 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004661 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004662 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004663
Chia-I Wu28f320b2018-05-03 11:02:56 -07004664 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004665 return NO_ERROR;
4666 }
Romain Guy54f154a2017-10-24 21:40:32 +01004667 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004668 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004669 invalidateHwcGeometry();
4670 repaintEverything();
4671 return NO_ERROR;
4672 }
4673 case 1024: { // Is wide color gamut rendering/color management supported?
4674 reply->writeBool(hasWideColorDisplay);
4675 return NO_ERROR;
4676 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004677 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004678 n = data.readInt32();
4679 if (n) {
4680 ALOGV("LayerTracing enabled");
4681 mTracing.enable();
4682 doTracing("tracing.enable");
4683 reply->writeInt32(NO_ERROR);
4684 } else {
4685 ALOGV("LayerTracing disabled");
4686 status_t err = mTracing.disable();
4687 reply->writeInt32(err);
4688 }
4689 return NO_ERROR;
4690 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004691 case 1026: { // Get layer tracing status
4692 reply->writeBool(mTracing.isEnabled());
4693 return NO_ERROR;
4694 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004695 // Is a DisplayColorSetting supported?
4696 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004697 const auto display = getDefaultDisplayDevice();
4698 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004699 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004700 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004701
4702 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4703 switch (setting) {
4704 case DisplayColorSetting::MANAGED:
4705 reply->writeBool(hasWideColorDisplay);
4706 break;
4707 case DisplayColorSetting::UNMANAGED:
4708 reply->writeBool(true);
4709 break;
4710 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004711 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004712 break;
4713 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004714 reply->writeBool(
4715 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004716 break;
4717 }
4718 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004719 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004720 // Is VrFlinger active?
4721 case 1028: {
4722 Mutex::Autolock _l(mStateLock);
4723 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4724 return NO_ERROR;
4725 }
David Sodman6d46c1e2018-07-13 12:59:48 -07004726 case 1029: {
4727 // Code 1029 is an experimental feature that allows applications to
4728 // simulate a high frequency panel by setting a multiplier and divisor
4729 // on the VSYNC-sf clock. If either the multiplier or divisor are
4730 // 0, then the code will set both to 1 to return the VSYNC-sf clock
4731 // to it's normal frequency.
4732 int multiplier = data.readInt32();
4733 int divisor = data.readInt32();
4734
4735 if ((multiplier == 0) || (divisor == 0)) {
4736 multiplier = 1;
4737 divisor = 1;
4738 }
4739
4740 if ((multiplier == 1) && (divisor == 1)) {
4741 enableHardwareVsync();
4742 } else {
4743 disableHardwareVsync(true);
4744 }
4745 getBE().mHwc->getActiveConfig(DisplayDevice::DISPLAY_PRIMARY)
4746 ->scalePanelFrequency(multiplier, divisor);
4747 mPrimaryDispSync->scalePeriod(multiplier, divisor);
4748
4749 ATRACE_INT("PeriodMultiplier", multiplier);
4750 ATRACE_INT("PeriodDivisor", divisor);
4751 return NO_ERROR;
4752 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004753 }
4754 }
4755 return err;
4756}
4757
Steven Thomas6d8110b2017-08-31 18:24:21 -07004758void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004759 android_atomic_or(1, &mRepaintEverything);
4760 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004761}
4762
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004763// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4764class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004765public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004766 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4767 ~WindowDisconnector() {
4768 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004769 }
4770
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004771private:
4772 ANativeWindow* mWindow;
4773 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004774};
4775
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004776status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4777 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4778 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4779 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004780 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004781 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004782
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004783 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004784
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004785 const auto display = getDisplayDeviceLocked(displayToken);
4786 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004787
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004788 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004789
4790 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004791 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004792 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004793}
4794
4795status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004796 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004797 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004798 ATRACE_CALL();
4799
4800 class LayerRenderArea : public RenderArea {
4801 public:
Robert Carr578038f2018-03-09 12:25:24 -08004802 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4803 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004804 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004805 mLayer(layer),
4806 mCrop(crop),
4807 mFlinger(flinger),
4808 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07004809 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004810 Rect getBounds() const override {
4811 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07004812 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07004813 }
Marissa Wall61c58622018-07-18 10:12:20 -07004814 int getHeight() const override {
4815 return mLayer->getActiveHeight(mLayer->getDrawingState());
4816 }
4817 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07004818 bool isSecure() const override { return false; }
4819 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004820 Rect getSourceCrop() const override {
4821 if (mCrop.isEmpty()) {
4822 return getBounds();
4823 } else {
4824 return mCrop;
4825 }
4826 }
Robert Carr578038f2018-03-09 12:25:24 -08004827 class ReparentForDrawing {
4828 public:
4829 const sp<Layer>& oldParent;
4830 const sp<Layer>& newParent;
4831
4832 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4833 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004834 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004835 }
Robert Carr15eae092018-03-23 13:43:53 -07004836 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004837 };
4838
4839 void render(std::function<void()> drawLayers) override {
4840 if (!mChildrenOnly) {
4841 mTransform = mLayer->getTransform().inverse();
4842 drawLayers();
4843 } else {
4844 Rect bounds = getBounds();
4845 screenshotParentLayer =
4846 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4847 bounds.getWidth(), bounds.getHeight(), 0);
4848
4849 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4850 drawLayers();
4851 }
4852 }
chaviwa76b2712017-09-20 12:02:26 -07004853
chaviwa76b2712017-09-20 12:02:26 -07004854 private:
chaviw7206d492017-11-10 16:16:12 -08004855 const sp<Layer> mLayer;
4856 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004857
4858 // In the "childrenOnly" case we reparent the children to a screenshot
4859 // layer which has no properties set and which does not draw.
4860 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07004861 ui::Transform mTransform;
Robert Carr578038f2018-03-09 12:25:24 -08004862
4863 SurfaceFlinger* mFlinger;
4864 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004865 };
4866
4867 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4868 auto parent = layerHandle->owner.promote();
4869
chaviw7206d492017-11-10 16:16:12 -08004870 if (parent == nullptr || parent->isPendingRemoval()) {
4871 ALOGE("captureLayers called with a removed parent");
4872 return NAME_NOT_FOUND;
4873 }
4874
Robert Carr578038f2018-03-09 12:25:24 -08004875 const int uid = IPCThreadState::self()->getCallingUid();
4876 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4877 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4878 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4879 return PERMISSION_DENIED;
4880 }
4881
chaviw7206d492017-11-10 16:16:12 -08004882 Rect crop(sourceCrop);
4883 if (sourceCrop.width() <= 0) {
4884 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07004885 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08004886 }
4887
4888 if (sourceCrop.height() <= 0) {
4889 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07004890 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08004891 }
4892
4893 int32_t reqWidth = crop.width() * frameScale;
4894 int32_t reqHeight = crop.height() * frameScale;
4895
Robert Carr578038f2018-03-09 12:25:24 -08004896 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004897
Robert Carr578038f2018-03-09 12:25:24 -08004898 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004899 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4900 if (!layer->isVisible()) {
4901 return;
Robert Carr578038f2018-03-09 12:25:24 -08004902 } else if (childrenOnly && layer == parent.get()) {
4903 return;
chaviwa76b2712017-09-20 12:02:26 -07004904 }
4905 visitor(layer);
4906 });
4907 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004908 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004909}
4910
4911status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4912 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004913 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004914 bool useIdentityTransform) {
4915 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004916
Iris Chang7501ed62018-04-30 14:45:42 +08004917 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004918
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004919 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4920 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4921 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4922 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004923
4924 // This mutex protects syncFd and captureResult for communication of the return values from the
4925 // main thread back to this Binder thread
4926 std::mutex captureMutex;
4927 std::condition_variable captureCondition;
4928 std::unique_lock<std::mutex> captureLock(captureMutex);
4929 int syncFd = -1;
4930 std::optional<status_t> captureResult;
4931
Robert Carr03480e22018-01-04 16:02:06 -08004932 const int uid = IPCThreadState::self()->getCallingUid();
4933 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4934
Dominik Laskowski8c001672018-05-30 16:52:06 -07004935 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004936 // If there is a refresh pending, bug out early and tell the binder thread to try again
4937 // after the refresh.
4938 if (mRefreshPending) {
4939 ATRACE_NAME("Skipping screenshot for now");
4940 std::unique_lock<std::mutex> captureLock(captureMutex);
4941 captureResult = std::make_optional<status_t>(EAGAIN);
4942 captureCondition.notify_one();
4943 return;
4944 }
4945
4946 status_t result = NO_ERROR;
4947 int fd = -1;
4948 {
4949 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07004950 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08004951 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4952 useIdentityTransform, forSystem, &fd);
4953 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004954 }
4955
4956 {
4957 std::unique_lock<std::mutex> captureLock(captureMutex);
4958 syncFd = fd;
4959 captureResult = std::make_optional<status_t>(result);
4960 captureCondition.notify_one();
4961 }
4962 });
4963
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004964 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004965 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004966 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004967 while (*captureResult == EAGAIN) {
4968 captureResult.reset();
4969 result = postMessageAsync(message);
4970 if (result != NO_ERROR) {
4971 return result;
4972 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07004973 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004974 }
4975 result = *captureResult;
4976 }
4977
4978 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004979 sync_wait(syncFd, -1);
4980 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004981 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004982
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004983 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004984}
4985
chaviwa76b2712017-09-20 12:02:26 -07004986void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
4987 TraverseLayersFunction traverseLayers, bool yswap,
4988 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07004989 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07004990
Lloyd Pique144e1162017-12-20 16:44:52 -08004991 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004992
4993 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07004994 const auto raWidth = renderArea.getWidth();
4995 const auto raHeight = renderArea.getHeight();
4996
4997 const auto reqWidth = renderArea.getReqWidth();
4998 const auto reqHeight = renderArea.getReqHeight();
4999 Rect sourceCrop = renderArea.getSourceCrop();
5000
Iris Chang7501ed62018-04-30 14:45:42 +08005001 bool filtering = false;
5002 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5003 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5004 static_cast<int32_t>(reqHeight) != raWidth;
5005 } else {
5006 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5007 static_cast<int32_t>(reqHeight) != raHeight;
5008 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005009
Dan Stozac1879002014-05-22 15:59:05 -07005010 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005011 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005012 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005013 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005014 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
Peiyong Linefefaac2018-08-17 12:27:51 -07005015 ui::Transform tr;
Iris Chang7501ed62018-04-30 14:45:42 +08005016 uint32_t flags = 0x00;
5017 switch (mPrimaryDisplayOrientation) {
5018 case DisplayState::eOrientation90:
Peiyong Linefefaac2018-08-17 12:27:51 -07005019 flags = ui::Transform::ROT_90;
Iris Chang7501ed62018-04-30 14:45:42 +08005020 break;
5021 case DisplayState::eOrientation180:
Peiyong Linefefaac2018-08-17 12:27:51 -07005022 flags = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005023 break;
5024 case DisplayState::eOrientation270:
Peiyong Linefefaac2018-08-17 12:27:51 -07005025 flags = ui::Transform::ROT_270;
Iris Chang7501ed62018-04-30 14:45:42 +08005026 break;
5027 }
5028 tr.set(flags, raWidth, raHeight);
5029 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005030 }
5031
5032 // ensure that sourceCrop is inside screen
5033 if (sourceCrop.left < 0) {
5034 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5035 }
chaviwa76b2712017-09-20 12:02:26 -07005036 if (sourceCrop.right > raWidth) {
5037 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005038 }
5039 if (sourceCrop.top < 0) {
5040 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5041 }
chaviwa76b2712017-09-20 12:02:26 -07005042 if (sourceCrop.bottom > raHeight) {
5043 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005044 }
5045
Chia-I Wu36574d92018-05-16 10:54:36 -07005046 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5047 engine.setOutputDataSpace(Dataspace::SRGB);
5048 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005049
Mathias Agopian180f10d2013-04-10 22:55:41 -07005050 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005051 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005052
Peiyong Linefefaac2018-08-17 12:27:51 -07005053 ui::Transform::orientation_flags rotation = renderArea.getRotationFlags();
Iris Chang7501ed62018-04-30 14:45:42 +08005054 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5055 // convert hw orientation into flag presentation
5056 // here inverse transform needed
5057 uint8_t hw_rot_90 = 0x00;
5058 uint8_t hw_flip_hv = 0x00;
5059 switch (mPrimaryDisplayOrientation) {
5060 case DisplayState::eOrientation90:
Peiyong Linefefaac2018-08-17 12:27:51 -07005061 hw_rot_90 = ui::Transform::ROT_90;
5062 hw_flip_hv = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005063 break;
5064 case DisplayState::eOrientation180:
Peiyong Linefefaac2018-08-17 12:27:51 -07005065 hw_flip_hv = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005066 break;
5067 case DisplayState::eOrientation270:
Peiyong Linefefaac2018-08-17 12:27:51 -07005068 hw_rot_90 = ui::Transform::ROT_90;
Iris Chang7501ed62018-04-30 14:45:42 +08005069 break;
5070 }
5071
5072 // transform flags operation
5073 // 1) flip H V if both have ROT_90 flag
5074 // 2) XOR these flags
Peiyong Linefefaac2018-08-17 12:27:51 -07005075 uint8_t rotation_rot_90 = rotation & ui::Transform::ROT_90;
5076 uint8_t rotation_flip_hv = rotation & ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005077 if (rotation_rot_90 & hw_rot_90) {
Peiyong Linefefaac2018-08-17 12:27:51 -07005078 rotation_flip_hv = (~rotation_flip_hv) & ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005079 }
Peiyong Linefefaac2018-08-17 12:27:51 -07005080 rotation = static_cast<ui::Transform::orientation_flags>
Iris Chang7501ed62018-04-30 14:45:42 +08005081 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5082 }
5083
Mathias Agopian180f10d2013-04-10 22:55:41 -07005084 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005085 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005086 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005087 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005088
chaviw50da5042018-04-09 13:49:37 -07005089 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005090 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005091 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005092
chaviwa76b2712017-09-20 12:02:26 -07005093 traverseLayers([&](Layer* layer) {
5094 if (filtering) layer->setFiltering(true);
David Sodmanca10ed22018-04-16 14:10:25 -07005095 layer->drawNow(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005096 if (filtering) layer->setFiltering(false);
5097 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005098}
5099
chaviwa76b2712017-09-20 12:02:26 -07005100status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5101 TraverseLayersFunction traverseLayers,
5102 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005103 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005104 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005105 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005106 ATRACE_CALL();
5107
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005108 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005109
5110 traverseLayers([&](Layer* layer) {
5111 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5112 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005113
Robert Carr03480e22018-01-04 16:02:06 -08005114 // We allow the system server to take screenshots of secure layers for
5115 // use in situations like the Screen-rotation animation and place
5116 // the impetus on WindowManager to not persist them.
5117 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005118 ALOGW("FB is protected: PERMISSION_DENIED");
5119 return PERMISSION_DENIED;
5120 }
5121
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005122 // this binds the given EGLImage as a framebuffer for the
5123 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005124 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005125 if (bufferBond.getStatus() != NO_ERROR) {
5126 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005127 return INVALID_OPERATION;
5128 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005129
Dan Stozaabcda352017-06-01 14:37:39 -07005130 // this will in fact render into our dequeued buffer
5131 // via an FBO, which means we didn't have to create
5132 // an EGLSurface and therefore we're not
5133 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005134 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005135
Dan Stozaabcda352017-06-01 14:37:39 -07005136 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005137 getRenderEngine().finish();
5138 *outSyncFd = -1;
5139
chaviwa76b2712017-09-20 12:02:26 -07005140 const auto reqWidth = renderArea.getReqWidth();
5141 const auto reqHeight = renderArea.getReqHeight();
5142
Dan Stozaabcda352017-06-01 14:37:39 -07005143 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5144 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005145 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005146 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005147 } else {
5148 base::unique_fd syncFd = getRenderEngine().flush();
5149 if (syncFd < 0) {
5150 getRenderEngine().finish();
5151 }
5152 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005153 }
5154
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005155 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005156}
5157
Mathias Agopiand5556842013-09-19 17:08:37 -07005158void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005159 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005160 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005161 for (size_t y = 0; y < h; y++) {
5162 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5163 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005164 if (p[x] != 0xFF000000) return;
5165 }
5166 }
chaviwa76b2712017-09-20 12:02:26 -07005167 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005168
Robert Carr2047fae2016-11-28 14:09:09 -08005169 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005170 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005171 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005172 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5173 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5174 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5175 static_cast<float>(state.color.a));
5176 i++;
5177 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005178 }
5179}
5180
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005181// ---------------------------------------------------------------------------
5182
Dan Stoza412903f2017-04-27 13:42:17 -07005183void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5184 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005185}
5186
Dan Stoza412903f2017-04-27 13:42:17 -07005187void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5188 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005189}
5190
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005191void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5192 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005193 const LayerVector::Visitor& visitor) {
5194 // We loop through the first level of layers without traversing,
5195 // as we need to interpret min/max layer Z in the top level Z space.
5196 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005197 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005198 continue;
5199 }
5200 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005201 // relative layers are traversed in Layer::traverseInZOrder
5202 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005203 continue;
5204 }
5205 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005206 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005207 return;
5208 }
chaviwa76b2712017-09-20 12:02:26 -07005209 if (!layer->isVisible()) {
5210 return;
5211 }
5212 visitor(layer);
5213 });
5214 }
5215}
5216
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005217}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005218
Lloyd Pique074e8122018-07-26 12:57:23 -07005219
Mathias Agopian3f844832013-08-07 21:24:32 -07005220#if defined(__gl_h_)
5221#error "don't include gl/gl.h in this file"
5222#endif
5223
5224#if defined(__gl2_h_)
5225#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005226#endif