blob: 31d8deba019afd56af76cbfcc97767b86fbc39fe [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"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070081#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070082#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070083#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070084#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
Mathias Agopian875d8e12013-06-07 15:35:48 -070086#include "RenderEngine/RenderEngine.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070087#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070088#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070089#include "Scheduler/EventControlThread.h"
90#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070091#include "Scheduler/InjectVSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070092
Mathias Agopianff2ed702013-09-01 21:36:12 -070093#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070094
Jiyong Park4b20c2e2017-01-14 19:45:11 +090095#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080096#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
97#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090098#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090099
chaviw1d044282017-09-27 12:19:28 -0700100#include <layerproto/LayerProtoParser.h>
101
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800102#define DISPLAY_COUNT 1
103
Mathias Agopianfee2b462013-07-03 12:34:01 -0700104/*
105 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
106 * black pixels.
107 */
108#define DEBUG_SCREENSHOTS false
109
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800110namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700111
Jaesoo Lee43518572017-01-23 19:03:16 +0900112using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900113using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700114using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700115using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700116using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700117using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900118
Steven Thomasb02664d2017-07-26 18:48:28 -0700119namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700120
121#pragma clang diagnostic push
122#pragma clang diagnostic error "-Wswitch-enum"
123
124bool isWideColorMode(const ColorMode colorMode) {
125 switch (colorMode) {
126 case ColorMode::DISPLAY_P3:
127 case ColorMode::ADOBE_RGB:
128 case ColorMode::DCI_P3:
129 case ColorMode::BT2020:
130 case ColorMode::BT2100_PQ:
131 case ColorMode::BT2100_HLG:
132 return true;
133 case ColorMode::NATIVE:
134 case ColorMode::STANDARD_BT601_625:
135 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
136 case ColorMode::STANDARD_BT601_525:
137 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
138 case ColorMode::STANDARD_BT709:
139 case ColorMode::SRGB:
140 return false;
141 }
142 return false;
143}
144
145#pragma clang diagnostic pop
146
Steven Thomasb02664d2017-07-26 18:48:28 -0700147class ConditionalLock {
148public:
149 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
150 if (lock) {
151 mMutex.lock();
152 }
153 }
154 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
155private:
156 Mutex& mMutex;
157 bool mLocked;
158};
Peiyong Linfca547f2018-07-09 13:03:33 -0700159
Steven Thomasb02664d2017-07-26 18:48:28 -0700160} // namespace anonymous
161
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800162// ---------------------------------------------------------------------------
163
Mathias Agopian99b49842011-06-27 16:05:52 -0700164const String16 sHardwareTest("android.permission.HARDWARE_TEST");
165const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
166const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
167const String16 sDump("android.permission.DUMP");
168
169// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800170int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
171int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700172int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700173bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800174uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800175bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800176bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800177int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800178// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600179bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700180
Kalle Raitaa099a242017-01-11 11:17:29 -0800181
182std::string getHwcServiceName() {
183 char value[PROPERTY_VALUE_MAX] = {};
184 property_get("debug.sf.hwc_service_name", value, "default");
185 ALOGI("Using HWComposer service: '%s'", value);
186 return std::string(value);
187}
188
189bool useTrebleTestingOverride() {
190 char value[PROPERTY_VALUE_MAX] = {};
191 property_get("debug.sf.treble_testing_override", value, "false");
192 ALOGI("Treble testing override: '%s'", value);
193 return std::string(value) == "true";
194}
195
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800196std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
197 switch(displayColorSetting) {
198 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700199 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800200 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700201 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800202 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700203 return std::string("Enhanced");
204 default:
205 return std::string("Unknown ") +
206 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800207 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800208}
209
Lloyd Pique99d3da52018-01-22 17:48:03 -0800210NativeWindowSurface::~NativeWindowSurface() = default;
211
212namespace impl {
213
214class NativeWindowSurface final : public android::NativeWindowSurface {
215public:
216 static std::unique_ptr<android::NativeWindowSurface> create(
217 const sp<IGraphicBufferProducer>& producer) {
218 return std::make_unique<NativeWindowSurface>(producer);
219 }
220
221 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
222 : surface(new Surface(producer, false)) {}
223
224 ~NativeWindowSurface() override = default;
225
226private:
227 sp<ANativeWindow> getNativeWindow() const override { return surface; }
228
229 void preallocateBuffers() override { surface->allocateBuffers(); }
230
231 sp<Surface> surface;
232};
233
234} // namespace impl
235
David Sodmanbc815282017-11-05 18:57:52 -0800236SurfaceFlingerBE::SurfaceFlingerBE()
237 : mHwcServiceName(getHwcServiceName()),
238 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800239 mFrameBuckets(),
240 mTotalTime(0),
241 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800242 mComposerSequenceId(0) {
243}
244
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800245SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800246 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800247 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700248 mTransactionPending(false),
249 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700250 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700251 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700252 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800253 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700254 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800255 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800256 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800257 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800258 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800259 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700260 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700261 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700262 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700263 mDebugInSwapBuffers(0),
264 mLastSwapBufferTime(0),
265 mDebugInTransaction(0),
266 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700267 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700268 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700269 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800270 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800271 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800272 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700273 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800274 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800275 mCreateBufferQueue(&BufferQueue::createBufferQueue),
276 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800277
278SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800279 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800280
281 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
282 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
283
284 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
285 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
286
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800287 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
288 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800289
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700290 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
291 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
292
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700293 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
294 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
295
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800296 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
297 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
298
Steven Thomas050b2c82017-03-06 11:45:16 -0800299 // Vr flinger is only enabled on Daydream ready devices.
300 useVrFlinger = getBool< ISurfaceFlingerConfigs,
301 &ISurfaceFlingerConfigs::useVrFlinger>(false);
302
Fabien Sanglard1971b632017-03-10 14:50:03 -0800303 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
304 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
305
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600306 hasWideColorDisplay =
307 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
308
Iris Chang7501ed62018-04-30 14:45:42 +0800309 V1_1::DisplayOrientation primaryDisplayOrientation =
310 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
311 V1_1::DisplayOrientation::ORIENTATION_0);
312
313 switch (primaryDisplayOrientation) {
314 case V1_1::DisplayOrientation::ORIENTATION_90:
315 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
316 break;
317 case V1_1::DisplayOrientation::ORIENTATION_180:
318 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
319 break;
320 case V1_1::DisplayOrientation::ORIENTATION_270:
321 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
322 break;
323 default:
324 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
325 break;
326 }
327 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
328
Lloyd Pique41be5d22018-06-21 13:11:48 -0700329 // Note: We create a local temporary with the real DispSync implementation
330 // type temporarily so we can initialize it with the configured values,
331 // before storing it for more generic use using the interface type.
332 auto primaryDispSync = std::make_unique<impl::DispSync>("PrimaryDispSync");
333 primaryDispSync->init(SurfaceFlinger::hasSyncFramework,
334 SurfaceFlinger::dispSyncPresentTimeOffset);
335 mPrimaryDispSync = std::move(primaryDispSync);
Saurabh Shahf4174532017-07-13 10:45:07 -0700336
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800337 // debugging stuff...
338 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700339
Mathias Agopianb4b17302013-03-20 18:36:41 -0700340 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700341 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700342
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800343 property_get("debug.sf.showupdates", value, "0");
344 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700345
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700346 property_get("debug.sf.ddms", value, "0");
347 mDebugDDMS = atoi(value);
348 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700349 if (!startDdmConnection()) {
350 // start failed, and DDMS debugging not enabled
351 mDebugDDMS = 0;
352 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700353 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700354 ALOGI_IF(mDebugRegion, "showupdates enabled");
355 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700356
357 property_get("debug.sf.disable_backpressure", value, "0");
358 mPropagateBackpressure = !atoi(value);
359 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700360
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800361 property_get("debug.sf.enable_hwc_vds", value, "0");
362 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800363 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800364
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800365 property_get("ro.sf.disable_triple_buffer", value, "1");
366 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800367 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700368
Yiwei Zhang243b3782018-05-15 17:40:04 -0700369 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700370 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
371 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
372
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200373 property_get("debug.sf.early_phase_offset_ns", value, "-1");
374 const int earlySfOffsetNs = atoi(value);
375
376 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
377 const int earlyGlSfOffsetNs = atoi(value);
378
379 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
380 const int earlyAppOffsetNs = atoi(value);
381
382 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
383 const int earlyGlAppOffsetNs = atoi(value);
384
385 const VSyncModulator::Offsets earlyOffsets =
386 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
387 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
388 const VSyncModulator::Offsets earlyGlOffsets =
389 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
390 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
391 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
392 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700393
Romain Guy11d63f42017-07-20 12:47:14 -0700394 // We should be reading 'persist.sys.sf.color_saturation' here
395 // but since /data may be encrypted, we need to wait until after vold
396 // comes online to attempt to read the property. The property is
397 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800398
399 if (useTrebleTestingOverride()) {
400 // Without the override SurfaceFlinger cannot connect to HIDL
401 // services that are not listed in the manifests. Considered
402 // deriving the setting from the set service name, but it
403 // would be brittle if the name that's not 'default' is used
404 // for production purposes later on.
405 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
406 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800407}
408
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800409void SurfaceFlinger::onFirstRef()
410{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800411 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800412}
413
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800414SurfaceFlinger::~SurfaceFlinger()
415{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800416}
417
Dan Stozac7014012014-02-14 15:03:43 -0800418void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800419{
420 // the window manager died on us. prepare its eulogy.
421
Andy McFadden13a082e2012-08-24 10:16:42 -0700422 // restore initial conditions (default device unblank, etc)
423 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800424
425 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700426 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800427}
428
Robert Carr1db73f62016-12-21 12:58:51 -0800429static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700430 status_t err = client->initCheck();
431 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800432 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800433 }
Robert Carr1db73f62016-12-21 12:58:51 -0800434 return nullptr;
435}
436
437sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
438 return initClient(new Client(this));
439}
440
441sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
442 const sp<IGraphicBufferProducer>& gbp) {
443 if (authenticateSurfaceTexture(gbp) == false) {
444 return nullptr;
445 }
446 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
447 if (layer == nullptr) {
448 return nullptr;
449 }
450
451 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800452}
453
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700454sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
455 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700456{
457 class DisplayToken : public BBinder {
458 sp<SurfaceFlinger> flinger;
459 virtual ~DisplayToken() {
460 // no more references, this display must be terminated
461 Mutex::Autolock _l(flinger->mStateLock);
462 flinger->mCurrentState.displays.removeItem(this);
463 flinger->setTransactionFlags(eDisplayTransactionNeeded);
464 }
465 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700466 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700467 : flinger(flinger) {
468 }
469 };
470
471 sp<BBinder> token = new DisplayToken(this);
472
473 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700474 DisplayDeviceState info;
475 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700476 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700477 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700478 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800479 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700480 return token;
481}
482
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700483void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700484 Mutex::Autolock _l(mStateLock);
485
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700486 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700487 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700488 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700489 return;
490 }
491
492 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700493 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700494 ALOGE("destroyDisplay called for non-virtual display");
495 return;
496 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700497 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700498 mCurrentState.displays.removeItemsAt(idx);
499 setTransactionFlags(eDisplayTransactionNeeded);
500}
501
Mathias Agopiane57f2922012-08-09 16:29:12 -0700502sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700503 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700504 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800505 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700506 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700507 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700508}
509
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800510void SurfaceFlinger::bootFinished()
511{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700512 if (mStartPropertySetThread->join() != NO_ERROR) {
513 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800514 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800515 const nsecs_t now = systemTime();
516 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000517 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700518
519 // wait patiently for the window manager death
520 const String16 name("window");
521 sp<IBinder> window(defaultServiceManager()->getService(name));
522 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700523 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700524 }
525
Steven Thomas050b2c82017-03-06 11:45:16 -0800526 if (mVrFlinger) {
527 mVrFlinger->OnBootFinished();
528 }
529
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700530 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700531 // formerly we would just kill the process, but we now ask it to exit so it
532 // can choose where to stop the animation.
533 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700534
535 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
536 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
537 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700538
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800539 postMessageAsync(new LambdaMessage([this] {
540 readPersistentProperties();
541 mBootStage = BootStage::FINISHED;
542 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800543}
544
Dan Stoza436ccf32018-06-21 12:10:12 -0700545uint32_t SurfaceFlinger::getNewTexture() {
546 {
547 std::lock_guard lock(mTexturePoolMutex);
548 if (!mTexturePool.empty()) {
549 uint32_t name = mTexturePool.back();
550 mTexturePool.pop_back();
551 ATRACE_INT("TexturePoolSize", mTexturePool.size());
552 return name;
553 }
554
555 // The pool was too small, so increase it for the future
556 ++mTexturePoolSize;
557 }
558
559 // The pool was empty, so we need to get a new texture name directly using a
560 // blocking call to the main thread
561 uint32_t name = 0;
562 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
563 return name;
564}
565
Mathias Agopian3f844832013-08-07 21:24:32 -0700566void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700567 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700568}
569
Wei Wangf9b05ee2017-07-19 20:59:39 -0700570// Do not call property_set on main thread which will be blocked by init
571// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700572void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700573 ALOGI( "SurfaceFlinger's main thread ready to run. "
574 "Initializing graphics H/W...");
575
Thierry Strudel2924d012017-08-14 15:19:37 -0700576 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900577
Steven Thomasb02664d2017-07-26 18:48:28 -0700578 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800579
Steven Thomasb02664d2017-07-26 18:48:28 -0700580 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800581 mEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700582 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
583 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800584 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700585 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800586 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800587 "appEventThread");
588 mSfEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700589 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800590 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800591
Lloyd Pique24b0a482018-03-09 18:52:26 -0800592 mSFEventThread =
593 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700594 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800595 [this](nsecs_t timestamp) {
596 mInterceptor->saveVSyncEvent(timestamp);
597 },
598 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800599 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200600 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800601
Steven Thomasb02664d2017-07-26 18:48:28 -0700602 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800603 getBE().mRenderEngine =
604 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
605 hasWideColorDisplay
606 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
607 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800608 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700609
610 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
611 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800612 getBE().mHwc.reset(
613 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700614 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800615 // Process any initial hotplug and resulting display changes.
616 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700617 const auto display = getDefaultDisplayDeviceLocked();
618 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
619 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
620 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800621
Lloyd Piquefcd86612017-12-14 17:15:36 -0800622 // make the default display GLContext current so that we can create textures
623 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700624 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800625
Steven Thomas050b2c82017-03-06 11:45:16 -0800626 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700627 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700628 // This callback is called from the vr flinger dispatch thread. We
629 // need to call signalTransaction(), which requires holding
630 // mStateLock when we're not on the main thread. Acquiring
631 // mStateLock from the vr flinger dispatch thread might trigger a
632 // deadlock in surface flinger (see b/66916578), so post a message
633 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700634 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700635 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
636 mVrFlingerRequestsDisplay = requestDisplay;
637 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700638 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800639 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700640 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
641 getHwComposer()
642 .getHwcDisplayId(display->getId())
643 .value_or(0),
644 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800645 if (!mVrFlinger) {
646 ALOGE("Failed to start vrflinger");
647 }
648 }
649
Lloyd Pique379adc12018-01-22 17:31:47 -0800650 mEventControlThread = std::make_unique<impl::EventControlThread>(
651 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700652
Mathias Agopian92a979a2012-08-02 18:32:23 -0700653 // initialize our drawing state
654 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700655
Andy McFadden13a082e2012-08-24 10:16:42 -0700656 // set initial conditions (e.g. unblank default device)
657 initializeDisplays();
658
David Sodmanbc815282017-11-05 18:57:52 -0800659 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700660
Wei Wangf9b05ee2017-07-19 20:59:39 -0700661 // Inform native graphics APIs whether the present timestamp is supported:
662 if (getHwComposer().hasCapability(
663 HWC2::Capability::PresentFenceIsNotReliable)) {
664 mStartPropertySetThread = new StartPropertySetThread(false);
665 } else {
666 mStartPropertySetThread = new StartPropertySetThread(true);
667 }
668
669 if (mStartPropertySetThread->Start() != NO_ERROR) {
670 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800671 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800672
Chia-I Wud49d6692018-06-27 07:17:41 +0800673 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
674 // is used to saturate legacy sRGB content. However, to make sure the same color under
675 // Display P3 will be saturated to the same color, we intentionally break the API spec
676 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
677 // such saturation matrix on Display P3 is understood fully, the API should always return
678 // identify matrix.
679 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
680 Dataspace::SRGB_LINEAR);
681
682 // we will apply this on Display P3.
683 if (mEnhancedSaturationMatrix != mat4()) {
684 ColorSpace srgb(ColorSpace::sRGB());
685 ColorSpace displayP3(ColorSpace::DisplayP3());
686 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
687 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
688 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
689 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800690
Dan Stoza9e56aa02015-11-02 13:00:03 -0800691 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700692}
693
Romain Guy11d63f42017-07-20 12:47:14 -0700694void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700695 Mutex::Autolock _l(mStateLock);
696
Romain Guy11d63f42017-07-20 12:47:14 -0700697 char value[PROPERTY_VALUE_MAX];
698
699 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800700 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700701 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800702 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100703
704 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700705 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700706}
707
Mathias Agopiana67e4182012-06-19 17:26:12 -0700708void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800709 // Start boot animation service by setting a property mailbox
710 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700711 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800712 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700713 if (mStartPropertySetThread->join() != NO_ERROR) {
714 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800715 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700716}
717
Mathias Agopian875d8e12013-06-07 15:35:48 -0700718size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800719 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700720}
721
Mathias Agopian875d8e12013-06-07 15:35:48 -0700722size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800723 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700724}
725
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800726// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800727
Jamie Gennis582270d2011-08-17 18:19:00 -0700728bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800729 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800730 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800731 return authenticateSurfaceTextureLocked(bufferProducer);
732}
733
734bool SurfaceFlinger::authenticateSurfaceTextureLocked(
735 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800736 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800737 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800738}
739
Brian Anderson6b376712017-04-04 10:51:39 -0700740status_t SurfaceFlinger::getSupportedFrameTimestamps(
741 std::vector<FrameEvent>* outSupported) const {
742 *outSupported = {
743 FrameEvent::REQUESTED_PRESENT,
744 FrameEvent::ACQUIRE,
745 FrameEvent::LATCH,
746 FrameEvent::FIRST_REFRESH_START,
747 FrameEvent::LAST_REFRESH_START,
748 FrameEvent::GPU_COMPOSITION_DONE,
749 FrameEvent::DEQUEUE_READY,
750 FrameEvent::RELEASE,
751 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700752 ConditionalLock _l(mStateLock,
753 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700754 if (!getHwComposer().hasCapability(
755 HWC2::Capability::PresentFenceIsNotReliable)) {
756 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
757 }
758 return NO_ERROR;
759}
760
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700761status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
762 Vector<DisplayInfo>* configs) {
763 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700764 return BAD_VALUE;
765 }
766
Jesse Hall692c7232012-11-08 15:41:56 -0800767 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700768 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
769 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700770 type = i;
771 break;
772 }
773 }
774
775 if (type < 0) {
776 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700777 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700778
Mathias Agopian8b736f12012-08-13 17:54:26 -0700779 // TODO: Not sure if display density should handled by SF any longer
780 class Density {
781 static int getDensityFromProperty(char const* propName) {
782 char property[PROPERTY_VALUE_MAX];
783 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800784 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700785 density = atoi(property);
786 }
787 return density;
788 }
789 public:
790 static int getEmuDensity() {
791 return getDensityFromProperty("qemu.sf.lcd_density"); }
792 static int getBuildDensity() {
793 return getDensityFromProperty("ro.sf.lcd_density"); }
794 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700795
Dan Stoza7f7da322014-05-02 15:26:25 -0700796 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700797
Steven Thomas6d8110b2017-08-31 18:24:21 -0700798 ConditionalLock _l(mStateLock,
799 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800800 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700801 DisplayInfo info = DisplayInfo();
802
Dan Stoza9e56aa02015-11-02 13:00:03 -0800803 float xdpi = hwConfig->getDpiX();
804 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700805
806 if (type == DisplayDevice::DISPLAY_PRIMARY) {
807 // The density of the device is provided by a build property
808 float density = Density::getBuildDensity() / 160.0f;
809 if (density == 0) {
810 // the build doesn't provide a density -- this is wrong!
811 // use xdpi instead
812 ALOGE("ro.sf.lcd_density must be defined as a build property");
813 density = xdpi / 160.0f;
814 }
815 if (Density::getEmuDensity()) {
816 // if "qemu.sf.lcd_density" is specified, it overrides everything
817 xdpi = ydpi = density = Density::getEmuDensity();
818 density /= 160.0f;
819 }
820 info.density = density;
821
822 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700823 const auto display = getDefaultDisplayDeviceLocked();
824 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700825 } else {
826 // TODO: where should this value come from?
827 static const int TV_DENSITY = 213;
828 info.density = TV_DENSITY / 160.0f;
829 info.orientation = 0;
830 }
831
Dan Stoza9e56aa02015-11-02 13:00:03 -0800832 info.w = hwConfig->getWidth();
833 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700834 info.xdpi = xdpi;
835 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800836 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900837 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800838
Andy McFadden91b2ca82014-06-13 14:04:23 -0700839 // This is how far in advance a buffer must be queued for
840 // presentation at a given time. If you want a buffer to appear
841 // on the screen at time N, you must submit the buffer before
842 // (N - presentationDeadline).
843 //
844 // Normally it's one full refresh period (to give SF a chance to
845 // latch the buffer), but this can be reduced by configuring a
846 // DispSync offset. Any additional delays introduced by the hardware
847 // composer or panel must be accounted for here.
848 //
849 // We add an additional 1ms to allow for processing time and
850 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800851 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800852 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700853
854 // All non-virtual displays are currently considered secure.
855 info.secure = true;
856
Iris Chang7501ed62018-04-30 14:45:42 +0800857 if (type == DisplayDevice::DISPLAY_PRIMARY &&
858 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
859 std::swap(info.w, info.h);
860 }
861
Michael Wright28f24d02016-07-12 13:30:53 -0700862 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700863 }
864
Dan Stoza7f7da322014-05-02 15:26:25 -0700865 return NO_ERROR;
866}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700867
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700868status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
869 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700870 return BAD_VALUE;
871 }
872
873 // FIXME for now we always return stats for the primary display
874 memset(stats, 0, sizeof(*stats));
Lloyd Pique41be5d22018-06-21 13:11:48 -0700875 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
876 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700877 return NO_ERROR;
878}
879
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700880int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
881 const auto display = getDisplayDevice(displayToken);
882 if (!display) {
883 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800884 return BAD_VALUE;
885 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700886
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700887 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700888}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700889
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700890void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
891 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700892 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700893 return;
894 }
895
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700896 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700897 ALOGW("Trying to set config for virtual display");
898 return;
899 }
900
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700901 display->setActiveConfig(mode);
902 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700903}
904
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700905status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700906 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700907 Vector<DisplayInfo> configs;
908 getDisplayConfigs(displayToken, &configs);
909 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
910 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
911 configs.size());
912 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700913 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700914 const auto display = getDisplayDevice(displayToken);
915 if (!display) {
916 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
917 displayToken.get());
918 } else if (display->isVirtual()) {
919 ALOGW("Attempt to set active config %d for virtual display", mode);
920 } else {
921 setActiveConfigInternal(display, mode);
922 }
923 }));
924
Mathias Agopian888c8222012-08-04 21:10:38 -0700925 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700926}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700927status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
928 Vector<ColorMode>* outColorModes) {
929 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700930 return BAD_VALUE;
931 }
932
Michael Wright28f24d02016-07-12 13:30:53 -0700933 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700934 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
935 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700936 type = i;
937 break;
938 }
939 }
940
941 if (type < 0) {
942 return type;
943 }
944
Peiyong Lina52f0292018-03-14 17:26:31 -0700945 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700946 {
947 ConditionalLock _l(mStateLock,
948 std::this_thread::get_id() != mMainThreadId);
949 modes = getHwComposer().getColorModes(type);
950 }
Michael Wright28f24d02016-07-12 13:30:53 -0700951 outColorModes->clear();
952 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
953
954 return NO_ERROR;
955}
956
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700957ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
958 if (const auto display = getDisplayDevice(displayToken)) {
959 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700960 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700961 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700962}
963
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700964void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
965 Dataspace dataSpace, RenderIntent renderIntent) {
966 ColorMode currentMode = display->getActiveColorMode();
967 Dataspace currentDataSpace = display->getCompositionDataSpace();
968 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -0700969
Peiyong Lin38e9a562018-04-10 16:24:20 -0700970 if (mode == currentMode && dataSpace == currentDataSpace &&
971 renderIntent == currentRenderIntent) {
972 return;
973 }
974
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700975 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -0700976 ALOGW("Trying to set config for virtual display");
977 return;
978 }
979
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700980 display->setActiveColorMode(mode);
981 display->setCompositionDataSpace(dataSpace);
982 display->setActiveRenderIntent(renderIntent);
983 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800984
985 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700986 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
987 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -0700988}
989
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700990status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700991 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700992 Vector<ColorMode> modes;
993 getDisplayColorModes(displayToken, &modes);
994 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
995 if (mode < ColorMode::NATIVE || !exists) {
996 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
997 decodeColorMode(mode).c_str(), mode, displayToken.get());
998 return;
Michael Wright28f24d02016-07-12 13:30:53 -0700999 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001000 const auto display = getDisplayDevice(displayToken);
1001 if (!display) {
1002 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1003 decodeColorMode(mode).c_str(), mode, displayToken.get());
1004 } else if (display->isVirtual()) {
1005 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1006 decodeColorMode(mode).c_str(), mode);
1007 } else {
1008 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1009 RenderIntent::COLORIMETRIC);
1010 }
1011 }));
1012
Michael Wright28f24d02016-07-12 13:30:53 -07001013 return NO_ERROR;
1014}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001015
Svetoslavd85084b2014-03-20 10:28:31 -07001016status_t SurfaceFlinger::clearAnimationFrameStats() {
1017 Mutex::Autolock _l(mStateLock);
1018 mAnimFrameTracker.clearStats();
1019 return NO_ERROR;
1020}
1021
1022status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1023 Mutex::Autolock _l(mStateLock);
1024 mAnimFrameTracker.getStats(outStats);
1025 return NO_ERROR;
1026}
1027
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001028status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1029 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001030 Mutex::Autolock _l(mStateLock);
1031
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001032 const auto display = getDisplayDeviceLocked(displayToken);
1033 if (!display) {
1034 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001035 return BAD_VALUE;
1036 }
1037
Peiyong Linfb069302018-04-25 14:34:31 -07001038 // At this point the DisplayDeivce should already be set up,
1039 // meaning the luminance information is already queried from
1040 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001041 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001042 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1043 capabilities.getDesiredMaxLuminance(),
1044 capabilities.getDesiredMaxAverageLuminance(),
1045 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001046
1047 return NO_ERROR;
1048}
1049
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001050status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001051 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001052 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001053
Chia-I Wu90f669f2017-10-05 14:24:41 -07001054 if (mInjectVSyncs == enable) {
1055 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001056 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001057
1058 if (enable) {
1059 ALOGV("VSync Injections enabled");
1060 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001061 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001062 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001063 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001064 impl::EventThread::InterceptVSyncsCallback(),
1065 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001066 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001067 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001068 } else {
1069 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001070 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001071 }
1072
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001073 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001074 }));
1075
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001076 return NO_ERROR;
1077}
1078
1079status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001080 Mutex::Autolock _l(mStateLock);
1081
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001082 if (!mInjectVSyncs) {
1083 ALOGE("VSync Injections not enabled");
1084 return BAD_VALUE;
1085 }
1086 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1087 ALOGV("Injecting VSync inside SurfaceFlinger");
1088 mVSyncInjector->onInjectSyncEvent(when);
1089 }
1090 return NO_ERROR;
1091}
1092
Lloyd Pique755e3192018-01-31 16:46:15 -08001093status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1094 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001095 // Try to acquire a lock for 1s, fail gracefully
1096 const status_t err = mStateLock.timedLock(s2ns(1));
1097 const bool locked = (err == NO_ERROR);
1098 if (!locked) {
1099 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1100 return TIMED_OUT;
1101 }
1102
1103 outLayers->clear();
1104 mCurrentState.traverseInZOrder([&](Layer* layer) {
1105 outLayers->push_back(layer->getLayerDebugInfo());
1106 });
1107
1108 mStateLock.unlock();
1109 return NO_ERROR;
1110}
1111
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001112// ----------------------------------------------------------------------------
1113
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001114sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1115 ISurfaceComposer::VsyncSource vsyncSource) {
1116 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1117 return mSFEventThread->createEventConnection();
1118 } else {
1119 return mEventThread->createEventConnection();
1120 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001121}
1122
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001123// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001124
1125void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001126 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001127}
1128
1129void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001130 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001131}
1132
1133void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001134 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001135}
1136
1137void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001138 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001139 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001140}
1141
1142status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001143 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001144 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001145}
1146
1147status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001148 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001149 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001150 if (res == NO_ERROR) {
1151 msg->wait();
1152 }
1153 return res;
1154}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001155
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001156void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001157 do {
1158 waitForEvent();
1159 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001160}
1161
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001162void SurfaceFlinger::enableHardwareVsync() {
1163 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001164 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001165 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001166 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001167 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001168 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001169}
1170
Jesse Hall948fe0c2013-10-14 12:56:09 -07001171void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001172 Mutex::Autolock _l(mHWVsyncLock);
1173
Jesse Hall948fe0c2013-10-14 12:56:09 -07001174 if (makeAvailable) {
1175 mHWVsyncAvailable = true;
1176 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001177 // Hardware vsync is not currently available, so abort the resync
1178 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001179 return;
1180 }
1181
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001182 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1183 if (!getHwComposer().isConnected(displayId)) {
1184 return;
1185 }
1186
1187 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001188 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001189
Lloyd Pique41be5d22018-06-21 13:11:48 -07001190 mPrimaryDispSync->reset();
1191 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001192
1193 if (!mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001194 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001195 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001196 mPrimaryHWVsyncEnabled = true;
1197 }
1198}
1199
Jesse Hall948fe0c2013-10-14 12:56:09 -07001200void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001201 Mutex::Autolock _l(mHWVsyncLock);
1202 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001203 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001204 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001205 mPrimaryHWVsyncEnabled = false;
1206 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001207 if (makeUnavailable) {
1208 mHWVsyncAvailable = false;
1209 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001210}
1211
Tim Murray4a4e4a22016-04-19 16:29:23 +00001212void SurfaceFlinger::resyncWithRateLimit() {
1213 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001214
1215 // No explicit locking is needed here since EventThread holds a lock while calling this method
1216 static nsecs_t sLastResyncAttempted = 0;
1217 const nsecs_t now = systemTime();
1218 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001219 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001220 }
Dan Stoza57164302017-05-08 14:03:54 -07001221 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001222}
1223
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001224void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1225 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001226 ATRACE_NAME("SF onVsync");
1227
Steven Thomas3cfac282017-02-06 12:29:30 -08001228 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001229 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001230 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001231 return;
1232 }
1233
1234 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001235 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001236 return;
1237 }
1238
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001239 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1240 // For now, we don't do anything with external display vsyncs.
1241 return;
1242 }
1243
Jamie Gennisd1700752013-10-14 12:22:52 -07001244 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001245
Jamie Gennisd1700752013-10-14 12:22:52 -07001246 { // Scope for the lock
1247 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001248 if (mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001249 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001250 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001251 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001252
1253 if (needsHwVsync) {
1254 enableHardwareVsync();
1255 } else {
1256 disableHardwareVsync(false);
1257 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001258}
1259
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001260void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001261 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1262 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001263}
1264
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001265void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001266 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001267 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001268 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001269
Lloyd Piqueba04e622017-12-14 17:11:26 -08001270 // Ignore events that do not have the right sequenceId.
1271 if (sequenceId != getBE().mComposerSequenceId) {
1272 return;
1273 }
1274
Steven Thomasb02664d2017-07-26 18:48:28 -07001275 // Only lock if we're not on the main thread. This function is normally
1276 // called on a hwbinder thread, but for the primary display it's called on
1277 // the main thread with the state lock already held, so don't attempt to
1278 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001279 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001280
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001281 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001282
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001283 if (std::this_thread::get_id() == mMainThreadId) {
1284 // Process all pending hot plug events immediately if we are on the main thread.
1285 processDisplayHotplugEventsLocked();
1286 }
1287
Lloyd Piqueba04e622017-12-14 17:11:26 -08001288 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001289}
1290
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001291void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001292 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001293 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001294 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001295 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001296 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001297}
1298
Dan Stoza9e56aa02015-11-02 13:00:03 -08001299void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001300 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001301 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001302 getHwComposer().setVsyncEnabled(disp,
1303 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001304}
1305
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001306// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001307void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001308 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001309 // Clear the drawing state so that the logic inside of
1310 // handleTransactionLocked will fire. It will determine the delta between
1311 // mCurrentState and mDrawingState and re-apply all changes when we make the
1312 // transition.
1313 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001314 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001315 mDisplays.clear();
1316}
1317
Steven Thomas050b2c82017-03-06 11:45:16 -08001318void SurfaceFlinger::updateVrFlinger() {
1319 if (!mVrFlinger)
1320 return;
1321 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001322 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001323 return;
1324 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001325
David Sodman105b7dc2017-11-04 20:28:14 -07001326 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001327 ALOGE("Vr flinger is only supported for remote hardware composer"
1328 " service connections. Ignoring request to transition to vr"
1329 " flinger.");
1330 mVrFlingerRequestsDisplay = false;
1331 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001332 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001333
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001334 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001335
Steven Thomas0123ac62018-07-12 11:32:34 -07001336 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001337 LOG_ALWAYS_FATAL_IF(!display);
1338 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001339 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1340 // called below. Clear the reference now so we don't accidentally use it
1341 // later.
1342 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001343
Steven Thomasb02664d2017-07-26 18:48:28 -07001344 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001345 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001346 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001347
Steven Thomasb02664d2017-07-26 18:48:28 -07001348 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001349 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001350 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1351 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001352 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001353
David Sodman105b7dc2017-11-04 20:28:14 -07001354 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1355 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001356
1357 if (vrFlingerRequestsDisplay) {
1358 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001359 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001360
1361 mVisibleRegionsDirty = true;
1362 invalidateHwcGeometry();
1363
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001364 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001365 display = getDefaultDisplayDeviceLocked();
1366 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001367 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001368
Steven Thomasb02664d2017-07-26 18:48:28 -07001369 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001370 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001371 const nsecs_t period = activeConfig->getVsyncPeriod();
1372 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001373
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001374 // The present fences returned from vr_hwc are not an accurate
1375 // representation of vsync times.
Lloyd Pique41be5d22018-06-21 13:11:48 -07001376 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1377 !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001378
Steven Thomasb02664d2017-07-26 18:48:28 -07001379 // Use phase of 0 since phase is not known.
1380 // Use latency of 0, which will snap to the ideal latency.
1381 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001382
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001383 resyncToHardwareVsync(false);
1384
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001385 android_atomic_or(1, &mRepaintEverything);
1386 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001387}
1388
Mathias Agopian4fec8732012-06-29 14:12:52 -07001389void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001390 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001391 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001392 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001393 bool frameMissed = !mHadClientComposition &&
1394 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001395 (mPreviousPresentFence->getSignalTime() ==
1396 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001397 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001398 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001399 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001400 mTimeStats.incrementMissedFrames();
1401 if (mPropagateBackpressure) {
1402 signalLayerUpdate();
1403 break;
1404 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001405 }
Dan Stoza50182882016-07-08 12:02:20 -07001406
Steven Thomas050b2c82017-03-06 11:45:16 -08001407 // Now that we're going to make it to the handleMessageTransaction()
1408 // call below it's safe to call updateVrFlinger(), which will
1409 // potentially trigger a display handoff.
1410 updateVrFlinger();
1411
Dan Stoza6b9454d2014-11-07 16:00:59 -08001412 bool refreshNeeded = handleMessageTransaction();
1413 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001414 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001415 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001416 // Signal a refresh if a transaction modified the window state,
1417 // a new buffer was latched, or if HWC has requested a full
1418 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001419 signalRefresh();
1420 }
1421 break;
1422 }
1423 case MessageQueue::REFRESH: {
1424 handleMessageRefresh();
1425 break;
1426 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001427 }
1428}
1429
Dan Stoza6b9454d2014-11-07 16:00:59 -08001430bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001431 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001432 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001433 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001434 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001435 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001436 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001437}
1438
Dan Stoza6b9454d2014-11-07 16:00:59 -08001439bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001440 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001441 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001442}
1443
1444void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001445 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001446
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001447 mRefreshPending = false;
1448
David Sodman2b406362017-12-15 13:33:47 -08001449 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001450 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001451 calculateWorkingSet();
David Sodman2b406362017-12-15 13:33:47 -08001452 beginFrame();
1453 prepareFrame();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001454 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001455 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001456 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001457 doComposition();
David Sodman2b406362017-12-15 13:33:47 -08001458 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001459
Dan Stozabfbffeb2016-07-21 14:49:33 -07001460 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001461 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001462 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001463 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001464 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001465 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001466
Dan Stoza9e56aa02015-11-02 13:00:03 -08001467 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001468}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001469
David Sodman79bba0e2018-08-05 18:07:49 -07001470void SurfaceFlinger::calculateWorkingSet() {
1471 ATRACE_CALL();
1472 ALOGV(__FUNCTION__);
1473
David Sodman79bba0e2018-08-05 18:07:49 -07001474 // build the h/w work list
1475 if (CC_UNLIKELY(mGeometryInvalid)) {
1476 mGeometryInvalid = false;
1477 for (const auto& [token, display] : mDisplays) {
1478 const auto displayId = display->getId();
1479 if (displayId >= 0) {
1480 const Vector<sp<Layer>>& currentLayers(
1481 display->getVisibleLayersSortedByZ());
1482 for (size_t i = 0; i < currentLayers.size(); i++) {
1483 const auto& layer = currentLayers[i];
1484
1485 if (!layer->hasHwcLayer(displayId)) {
1486 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1487 layer->forceClientComposition(displayId);
1488 continue;
1489 }
1490 }
1491
1492 layer->setGeometry(display, i);
1493 if (mDebugDisableHWC || mDebugRegion) {
1494 layer->forceClientComposition(displayId);
1495 }
1496 }
1497 }
1498 }
1499 }
1500
1501 // Set the per-frame data
1502 for (const auto& [token, display] : mDisplays) {
1503 const auto displayId = display->getId();
1504 if (displayId < 0) {
1505 continue;
1506 }
1507
1508 if (mDrawingState.colorMatrixChanged) {
1509 display->setColorTransform(mDrawingState.colorMatrix);
1510 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1511 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1512 "display %d: %d", displayId, result);
1513 }
1514 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1515 if (layer->isHdrY410()) {
1516 layer->forceClientComposition(displayId);
1517 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1518 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1519 !display->hasHDR10Support()) {
1520 layer->forceClientComposition(displayId);
1521 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1522 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1523 !display->hasHLGSupport()) {
1524 layer->forceClientComposition(displayId);
1525 }
1526
1527 if (layer->getForceClientComposition(displayId)) {
1528 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1529 layer->setCompositionType(displayId, HWC2::Composition::Client);
1530 continue;
1531 }
1532
1533 layer->setPerFrameData(display);
1534 }
1535
1536 if (hasWideColorDisplay) {
1537 ColorMode colorMode;
1538 Dataspace dataSpace;
1539 RenderIntent renderIntent;
1540 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1541 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1542 }
1543 }
1544
1545 mDrawingState.colorMatrixChanged = false;
David Sodman79bba0e2018-08-05 18:07:49 -07001546}
1547
Mathias Agopiancd60f992012-08-16 16:28:27 -07001548void SurfaceFlinger::doDebugFlashRegions()
1549{
1550 // is debugging enabled
1551 if (CC_LIKELY(!mDebugRegion))
1552 return;
1553
1554 const bool repaintEverything = mRepaintEverything;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001555 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001556 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001557 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001558 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001559 if (!dirtyRegion.isEmpty()) {
1560 // redraw the whole screen
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001561 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001562
1563 // and draw the dirty region
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001564 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001565 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001566 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1567
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001568 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001569 }
1570 }
1571 }
1572
1573 postFramebuffer();
1574
1575 if (mDebugRegion > 1) {
1576 usleep(mDebugRegion * 1000);
1577 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001578
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001579 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001580 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001581 continue;
1582 }
1583
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001584 status_t result = display->prepareFrame(*getBE().mHwc);
1585 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001586 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001587 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001588}
1589
Adrian Roos1e1a1282017-11-01 19:05:31 +01001590void SurfaceFlinger::doTracing(const char* where) {
1591 ATRACE_CALL();
1592 ATRACE_NAME(where);
1593 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001594 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001595 }
1596}
1597
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001598void SurfaceFlinger::logLayerStats() {
1599 ATRACE_CALL();
1600 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001601 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001602 if (display->isPrimary()) {
1603 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001604 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001605 }
1606 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001607
1608 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001609 }
1610}
1611
David Sodman2b406362017-12-15 13:33:47 -08001612void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001613{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001614 ATRACE_CALL();
1615 ALOGV("preComposition");
1616
David Sodman2b406362017-12-15 13:33:47 -08001617 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1618
Mathias Agopiancd60f992012-08-16 16:28:27 -07001619 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001620 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001621 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001622 needExtraInvalidate = true;
1623 }
Robert Carr2047fae2016-11-28 14:09:09 -08001624 });
1625
Mathias Agopiancd60f992012-08-16 16:28:27 -07001626 if (needExtraInvalidate) {
1627 signalLayerUpdate();
1628 }
1629}
1630
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001631void SurfaceFlinger::updateCompositorTiming(
1632 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1633 std::shared_ptr<FenceTime>& presentFenceTime) {
1634 // Update queue of past composite+present times and determine the
1635 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001636 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001637 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001638 while (!getBE().mCompositePresentTimes.empty()) {
1639 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001640 // Cached values should have been updated before calling this method,
1641 // which helps avoid duplicate syscalls.
1642 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1643 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1644 break;
1645 }
1646 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001647 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001648 }
1649
1650 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001651 while (getBE().mCompositePresentTimes.size() > 16) {
1652 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001653 }
1654
Brian Andersond0010582017-03-07 13:20:31 -08001655 setCompositorTimingSnapped(
1656 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1657}
1658
1659void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1660 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001661 // Integer division and modulo round toward 0 not -inf, so we need to
1662 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001663 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001664 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1665 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1666
Brian Andersond0010582017-03-07 13:20:31 -08001667 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1668 if (idealLatency <= 0) {
1669 idealLatency = vsyncInterval;
1670 }
1671
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001672 // Snap the latency to a value that removes scheduling jitter from the
1673 // composition and present times, which often have >1ms of jitter.
1674 // Reducing jitter is important if an app attempts to extrapolate
1675 // something (such as user input) to an accurate diasplay time.
1676 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1677 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001678 nsecs_t bias = vsyncInterval / 2;
1679 int64_t extraVsyncs =
1680 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1681 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1682 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001683
David Sodman99974d22017-11-28 12:04:33 -08001684 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1685 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1686 getBE().mCompositorTiming.interval = vsyncInterval;
1687 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001688}
1689
David Sodman2b406362017-12-15 13:33:47 -08001690void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001691{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001692 ATRACE_CALL();
1693 ALOGV("postComposition");
1694
Brian Anderson3546a3f2016-07-14 11:51:14 -07001695 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001696 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001697 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001698 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001699 }
1700
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001701 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001702 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001703
David Sodman73beded2017-11-15 11:56:06 -08001704 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001705 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001706 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001707 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001708 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001709 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001710 } else {
1711 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1712 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001713
David Sodman73beded2017-11-15 11:56:06 -08001714 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001715 mPreviousPresentFence =
1716 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1717 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001718 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001719
Lloyd Pique41be5d22018-06-21 13:11:48 -07001720 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1721 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001722
David Sodman2b406362017-12-15 13:33:47 -08001723 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001724 // when we started doing work for this frame, but that should be okay
1725 // since updateCompositorTiming has snapping logic.
1726 updateCompositorTiming(
David Sodman2b406362017-12-15 13:33:47 -08001727 vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001728 CompositorTiming compositorTiming;
1729 {
David Sodman99974d22017-11-28 12:04:33 -08001730 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1731 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001732 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001733
Robert Carr2047fae2016-11-28 14:09:09 -08001734 mDrawingState.traverseInZOrder([&](Layer* layer) {
1735 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001736 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001737 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001738 recordBufferingStats(layer->getName().string(),
1739 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001740 }
Robert Carr2047fae2016-11-28 14:09:09 -08001741 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001742
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001743 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001744 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001745 enableHardwareVsync();
1746 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001747 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001748 }
1749 }
1750
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001751 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001752 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001753 enableHardwareVsync();
1754 }
1755 }
1756
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001757 if (mAnimCompositionPending) {
1758 mAnimCompositionPending = false;
1759
Brian Anderson4e606e32017-03-16 15:34:57 -07001760 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001761 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001762 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001763 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001764 // The HWC doesn't support present fences, so use the refresh
1765 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001766 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001767 mAnimFrameTracker.setActualPresentTime(presentTime);
1768 }
1769 mAnimFrameTracker.advanceFrame();
1770 }
Dan Stozab90cf072015-03-05 11:05:59 -08001771
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001772 mTimeStats.incrementTotalFrames();
1773 if (mHadClientComposition) {
1774 mTimeStats.incrementClientCompositionFrames();
1775 }
1776
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001777 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001778 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001779 return;
1780 }
1781
1782 nsecs_t currentTime = systemTime();
1783 if (mHasPoweredOff) {
1784 mHasPoweredOff = false;
1785 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001786 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001787 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001788 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1789 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001790 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001791 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001792 }
David Sodman4a36e932017-11-07 14:29:47 -08001793 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001794 }
David Sodman4a36e932017-11-07 14:29:47 -08001795 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001796
1797 {
1798 std::lock_guard lock(mTexturePoolMutex);
1799 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1800 if (refillCount > 0) {
1801 const size_t offset = mTexturePool.size();
1802 mTexturePool.resize(mTexturePoolSize);
1803 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1804 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1805 }
1806 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001807}
1808
1809void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001810 ATRACE_CALL();
1811 ALOGV("rebuildLayerStacks");
1812
Mathias Agopiancd60f992012-08-16 16:28:27 -07001813 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001814 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001815 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001816 mVisibleRegionsDirty = false;
1817 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001818
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001819 for (const auto& pair : mDisplays) {
1820 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001821 Region opaqueRegion;
1822 Region dirtyRegion;
1823 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001824 Vector<sp<Layer>> layersNeedingFences;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001825 const Transform& tr = display->getTransform();
1826 const Rect bounds = display->getBounds();
1827 if (display->isPoweredOn()) {
1828 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001829
Jeff Sharkey76488112017-02-27 14:15:18 -07001830 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001831 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001832 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001833 Region drawRegion(tr.transform(
1834 layer->visibleNonTransparentRegion));
1835 drawRegion.andSelf(bounds);
1836 if (!drawRegion.isEmpty()) {
1837 layersSortedByZ.add(layer);
1838 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001839 // Clear out the HWC layer if this layer was
1840 // previously visible, but no longer is
1841 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001842 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001843 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001844 // WM changes display->layerStack upon sleep/awake.
1845 // Here we make sure we delete the HWC layers even if
1846 // WM changed their layer stack.
1847 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001848 }
1849
1850 // If a layer is not going to get a release fence because
1851 // it is invisible, but it is also going to release its
1852 // old buffer, add it to the list of layers needing
1853 // fences.
1854 if (hwcLayerDestroyed) {
1855 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1856 mLayersWithQueuedFrames.cend(), layer);
1857 if (found != mLayersWithQueuedFrames.cend()) {
1858 layersNeedingFences.add(layer);
1859 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001860 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001861 });
1862 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001863 display->setVisibleLayersSortedByZ(layersSortedByZ);
1864 display->setLayersNeedingFences(layersNeedingFences);
1865 display->undefinedRegion.set(bounds);
1866 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1867 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001868 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001869 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001870}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001871
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001872// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001873// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001874// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001875// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001876// The returned HDR data space is one of
1877// - Dataspace::UNKNOWN
1878// - Dataspace::BT2020_HLG
1879// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001880Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1881 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001882 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001883 *outHdrDataSpace = Dataspace::UNKNOWN;
1884
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001885 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001886 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001887 case Dataspace::V0_SCRGB:
1888 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001889 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001890 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001891 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001892 case Dataspace::BT2020_PQ:
1893 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001894 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001895 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001896 case Dataspace::BT2020_HLG:
1897 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001898 // When there's mixed PQ content and HLG content, we set the HDR
1899 // data space to be BT2020_PQ and convert HLG to PQ.
1900 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1901 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001902 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001903 break;
1904 default:
1905 break;
1906 }
Romain Guy54f154a2017-10-24 21:40:32 +01001907 }
1908
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001909 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001910}
1911
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001912// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001913void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1914 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001915 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1916 *outMode = ColorMode::NATIVE;
1917 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001918 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001919 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001920 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001921
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001922 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001923 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001924
Peiyong Lindfde5112018-06-05 10:58:41 -07001925 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001926 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001927 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001928 if (isHdr) {
1929 bestDataSpace = hdrDataSpace;
1930 }
1931
Chia-I Wu0d711262018-05-21 15:19:35 -07001932 RenderIntent intent;
1933 switch (mDisplayColorSetting) {
1934 case DisplayColorSetting::MANAGED:
1935 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001936 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001937 break;
1938 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001939 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001940 break;
1941 default: // vendor display color setting
1942 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1943 break;
1944 }
Chia-I Wube02ec02018-05-18 10:59:36 -07001945
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001946 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001947}
1948
David Sodman2b406362017-12-15 13:33:47 -08001949void SurfaceFlinger::beginFrame()
1950{
1951 for (const auto& [token, display] : mDisplays) {
1952 bool dirty = !display->getDirtyRegion(mRepaintEverything).isEmpty();
1953 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
1954 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
1955
1956 // If nothing has changed (!dirty), don't recompose.
1957 // If something changed, but we don't currently have any visible layers,
1958 // and didn't when we last did a composition, then skip it this time.
1959 // The second rule does two things:
1960 // - When all layers are removed from a display, we'll emit one black
1961 // frame, then nothing more until we get new layers.
1962 // - When a display is created with a private layer stack, we won't
1963 // emit any black frames until a layer is added to the layer stack.
1964 bool mustRecompose = dirty && !(empty && wasEmpty);
1965
1966 ALOGV_IF(display->isVirtual(), "Display %d: %s composition (%sdirty %sempty %swasEmpty)",
1967 display->getId(), mustRecompose ? "doing" : "skipping", dirty ? "+" : "-",
1968 empty ? "+" : "-", wasEmpty ? "+" : "-");
1969
1970 display->beginFrame(mustRecompose);
1971
1972 if (mustRecompose) {
1973 display->lastCompositionHadVisibleLayers = !empty;
1974 }
1975 }
1976}
1977
1978void SurfaceFlinger::prepareFrame()
1979{
1980 for (const auto& [token, display] : mDisplays) {
1981 if (!display->isPoweredOn()) {
1982 continue;
1983 }
1984
1985 status_t result = display->prepareFrame(*getBE().mHwc);
1986 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
1987 display->getId(), result, strerror(-result));
1988 }
1989}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001990
Mathias Agopiancd60f992012-08-16 16:28:27 -07001991void SurfaceFlinger::doComposition() {
1992 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001993 ALOGV("doComposition");
1994
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001995 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001996 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001997 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001998 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001999 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002000
2001 // repaint the framebuffer (if needed)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002002 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002003
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002004 display->dirtyRegion.clear();
2005 display->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002006 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002007 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002008 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002009}
2010
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002011void SurfaceFlinger::postFramebuffer()
2012{
Mathias Agopian841cde52012-03-01 15:44:37 -08002013 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002014 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002015
Mathias Agopiana44b0412011-10-16 18:46:35 -07002016 const nsecs_t now = systemTime();
2017 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002018
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002019 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002020 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002021 continue;
2022 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07002023 const auto displayId = display->getId();
2024 if (displayId >= 0) {
2025 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002026 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002027 display->onSwapBuffersCompleted();
2028 display->makeCurrent();
2029 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002030 sp<Fence> releaseFence = Fence::NO_FENCE;
2031
Chia-I Wu7b549592017-11-15 09:14:57 -08002032 // The layer buffer from the previous frame (if any) is released
2033 // by HWC only when the release fence from this frame (if any) is
2034 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002035 auto hwcLayer = layer->getHwcLayer(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002036 if (displayId >= 0) {
2037 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
2038 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002039
2040 // If the layer was client composited in the previous frame, we
2041 // need to merge with the previous client target acquire fence.
2042 // Since we do not track that, always merge with the current
2043 // client target acquire fence when it is available, even though
2044 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002045 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002046 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002047 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002048 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002049
David Sodmanb8af7922017-12-21 15:17:55 -08002050 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002051 }
Chia-I Wu83806892017-11-16 10:50:20 -08002052
2053 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002054 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002055 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002056 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002057 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002058 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002059 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002060 }
2061 }
2062
Dominik Laskowski7e045462018-05-30 13:02:02 -07002063 if (displayId >= 0) {
2064 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002065 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002066 }
2067
Mathias Agopiana44b0412011-10-16 18:46:35 -07002068 mLastSwapBufferTime = systemTime() - now;
2069 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002070
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002071 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002072 const auto display = getDefaultDisplayDeviceLocked();
2073 if (display && getHwComposer().isConnected(display->getId())) {
2074 const uint32_t flipCount = display->getPageFlipCount();
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002075 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2076 logFrameStats();
2077 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002078 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002079}
2080
Mathias Agopian87baae12012-07-31 12:38:26 -07002081void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002082{
Mathias Agopian841cde52012-03-01 15:44:37 -08002083 ATRACE_CALL();
2084
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002085 // here we keep a copy of the drawing state (that is the state that's
2086 // going to be overwritten by handleTransactionLocked()) outside of
2087 // mStateLock so that the side-effects of the State assignment
2088 // don't happen with mStateLock held (which can cause deadlocks).
2089 State drawingState(mDrawingState);
2090
Mathias Agopianca4d3602011-05-19 15:38:14 -07002091 Mutex::Autolock _l(mStateLock);
2092 const nsecs_t now = systemTime();
2093 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002094
Mathias Agopianca4d3602011-05-19 15:38:14 -07002095 // Here we're guaranteed that some transaction flags are set
2096 // so we can call handleTransactionLocked() unconditionally.
2097 // We call getTransactionFlags(), which will also clear the flags,
2098 // with mStateLock held to guarantee that mCurrentState won't change
2099 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002100
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002101 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002102 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002103 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002104
Mathias Agopianca4d3602011-05-19 15:38:14 -07002105 mLastTransactionTime = systemTime() - now;
2106 mDebugInTransaction = 0;
2107 invalidateHwcGeometry();
2108 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002109}
2110
Dominik Laskowski7e045462018-05-30 13:02:02 -07002111DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002112 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002113 // Figure out whether the event is for the primary display or an
2114 // external display by matching the Hwc display id against one for a
2115 // connected display. If we did not find a match, we then check what
2116 // displays are not already connected to determine the type. If we don't
2117 // have a connected primary display, we assume the new display is meant to
2118 // be the primary display, and then if we don't have an external display,
2119 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002120 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2121 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002122 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002123 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002124 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002125 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002126 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002127 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002128 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002129 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002130 return DisplayDevice::DISPLAY_EXTERNAL;
2131 }
2132
2133 return DisplayDevice::DISPLAY_ID_INVALID;
2134}
2135
Lloyd Piqueba04e622017-12-14 17:11:26 -08002136void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2137 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002138 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002139 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002140 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002141 continue;
2142 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002143
2144 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2145 ALOGE("External displays are not supported by the vr hardware composer.");
2146 continue;
2147 }
2148
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002149 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002150 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002151 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002152 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002153 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002154
2155 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002156 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002157 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002158 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002159 DisplayDeviceState info;
2160 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002161 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2162 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002163 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002164 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002165 mInterceptor->saveDisplayCreation(info);
2166 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002167 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002168 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002169
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002170 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002171 if (idx >= 0) {
2172 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002173 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002174 mCurrentState.displays.removeItemsAt(idx);
2175 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002176 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002177 }
2178
2179 processDisplayChangesLocked();
2180 }
2181
2182 mPendingHotplugEvents.clear();
2183}
2184
Lloyd Pique99d3da52018-01-22 17:48:03 -08002185sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002186 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002187 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002188 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002189 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002190 HdrCapabilities hdrCapabilities;
2191 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002192
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002193 if (hasWideColorDisplay && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002194 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002195 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002196 if (isWideColorMode(colorMode)) {
2197 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002198 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002199
Dominik Laskowski7e045462018-05-30 13:02:02 -07002200 std::vector<RenderIntent> renderIntents =
2201 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002202 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002203 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002204
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002205 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2206 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2207 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002208
2209 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2210 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2211
2212 /*
2213 * Create our display's surface
2214 */
2215 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2216 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002217 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002218 renderSurface->setNativeWindow(nativeWindow.get());
2219 const int displayWidth = renderSurface->queryWidth();
2220 const int displayHeight = renderSurface->queryHeight();
2221
2222 // Make sure that composition can never be stalled by a virtual display
2223 // consumer that isn't processing buffers fast enough. We have to do this
2224 // in two places:
2225 // * Here, in case the display is composed entirely by HWC.
2226 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2227 // window's swap interval in eglMakeCurrent, so they'll override the
2228 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002229 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002230 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2231 }
2232
2233 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002234 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002235
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002236 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002237 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2238 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2239 displayHeight, hasWideColorGamut, hdrCapabilities,
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002240 supportedPerFrameMetadata, hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002241
2242 if (maxFrameBufferAcquiredBuffers >= 3) {
2243 nativeWindowSurface->preallocateBuffers();
2244 }
2245
2246 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002247 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2248 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002249 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002250 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002251 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002252 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002253 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002254 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002255 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002256 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002257 display->setLayerStack(state.layerStack);
2258 display->setProjection(state.orientation, state.viewport, state.frame);
2259 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002260
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002261 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002262}
2263
Lloyd Pique347200f2017-12-14 17:00:15 -08002264void SurfaceFlinger::processDisplayChangesLocked() {
2265 // here we take advantage of Vector's copy-on-write semantics to
2266 // improve performance by skipping the transaction entirely when
2267 // know that the lists are identical
2268 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2269 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2270 if (!curr.isIdenticalTo(draw)) {
2271 mVisibleRegionsDirty = true;
2272 const size_t cc = curr.size();
2273 size_t dc = draw.size();
2274
2275 // find the displays that were removed
2276 // (ie: in drawing state but not in current state)
2277 // also handle displays that changed
2278 // (ie: displays that are in both lists)
2279 for (size_t i = 0; i < dc;) {
2280 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2281 if (j < 0) {
2282 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002283 // Call makeCurrent() on the primary display so we can
2284 // be sure that nothing associated with this display
2285 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002286 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2287 defaultDisplay->makeCurrent();
2288 }
2289 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2290 display->disconnect(getHwComposer());
2291 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002292 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2293 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2294 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2295 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2296 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002297 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002298 } else {
2299 // this display is in both lists. see if something changed.
2300 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002301 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002302 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2303 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2304 if (state_binder != draw_binder) {
2305 // changing the surface is like destroying and
2306 // recreating the DisplayDevice, so we just remove it
2307 // from the drawing state, so that it get re-added
2308 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002309 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2310 display->disconnect(getHwComposer());
2311 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002312 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002313 mDrawingState.displays.removeItemsAt(i);
2314 dc--;
2315 // at this point we must loop to the next item
2316 continue;
2317 }
2318
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002319 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002320 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002321 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002322 }
2323 if ((state.orientation != draw[i].orientation) ||
2324 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002325 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002326 }
2327 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002328 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002329 }
2330 }
2331 }
2332 ++i;
2333 }
2334
2335 // find displays that were added
2336 // (ie: in current state but not in drawing state)
2337 for (size_t i = 0; i < cc; i++) {
2338 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2339 const DisplayDeviceState& state(curr[i]);
2340
2341 sp<DisplaySurface> dispSurface;
2342 sp<IGraphicBufferProducer> producer;
2343 sp<IGraphicBufferProducer> bqProducer;
2344 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002345 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002346
Dominik Laskowski7e045462018-05-30 13:02:02 -07002347 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002348 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002349 // Virtual displays without a surface are dormant:
2350 // they have external state (layer stack, projection,
2351 // etc.) but no internal state (i.e. a DisplayDevice).
2352 if (state.surface != nullptr) {
2353 // Allow VR composer to use virtual displays.
2354 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2355 int width = 0;
2356 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2357 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2358 int height = 0;
2359 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2360 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2361 int intFormat = 0;
2362 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2363 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002364 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002365
Dominik Laskowski7e045462018-05-30 13:02:02 -07002366 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2367 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002368 }
2369
2370 // TODO: Plumb requested format back up to consumer
2371
2372 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002373 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002374 bqProducer, bqConsumer,
2375 state.displayName);
2376
2377 dispSurface = vds;
2378 producer = vds;
2379 }
2380 } else {
2381 ALOGE_IF(state.surface != nullptr,
2382 "adding a supported display, but rendering "
2383 "surface is provided (%p), ignoring it",
2384 state.surface.get());
2385
Dominik Laskowski7e045462018-05-30 13:02:02 -07002386 displayId = state.type;
2387 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002388 producer = bqProducer;
2389 }
2390
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002391 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002392 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002393 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002394 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002395 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002396 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002397 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2398 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2399 true);
2400 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2401 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2402 true);
2403 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002404 }
2405 }
2406 }
2407 }
2408 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002409
2410 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002411}
2412
Mathias Agopian87baae12012-07-31 12:38:26 -07002413void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002414{
Dan Stoza7dde5992015-05-22 09:51:44 -07002415 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002416 mCurrentState.traverseInZOrder([](Layer* layer) {
2417 layer->notifyAvailableFrames();
2418 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002419
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002420 /*
2421 * Traversal of the children
2422 * (perform the transaction for each of them if needed)
2423 */
2424
Mathias Agopian3559b072012-08-15 13:46:03 -07002425 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002426 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002427 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002428 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002429
2430 const uint32_t flags = layer->doTransaction(0);
2431 if (flags & Layer::eVisibleRegion)
2432 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002433 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002434 }
2435
2436 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002437 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002438 */
2439
Mathias Agopiane57f2922012-08-09 16:29:12 -07002440 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002441 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002442 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002443 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002444
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002445 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002446 // The transform hint might have changed for some layers
2447 // (either because a display has changed, or because a layer
2448 // as changed).
2449 //
2450 // Walk through all the layers in currentLayers,
2451 // and update their transform hint.
2452 //
2453 // If a layer is visible only on a single display, then that
2454 // display is used to calculate the hint, otherwise we use the
2455 // default display.
2456 //
2457 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2458 // the hint is set before we acquire a buffer from the surface texture.
2459 //
2460 // NOTE: layer transactions have taken place already, so we use their
2461 // drawing state. However, SurfaceFlinger's own transaction has not
2462 // happened yet, so we must use the current state layer list
2463 // (soon to become the drawing state list).
2464 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002465 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002466 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002467 bool first = true;
2468 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002469 // NOTE: we rely on the fact that layers are sorted by
2470 // layerStack first (so we don't have to traverse the list
2471 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002472 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002473 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002474 currentlayerStack = layerStack;
2475 // figure out if this layerstack is mirrored
2476 // (more than one display) if so, pick the default display,
2477 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002478 hintDisplay = nullptr;
2479 for (const auto& [token, display] : mDisplays) {
2480 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2481 if (hintDisplay) {
2482 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002483 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002484 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002485 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002486 }
2487 }
2488 }
2489 }
Chet Haase91d25932013-04-11 15:24:55 -07002490
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002491 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002492 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2493 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002494
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002495 // could be null when this layer is using a layerStack
2496 // that is not visible on any display. Also can occur at
2497 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002498 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002499 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002500
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002501 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002502 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002503 if (hintDisplay) {
2504 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002505 }
Robert Carr2047fae2016-11-28 14:09:09 -08002506
2507 first = false;
2508 });
Mathias Agopian84300952012-11-21 16:02:13 -08002509 }
2510
2511
Mathias Agopian3559b072012-08-15 13:46:03 -07002512 /*
2513 * Perform our own transaction if needed
2514 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002515
2516 if (mLayersAdded) {
2517 mLayersAdded = false;
2518 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002519 mVisibleRegionsDirty = true;
2520 }
2521
2522 // some layers might have been removed, so
2523 // we need to update the regions they're exposing.
2524 if (mLayersRemoved) {
2525 mLayersRemoved = false;
2526 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002527 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002528 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002529 // this layer is not visible anymore
2530 // TODO: we could traverse the tree from front to back and
2531 // compute the actual visible region
2532 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002533 Region visibleReg;
2534 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002535 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002536 }
Robert Carr2047fae2016-11-28 14:09:09 -08002537 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002538 }
2539
2540 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002541
2542 updateCursorAsync();
2543}
2544
2545void SurfaceFlinger::updateCursorAsync()
2546{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002547 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002548 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002549 continue;
2550 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002551
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002552 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2553 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002554 }
2555 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002556}
2557
2558void SurfaceFlinger::commitTransaction()
2559{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002560 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002561 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002562 for (const auto& l : mLayersPendingRemoval) {
2563 recordBufferingStats(l->getName().string(),
2564 l->getOccupancyHistory(true));
2565 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002566 }
2567 mLayersPendingRemoval.clear();
2568 }
2569
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002570 // If this transaction is part of a window animation then the next frame
2571 // we composite should be considered an animation as well.
2572 mAnimCompositionPending = mAnimTransactionPending;
2573
Mathias Agopian4fec8732012-06-29 14:12:52 -07002574 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002575 // clear the "changed" flags in current state
2576 mCurrentState.colorMatrixChanged = false;
2577
Robert Carr1f0a16a2016-10-24 16:27:39 -07002578 mDrawingState.traverseInZOrder([](Layer* layer) {
2579 layer->commitChildList();
2580 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002581 mTransactionPending = false;
2582 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002583 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002584}
2585
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002586void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2587 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002588 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002589 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002590
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002591 Region aboveOpaqueLayers;
2592 Region aboveCoveredLayers;
2593 Region dirty;
2594
Mathias Agopian87baae12012-07-31 12:38:26 -07002595 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002596
Robert Carr2047fae2016-11-28 14:09:09 -08002597 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002598 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002599 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002600
Jesse Hall01e29052013-02-19 16:13:35 -08002601 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002602 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002603 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002604 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002605
Mathias Agopianab028732010-03-16 16:41:46 -07002606 /*
2607 * opaqueRegion: area of a surface that is fully opaque.
2608 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002609 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002610
2611 /*
2612 * visibleRegion: area of a surface that is visible on screen
2613 * and not fully transparent. This is essentially the layer's
2614 * footprint minus the opaque regions above it.
2615 * Areas covered by a translucent surface are considered visible.
2616 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002617 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002618
2619 /*
2620 * coveredRegion: area of a surface that is covered by all
2621 * visible regions above it (which includes the translucent areas).
2622 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002623 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002624
Jesse Halla8026d22012-09-25 13:25:04 -07002625 /*
2626 * transparentRegion: area of a surface that is hinted to be completely
2627 * transparent. This is only used to tell when the layer has no visible
2628 * non-transparent regions and can be removed from the layer list. It
2629 * does not affect the visibleRegion of this layer or any layers
2630 * beneath it. The hint may not be correct if apps don't respect the
2631 * SurfaceView restrictions (which, sadly, some don't).
2632 */
2633 Region transparentRegion;
2634
Mathias Agopianab028732010-03-16 16:41:46 -07002635
2636 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002637 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002638 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002639 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002640 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002641 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002642 if (!visibleRegion.isEmpty()) {
2643 // Remove the transparent area from the visible region
2644 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002645 if (tr.preserveRects()) {
2646 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002647 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002648 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002649 // transformation too complex, can't do the
2650 // transparent region optimization.
2651 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002652 }
Mathias Agopianab028732010-03-16 16:41:46 -07002653 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002654
Mathias Agopianab028732010-03-16 16:41:46 -07002655 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002656 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002657 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002658 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2659 // the opaque region is the layer's footprint
2660 opaqueRegion = visibleRegion;
2661 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002662 }
2663 }
2664
Robert Carre5f4f692018-01-12 13:12:28 -08002665 if (visibleRegion.isEmpty()) {
2666 layer->clearVisibilityRegions();
2667 return;
2668 }
2669
Mathias Agopianab028732010-03-16 16:41:46 -07002670 // Clip the covered region to the visible region
2671 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2672
2673 // Update aboveCoveredLayers for next (lower) layer
2674 aboveCoveredLayers.orSelf(visibleRegion);
2675
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002676 // subtract the opaque region covered by the layers above us
2677 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002678
2679 // compute this layer's dirty region
2680 if (layer->contentDirty) {
2681 // we need to invalidate the whole region
2682 dirty = visibleRegion;
2683 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002684 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002685 layer->contentDirty = false;
2686 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002687 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002688 * the exposed region consists of two components:
2689 * 1) what's VISIBLE now and was COVERED before
2690 * 2) what's EXPOSED now less what was EXPOSED before
2691 *
2692 * note that (1) is conservative, we start with the whole
2693 * visible region but only keep what used to be covered by
2694 * something -- which mean it may have been exposed.
2695 *
2696 * (2) handles areas that were not covered by anything but got
2697 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002698 */
Mathias Agopianab028732010-03-16 16:41:46 -07002699 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002700 const Region oldVisibleRegion = layer->visibleRegion;
2701 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002702 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2703 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002704 }
2705 dirty.subtractSelf(aboveOpaqueLayers);
2706
2707 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002708 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002709
Mathias Agopianab028732010-03-16 16:41:46 -07002710 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002711 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002712
Jesse Halla8026d22012-09-25 13:25:04 -07002713 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002714 layer->setVisibleRegion(visibleRegion);
2715 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002716 layer->setVisibleNonTransparentRegion(
2717 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002718 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002719
Mathias Agopian87baae12012-07-31 12:38:26 -07002720 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002721}
2722
Chia-I Wuab0c3192017-08-01 11:29:00 -07002723void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002724 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002725 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2726 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002727 }
2728 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002729}
2730
Dan Stoza6b9454d2014-11-07 16:00:59 -08002731bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002732{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002733 ALOGV("handlePageFlip");
2734
Brian Andersond6927fb2016-07-23 23:37:30 -07002735 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002736
Mathias Agopian4fec8732012-06-29 14:12:52 -07002737 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002738 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002739 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002740
2741 // Store the set of layers that need updates. This set must not change as
2742 // buffers are being latched, as this could result in a deadlock.
2743 // Example: Two producers share the same command stream and:
2744 // 1.) Layer 0 is latched
2745 // 2.) Layer 0 gets a new frame
2746 // 2.) Layer 1 gets a new frame
2747 // 3.) Layer 1 is latched.
2748 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2749 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002750 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002751 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002752 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07002753 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002754 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002755 } else {
2756 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002757 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002758 } else {
2759 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002760 }
Robert Carr2047fae2016-11-28 14:09:09 -08002761 });
2762
Dan Stoza9e56aa02015-11-02 13:00:03 -08002763 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002764 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002765 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002766 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002767 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002768 newDataLatched = true;
2769 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002770 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002771
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002772 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002773
2774 // If we will need to wake up at some time in the future to deal with a
2775 // queued frame that shouldn't be displayed during this vsync period, wake
2776 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002777 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002778 signalLayerUpdate();
2779 }
2780
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002781 // enter boot animation on first buffer latch
2782 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2783 ALOGI("Enter boot animation");
2784 mBootStage = BootStage::BOOTANIMATION;
2785 }
2786
Dan Stoza6b9454d2014-11-07 16:00:59 -08002787 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002788 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002789}
2790
Mathias Agopianad456f92011-01-13 17:53:01 -08002791void SurfaceFlinger::invalidateHwcGeometry()
2792{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002793 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002794}
2795
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002796void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2797 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002798 // We only need to actually compose the display if:
2799 // 1) It is being handled by hardware composer, which may need this to
2800 // keep its virtual display state machine in sync, or
2801 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002802 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002803 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002804 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002805 return;
2806 }
2807
Dan Stoza9e56aa02015-11-02 13:00:03 -08002808 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002809 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002810
2811 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002812 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002813}
2814
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002815bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002816 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002817
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002818 const Region bounds(display->bounds());
2819 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002820 const auto displayId = display->getId();
2821 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002822 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002823
Chia-I Wu8e50e692018-05-04 10:12:37 -07002824 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002825 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002826
Dan Stoza9e56aa02015-11-02 13:00:03 -08002827 if (hasClientComposition) {
2828 ALOGV("hasClientComposition");
2829
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002830 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002831 if (display->hasWideColorGamut()) {
2832 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002833 }
2834 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002835 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002836 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002837
Dominik Laskowski7e045462018-05-30 13:02:02 -07002838 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002839 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2840 HWC2::Capability::SkipClientColorTransform);
2841
Chia-I Wud49d6692018-06-27 07:17:41 +08002842 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002843 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2844 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08002845 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002846 }
2847
Chia-I Wud49d6692018-06-27 07:17:41 +08002848 // The current enhanced saturation matrix is designed to enhance Display P3,
2849 // thus we only apply this matrix when the render intent is not colorimetric
2850 // and the output color space is Display P3.
2851 needsEnhancedColorMatrix =
2852 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2853 outputDataspace == Dataspace::DISPLAY_P3);
2854 if (needsEnhancedColorMatrix) {
2855 colorMatrix *= mEnhancedSaturationMatrix;
2856 }
2857
2858 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002859
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002860 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002861 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002862 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002863 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002864
2865 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002866 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
2867 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
2868 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07002869 }
2870 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002871 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002872
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002873 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002874 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002875 // when using overlays, we assume a fully transparent framebuffer
2876 // NOTE: we could reduce how much we need to clear, for instance
2877 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002878 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002879 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002880 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002881 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002882 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002883 // we're left with the letterbox region
2884 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002885 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07002886
2887 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002888 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07002889
Mathias Agopianb9494d52012-04-18 02:28:45 -07002890 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002891 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002892 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002893 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002894 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002895 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002896
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002897 if (!display->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002898 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002899 // scissor on the main display. It should never be needed
2900 // anyways (though in theory it could since the API allows it).
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002901 const Rect& bounds = display->getBounds();
2902 const Rect& scissor = display->getScissor();
Mathias Agopianf45c5102012-10-24 16:29:17 -07002903 if (scissor != bounds) {
2904 // scissor doesn't match the screen's dimensions, so we
2905 // need to clear everything outside of it and enable
2906 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002907
Mathias Agopianf45c5102012-10-24 16:29:17 -07002908 // enable scissor for this frame
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002909 const uint32_t height = display->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002910 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002911 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002912 }
2913 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002914 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002915
Mathias Agopian85d751c2012-08-29 16:59:24 -07002916 /*
2917 * and then, render the layers targeted at the framebuffer
2918 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002919
Dan Stoza9e56aa02015-11-02 13:00:03 -08002920 ALOGV("Rendering client layers");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002921 const Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002922 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002923 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002924 const Region clip(bounds.intersect(
2925 displayTransform.transform(layer->visibleRegion)));
2926 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002927 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002928 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002929 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002930 case HWC2::Composition::Cursor:
2931 case HWC2::Composition::Device:
2932 case HWC2::Composition::Sideband:
2933 case HWC2::Composition::SolidColor: {
2934 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002935 if (layer->getClearClientTarget(displayId) && !firstLayer &&
Rajavenu Kyatham2eae6d32018-04-10 12:34:05 +05302936 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
2937 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002938 // never clear the very first layer since we're
2939 // guaranteed the FB is already cleared
2940 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002941 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002942 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002943 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002944 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002945 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002946 break;
2947 }
2948 default:
2949 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002950 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002951 } else {
2952 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002953 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002954 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002955 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002956
Chia-I Wud49d6692018-06-27 07:17:41 +08002957 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07002958 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002959 }
2960
Mathias Agopianf45c5102012-10-24 16:29:17 -07002961 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002962 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002963 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002964}
2965
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002966void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
2967 const Region& region) const {
2968 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002969 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002970 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002971}
2972
Dan Stoza7d89d062015-04-30 13:29:25 -07002973status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002974 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002975 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002976 const sp<Layer>& lbc,
2977 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002978{
Dan Stoza7d89d062015-04-30 13:29:25 -07002979 // add this layer to the current state list
2980 {
2981 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002982 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002983 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2984 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002985 return NO_MEMORY;
2986 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002987 if (parent == nullptr) {
2988 mCurrentState.layersSortedByZ.add(lbc);
2989 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002990 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002991 ALOGE("addClientLayer called with a removed parent");
2992 return NAME_NOT_FOUND;
2993 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002994 parent->addChild(lbc);
2995 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002996
Yiwei Zhang243b3782018-05-15 17:40:04 -07002997 if (gbc != nullptr) {
2998 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
2999 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3000 mMaxGraphicBufferProducerListSize,
3001 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3002 mGraphicBufferProducerList.size(),
3003 mMaxGraphicBufferProducerListSize, mNumLayers);
3004 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003005 mLayersAdded = true;
3006 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003007 }
3008
Mathias Agopian96f08192010-06-02 23:28:45 -07003009 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003010 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003011
Dan Stoza7d89d062015-04-30 13:29:25 -07003012 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003013}
3014
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003015status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003016 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003017 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3018}
Robert Carr7f9b8992017-03-10 11:08:39 -08003019
chaviwca27f252018-02-06 16:46:39 -08003020status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3021 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003022 if (layer->isPendingRemoval()) {
3023 return NO_ERROR;
3024 }
3025
Robert Carr1f0a16a2016-10-24 16:27:39 -07003026 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003027 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003028 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003029 if (topLevelOnly) {
3030 return NO_ERROR;
3031 }
3032
Chia-I Wu98f1c102017-05-30 14:54:08 -07003033 sp<Layer> ancestor = p;
3034 while (ancestor->getParent() != nullptr) {
3035 ancestor = ancestor->getParent();
3036 }
3037 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3038 ALOGE("removeLayer called with a layer whose parent has been removed");
3039 return NAME_NOT_FOUND;
3040 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003041
3042 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003043 } else {
3044 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003045 }
3046
Robert Carr136e2f62017-02-08 17:54:29 -08003047 // As a matter of normal operation, the LayerCleaner will produce a second
3048 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3049 // so we will succeed in promoting it, but it's already been removed
3050 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3051 // otherwise something has gone wrong and we are leaking the layer.
3052 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003053 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3054 layer->getName().string(),
3055 (p != nullptr) ? p->getName().string() : "no-parent");
3056 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003057 } else if (index < 0) {
3058 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003059 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003060
Chia-I Wuc6657022017-08-15 11:18:17 -07003061 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003062 mLayersPendingRemoval.add(layer);
3063 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003064 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003065 setTransactionFlags(eTransactionNeeded);
3066 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003067}
3068
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003069uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003070 return android_atomic_release_load(&mTransactionFlags);
3071}
3072
Mathias Agopian3f844832013-08-07 21:24:32 -07003073uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003074 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3075}
3076
Mathias Agopian3f844832013-08-07 21:24:32 -07003077uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003078 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3079}
3080
3081uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3082 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003083 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003084 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003085 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003086 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003087 }
3088 return old;
3089}
3090
chaviwca27f252018-02-06 16:46:39 -08003091bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3092 for (const ComposerState& state : states) {
3093 // Here we need to check that the interface we're given is indeed
3094 // one of our own. A malicious client could give us a nullptr
3095 // IInterface, or one of its own or even one of our own but a
3096 // different type. All these situations would cause us to crash.
3097 if (state.client == nullptr) {
3098 return true;
3099 }
3100
3101 sp<IBinder> binder = IInterface::asBinder(state.client);
3102 if (binder == nullptr) {
3103 return true;
3104 }
3105
3106 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3107 return true;
3108 }
3109 }
3110 return false;
3111}
3112
Mathias Agopian8b33f032012-07-24 20:43:54 -07003113void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003114 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003115 const Vector<DisplayState>& displays,
3116 uint32_t flags)
3117{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003118 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003119 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003120 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003121
chaviwca27f252018-02-06 16:46:39 -08003122 if (containsAnyInvalidClientState(states)) {
3123 return;
3124 }
3125
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003126 if (flags & eAnimation) {
3127 // For window updates that are part of an animation we must wait for
3128 // previous animation "frames" to be handled.
3129 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003130 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003131 if (CC_UNLIKELY(err != NO_ERROR)) {
3132 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003133 // caller after a few seconds.
3134 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3135 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003136 mAnimTransactionPending = false;
3137 break;
3138 }
3139 }
3140 }
3141
chaviwca27f252018-02-06 16:46:39 -08003142 for (const DisplayState& display : displays) {
3143 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003144 }
3145
chaviwca27f252018-02-06 16:46:39 -08003146 for (const ComposerState& state : states) {
3147 transactionFlags |= setClientStateLocked(state);
3148 }
3149
3150 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3151 // as destroyed should only occur after setting all other states. This is to allow for a
3152 // child re-parent to happen before marking its original parent as destroyed (which would
3153 // then mark the child as destroyed).
3154 for (const ComposerState& state : states) {
3155 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003156 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003157
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003158 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3159 // anyway. This can be used as a flush mechanism for previous async transactions.
3160 // Empty animation transaction can be used to simulate back-pressure, so also force a
3161 // transaction for empty animation transactions.
3162 if (transactionFlags == 0 &&
3163 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003164 transactionFlags = eTransactionNeeded;
3165 }
3166
Mathias Agopian386aa982011-11-07 21:58:03 -08003167 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003168 if (mInterceptor->isEnabled()) {
3169 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003170 }
Irvel468051e2016-06-13 16:44:44 -07003171
Mathias Agopian386aa982011-11-07 21:58:03 -08003172 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003173 const auto start = (flags & eEarlyWakeup)
3174 ? VSyncModulator::TransactionStart::EARLY
3175 : VSyncModulator::TransactionStart::NORMAL;
3176 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003177
3178 // if this is a synchronous transaction, wait for it to take effect
3179 // before returning.
3180 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003181 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003182 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003183 if (flags & eAnimation) {
3184 mAnimTransactionPending = true;
3185 }
3186 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003187 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3188 if (CC_UNLIKELY(err != NO_ERROR)) {
3189 // just in case something goes wrong in SF, return to the
3190 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003191 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3192 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003193 break;
3194 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003195 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003196 }
3197}
3198
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003199uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3200 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3201 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003202
Mathias Agopiane57f2922012-08-09 16:29:12 -07003203 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003204 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3205
3206 const uint32_t what = s.what;
3207 if (what & DisplayState::eSurfaceChanged) {
3208 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3209 state.surface = s.surface;
3210 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003211 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003212 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003213 if (what & DisplayState::eLayerStackChanged) {
3214 if (state.layerStack != s.layerStack) {
3215 state.layerStack = s.layerStack;
3216 flags |= eDisplayTransactionNeeded;
3217 }
3218 }
3219 if (what & DisplayState::eDisplayProjectionChanged) {
3220 if (state.orientation != s.orientation) {
3221 state.orientation = s.orientation;
3222 flags |= eDisplayTransactionNeeded;
3223 }
3224 if (state.frame != s.frame) {
3225 state.frame = s.frame;
3226 flags |= eDisplayTransactionNeeded;
3227 }
3228 if (state.viewport != s.viewport) {
3229 state.viewport = s.viewport;
3230 flags |= eDisplayTransactionNeeded;
3231 }
3232 }
3233 if (what & DisplayState::eDisplaySizeChanged) {
3234 if (state.width != s.width) {
3235 state.width = s.width;
3236 flags |= eDisplayTransactionNeeded;
3237 }
3238 if (state.height != s.height) {
3239 state.height = s.height;
3240 flags |= eDisplayTransactionNeeded;
3241 }
3242 }
3243
Mathias Agopiane57f2922012-08-09 16:29:12 -07003244 return flags;
3245}
3246
Robert Carrd4ae7f32018-06-07 16:10:57 -07003247bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3248 IPCThreadState* ipc = IPCThreadState::self();
3249 const int pid = ipc->getCallingPid();
3250 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003251 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulecfbe2c002018-08-09 22:32:45 +00003252 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003253 return false;
3254 }
3255 return true;
3256}
3257
chaviwca27f252018-02-06 16:46:39 -08003258uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3259 const layer_state_t& s = composerState.state;
3260 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3261
Mathias Agopian13127d82013-03-05 17:47:11 -08003262 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003263 if (layer == nullptr) {
3264 return 0;
3265 }
3266
3267 if (layer->isPendingRemoval()) {
3268 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3269 return 0;
3270 }
3271
3272 uint32_t flags = 0;
3273
3274 const uint32_t what = s.what;
3275 bool geometryAppliesWithResize =
3276 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003277
3278 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3279 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003280 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003281 layer->pushPendingState();
3282 }
3283
chaviw8b3871a2017-11-01 17:41:01 -07003284 if (what & layer_state_t::ePositionChanged) {
3285 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3286 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003287 }
chaviw8b3871a2017-11-01 17:41:01 -07003288 }
3289 if (what & layer_state_t::eLayerChanged) {
3290 // NOTE: index needs to be calculated before we update the state
3291 const auto& p = layer->getParent();
3292 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003293 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003294 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003295 mCurrentState.layersSortedByZ.removeAt(idx);
3296 mCurrentState.layersSortedByZ.add(layer);
3297 // we need traversal (state changed)
3298 // AND transaction (list changed)
3299 flags |= eTransactionNeeded|eTraversalNeeded;
3300 }
chaviw8b3871a2017-11-01 17:41:01 -07003301 } else {
3302 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003303 flags |= eTransactionNeeded|eTraversalNeeded;
3304 }
3305 }
chaviw8b3871a2017-11-01 17:41:01 -07003306 }
3307 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003308 // NOTE: index needs to be calculated before we update the state
3309 const auto& p = layer->getParent();
3310 if (p == nullptr) {
3311 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3312 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3313 mCurrentState.layersSortedByZ.removeAt(idx);
3314 mCurrentState.layersSortedByZ.add(layer);
3315 // we need traversal (state changed)
3316 // AND transaction (list changed)
3317 flags |= eTransactionNeeded|eTraversalNeeded;
3318 }
3319 } else {
3320 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3321 flags |= eTransactionNeeded|eTraversalNeeded;
3322 }
chaviw8b3871a2017-11-01 17:41:01 -07003323 }
3324 }
3325 if (what & layer_state_t::eSizeChanged) {
3326 if (layer->setSize(s.w, s.h)) {
3327 flags |= eTraversalNeeded;
3328 }
3329 }
3330 if (what & layer_state_t::eAlphaChanged) {
3331 if (layer->setAlpha(s.alpha))
3332 flags |= eTraversalNeeded;
3333 }
3334 if (what & layer_state_t::eColorChanged) {
3335 if (layer->setColor(s.color))
3336 flags |= eTraversalNeeded;
3337 }
3338 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003339 // TODO: b/109894387
3340 //
3341 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3342 // rotation. To see the problem observe that if we have a square parent, and a child
3343 // of the same size, then we rotate the child 45 degrees around it's center, the child
3344 // must now be cropped to a non rectangular 8 sided region.
3345 //
3346 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3347 // private API, and the WindowManager only uses rotation in one case, which is on a top
3348 // level layer in which cropping is not an issue.
3349 //
3350 // However given that abuse of rotation matrices could lead to surfaces extending outside
3351 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3352 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3353 // transformations.
3354 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003355 flags |= eTraversalNeeded;
3356 }
3357 if (what & layer_state_t::eTransparentRegionChanged) {
3358 if (layer->setTransparentRegionHint(s.transparentRegion))
3359 flags |= eTraversalNeeded;
3360 }
3361 if (what & layer_state_t::eFlagsChanged) {
3362 if (layer->setFlags(s.flags, s.mask))
3363 flags |= eTraversalNeeded;
3364 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003365 if (what & layer_state_t::eCropChanged_legacy) {
3366 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003367 flags |= eTraversalNeeded;
3368 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003369 if (what & layer_state_t::eFinalCropChanged_legacy) {
3370 if (layer->setFinalCrop_legacy(s.finalCrop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003371 flags |= eTraversalNeeded;
3372 }
3373 if (what & layer_state_t::eLayerStackChanged) {
3374 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3375 // We only allow setting layer stacks for top level layers,
3376 // everything else inherits layer stack from its parent.
3377 if (layer->hasParent()) {
3378 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3379 layer->getName().string());
3380 } else if (idx < 0) {
3381 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3382 "that also does not appear in the top level layer list. Something"
3383 " has gone wrong.", layer->getName().string());
3384 } else if (layer->setLayerStack(s.layerStack)) {
3385 mCurrentState.layersSortedByZ.removeAt(idx);
3386 mCurrentState.layersSortedByZ.add(layer);
3387 // we need traversal (state changed)
3388 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003389 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003390 }
3391 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003392 if (what & layer_state_t::eDeferTransaction_legacy) {
3393 if (s.barrierHandle_legacy != nullptr) {
3394 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3395 } else if (s.barrierGbp_legacy != nullptr) {
3396 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003397 if (authenticateSurfaceTextureLocked(gbp)) {
3398 const auto& otherLayer =
3399 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003400 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003401 } else {
3402 ALOGE("Attempt to defer transaction to to an"
3403 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003404 }
3405 }
chaviw8b3871a2017-11-01 17:41:01 -07003406 // We don't trigger a traversal here because if no other state is
3407 // changed, we don't want this to cause any more work
3408 }
3409 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003410 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003411 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003412 if (!hadParent) {
3413 mCurrentState.layersSortedByZ.remove(layer);
3414 }
chaviw8b3871a2017-11-01 17:41:01 -07003415 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003416 }
chaviw8b3871a2017-11-01 17:41:01 -07003417 }
3418 if (what & layer_state_t::eReparentChildren) {
3419 if (layer->reparentChildren(s.reparentHandle)) {
3420 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003421 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003422 }
chaviw8b3871a2017-11-01 17:41:01 -07003423 if (what & layer_state_t::eDetachChildren) {
3424 layer->detachChildren();
3425 }
3426 if (what & layer_state_t::eOverrideScalingModeChanged) {
3427 layer->setOverrideScalingMode(s.overrideScalingMode);
3428 // We don't trigger a traversal here because if no other state is
3429 // changed, we don't want this to cause any more work
3430 }
Marissa Wall61c58622018-07-18 10:12:20 -07003431 if (what & layer_state_t::eTransformChanged) {
3432 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3433 }
3434 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3435 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3436 flags |= eTraversalNeeded;
3437 }
3438 if (what & layer_state_t::eCropChanged) {
3439 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3440 }
3441 if (what & layer_state_t::eBufferChanged) {
3442 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3443 }
3444 if (what & layer_state_t::eAcquireFenceChanged) {
3445 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3446 }
3447 if (what & layer_state_t::eDataspaceChanged) {
3448 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3449 }
3450 if (what & layer_state_t::eHdrMetadataChanged) {
3451 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3452 }
3453 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3454 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3455 }
3456 if (what & layer_state_t::eApiChanged) {
3457 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3458 }
3459 if (what & layer_state_t::eSidebandStreamChanged) {
3460 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3461 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003462 return flags;
3463}
3464
chaviwca27f252018-02-06 16:46:39 -08003465void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3466 const layer_state_t& state = composerState.state;
3467 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3468
3469 sp<Layer> layer(client->getLayerUser(state.surface));
3470 if (layer == nullptr) {
3471 return;
3472 }
3473
3474 if (layer->isPendingRemoval()) {
3475 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3476 return;
3477 }
3478
3479 if (state.what & layer_state_t::eDestroySurface) {
3480 removeLayerLocked(mStateLock, layer);
3481 }
3482}
3483
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003484status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003485 const String8& name,
3486 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003487 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003488 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003489 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003490{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003491 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003492 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003493 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003494 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003495 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003496
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003497 status_t result = NO_ERROR;
3498
3499 sp<Layer> layer;
3500
Cody Northropbc755282017-03-31 12:00:08 -06003501 String8 uniqueName = getUniqueLayerName(name);
3502
Mathias Agopian3165cc22012-08-08 19:42:09 -07003503 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003504 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003505 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3506 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003507
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003508 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003509 case ISurfaceComposerClient::eFXSurfaceBufferState:
3510 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3511 break;
chaviw13fdc492017-06-27 12:40:18 -07003512 case ISurfaceComposerClient::eFXSurfaceColor:
3513 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003514 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003515 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003516 break;
3517 default:
3518 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003519 break;
3520 }
3521
Dan Stoza7d89d062015-04-30 13:29:25 -07003522 if (result != NO_ERROR) {
3523 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003524 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003525
Chia-I Wuab0c3192017-08-01 11:29:00 -07003526 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3527 // TODO b/64227542
3528 if (windowType == 441731) {
3529 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3530 layer->setPrimaryDisplayOnly();
3531 }
3532
Albert Chaulk479c60c2017-01-27 14:21:34 -05003533 layer->setInfo(windowType, ownerUid);
3534
Robert Carr1f0a16a2016-10-24 16:27:39 -07003535 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003536 if (result != NO_ERROR) {
3537 return result;
3538 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003539 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003540
3541 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003542 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003543}
3544
Cody Northropbc755282017-03-31 12:00:08 -06003545String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3546{
3547 bool matchFound = true;
3548 uint32_t dupeCounter = 0;
3549
3550 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3551 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3552
Dan Stoza436ccf32018-06-21 12:10:12 -07003553 // Grab the state lock since we're accessing mCurrentState
3554 Mutex::Autolock lock(mStateLock);
3555
Cody Northropbc755282017-03-31 12:00:08 -06003556 // Loop over layers until we're sure there is no matching name
3557 while (matchFound) {
3558 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003559 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003560 if (layer->getName() == uniqueName) {
3561 matchFound = true;
3562 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3563 }
3564 });
3565 }
3566
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003567 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3568 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003569
3570 return uniqueName;
3571}
3572
Marissa Wallfd668622018-05-10 10:21:13 -07003573status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3574 uint32_t w, uint32_t h, uint32_t flags,
3575 PixelFormat& format, sp<IBinder>* handle,
3576 sp<IGraphicBufferProducer>* gbp,
3577 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003578 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003579 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003580 case PIXEL_FORMAT_TRANSPARENT:
3581 case PIXEL_FORMAT_TRANSLUCENT:
3582 format = PIXEL_FORMAT_RGBA_8888;
3583 break;
3584 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003585 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003586 break;
3587 }
3588
Marissa Wallfd668622018-05-10 10:21:13 -07003589 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3590 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003591 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003592 *handle = layer->getHandle();
3593 *gbp = layer->getProducer();
3594 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003595 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003596
Marissa Wallfd668622018-05-10 10:21:13 -07003597 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003598 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003599}
3600
Marissa Wall61c58622018-07-18 10:12:20 -07003601status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3602 uint32_t w, uint32_t h, uint32_t flags,
3603 sp<IBinder>* handle, sp<Layer>* outLayer) {
3604 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3605 *handle = layer->getHandle();
3606 *outLayer = layer;
3607
3608 return NO_ERROR;
3609}
3610
chaviw13fdc492017-06-27 12:40:18 -07003611status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003612 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003613 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003614{
chaviw13fdc492017-06-27 12:40:18 -07003615 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003616 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003617 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003618}
3619
Mathias Agopianac9fa422013-02-11 16:40:36 -08003620status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003621{
Robert Carr9524cb32017-02-13 11:32:32 -08003622 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003623 status_t err = NO_ERROR;
3624 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003625 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003626 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003627 err = removeLayer(l);
3628 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3629 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003630 }
3631 return err;
3632}
3633
Mathias Agopian13127d82013-03-05 17:47:11 -08003634status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003635{
Mathias Agopian67106042013-03-14 19:18:13 -07003636 // called by ~LayerCleaner() when all references to the IBinder (handle)
3637 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003638 sp<Layer> l = layer.promote();
3639 if (l == nullptr) {
3640 // The layer has already been removed, carry on
3641 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003642 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003643 // If we have a parent, then we can continue to live as long as it does.
3644 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003645}
3646
Mathias Agopianb60314a2012-04-10 22:09:54 -07003647// ---------------------------------------------------------------------------
3648
Andy McFadden13a082e2012-08-24 10:16:42 -07003649void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003650 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3651 if (!displayToken) return;
3652
Jesse Hall01e29052013-02-19 16:13:35 -08003653 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003654 Vector<ComposerState> state;
3655 Vector<DisplayState> displays;
3656 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003657 d.what = DisplayState::eDisplayProjectionChanged |
3658 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003659 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003660 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003661 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003662 d.frame.makeInvalid();
3663 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003664 d.width = 0;
3665 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003666 displays.add(d);
3667 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003668
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003669 const auto display = getDisplayDevice(displayToken);
3670 if (!display) return;
3671
3672 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3673
3674 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003675 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003676 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003677
Brian Andersond0010582017-03-07 13:20:31 -08003678 // Use phase of 0 since phase is not known.
3679 // Use latency of 0, which will snap to the ideal latency.
3680 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003681}
3682
3683void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003684 // Async since we may be called from the main thread.
3685 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003686}
3687
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003688void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3689 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003690 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003691 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003692
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003693 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003694 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003695 return;
3696 }
3697
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003698 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003699 ALOGW("Trying to set power mode for virtual display");
3700 return;
3701 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003702
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003703 display->setPowerMode(mode);
3704
Lloyd Pique4dccc412018-01-22 17:21:36 -08003705 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003706 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003707 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003708 if (idx < 0) {
3709 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3710 return;
3711 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003712 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003713 }
3714
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003715 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003716 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003717 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003718 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003719 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003720 // FIXME: eventthread only knows about the main display right now
3721 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003722 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003723 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003724
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003725 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003726 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003727 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003728
3729 struct sched_param param = {0};
3730 param.sched_priority = 1;
3731 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3732 ALOGW("Couldn't set SCHED_FIFO on display on");
3733 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003734 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003735 // Turn off the display
3736 struct sched_param param = {0};
3737 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3738 ALOGW("Couldn't set SCHED_OTHER on display off");
3739 }
3740
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003741 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003742 disableHardwareVsync(true); // also cancels any in-progress resync
3743
Mathias Agopiancde87a32012-09-13 14:09:01 -07003744 // FIXME: eventthread only knows about the main display right now
3745 mEventThread->onScreenReleased();
3746 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003747
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003748 getHwComposer().setPowerMode(type, mode);
3749 mVisibleRegionsDirty = true;
3750 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003751 } else if (mode == HWC_POWER_MODE_DOZE ||
3752 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003753 // Update display while dozing
3754 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003755 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003756 // FIXME: eventthread only knows about the main display right now
3757 mEventThread->onScreenAcquired();
3758 resyncToHardwareVsync(true);
3759 }
3760 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3761 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003762 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003763 disableHardwareVsync(true); // also cancels any in-progress resync
3764 // FIXME: eventthread only knows about the main display right now
3765 mEventThread->onScreenReleased();
3766 }
3767 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003768 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003769 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003770 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003771 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003772
3773 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003774}
3775
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003776void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003777 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003778 const auto display = getDisplayDevice(displayToken);
3779 if (!display) {
3780 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3781 displayToken.get());
3782 } else if (display->isVirtual()) {
3783 ALOGW("Attempt to set power mode %d for virtual display", mode);
3784 } else {
3785 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003786 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003787 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003788}
3789
3790// ---------------------------------------------------------------------------
3791
Lloyd Pique755e3192018-01-31 16:46:15 -08003792status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3793 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003794 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003795
Mathias Agopianbd115332013-04-18 16:41:04 -07003796 IPCThreadState* ipc = IPCThreadState::self();
3797 const int pid = ipc->getCallingPid();
3798 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003799
Mathias Agopianbd115332013-04-18 16:41:04 -07003800 if ((uid != AID_SHELL) &&
3801 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003802 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003803 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003804 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003805 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003806 // (this would indicate SF is stuck, but we want to be able to
3807 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003808 status_t err = mStateLock.timedLock(s2ns(1));
3809 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003810 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003811 result.appendFormat(
3812 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3813 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003814 }
3815
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003816 bool dumpAll = true;
3817 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003818 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003819
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003820 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003821 if ((index < numArgs) &&
3822 (args[index] == String16("--list"))) {
3823 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003824 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003825 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003826 }
3827
3828 if ((index < numArgs) &&
3829 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003830 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003831 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003832 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003833 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003834
3835 if ((index < numArgs) &&
3836 (args[index] == String16("--latency-clear"))) {
3837 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003838 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003839 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003840 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003841
3842 if ((index < numArgs) &&
3843 (args[index] == String16("--dispsync"))) {
3844 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07003845 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07003846 dumpAll = false;
3847 }
Dan Stozab90cf072015-03-05 11:05:59 -08003848
3849 if ((index < numArgs) &&
3850 (args[index] == String16("--static-screen"))) {
3851 index++;
3852 dumpStaticScreenStats(result);
3853 dumpAll = false;
3854 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003855
3856 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003857 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003858 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003859 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003860 dumpAll = false;
3861 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003862
3863 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3864 index++;
3865 dumpWideColorInfo(result);
3866 dumpAll = false;
3867 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003868
3869 if ((index < numArgs) &&
3870 (args[index] == String16("--enable-layer-stats"))) {
3871 index++;
3872 mLayerStats.enable();
3873 dumpAll = false;
3874 }
3875
3876 if ((index < numArgs) &&
3877 (args[index] == String16("--disable-layer-stats"))) {
3878 index++;
3879 mLayerStats.disable();
3880 dumpAll = false;
3881 }
3882
3883 if ((index < numArgs) &&
3884 (args[index] == String16("--clear-layer-stats"))) {
3885 index++;
3886 mLayerStats.clear();
3887 dumpAll = false;
3888 }
3889
3890 if ((index < numArgs) &&
3891 (args[index] == String16("--dump-layer-stats"))) {
3892 index++;
3893 mLayerStats.dump(result);
3894 dumpAll = false;
3895 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003896
3897 if ((index < numArgs) &&
3898 (args[index] == String16("--display-identification"))) {
3899 index++;
3900 dumpDisplayIdentificationData(result);
3901 dumpAll = false;
3902 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003903
3904 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3905 index++;
3906 mTimeStats.parseArgs(asProto, args, index, result);
3907 dumpAll = false;
3908 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003909 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003910
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003911 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003912 if (asProto) {
3913 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3914 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3915 } else {
3916 dumpAllLocked(args, index, result);
3917 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003918 }
3919
Mathias Agopian9795c422009-08-26 16:36:26 -07003920 if (locked) {
3921 mStateLock.unlock();
3922 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003923 }
3924 write(fd, result.string(), result.size());
3925 return NO_ERROR;
3926}
3927
Dan Stozac7014012014-02-14 15:03:43 -08003928void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3929 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003930{
Robert Carr2047fae2016-11-28 14:09:09 -08003931 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003932 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003933 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003934}
3935
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003936void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003937 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003938{
3939 String8 name;
3940 if (index < args.size()) {
3941 name = String8(args[index]);
3942 index++;
3943 }
3944
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003945 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
3946 getHwComposer().isConnected(displayId)) {
3947 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
3948 const nsecs_t period = activeConfig->getVsyncPeriod();
3949 result.appendFormat("%" PRId64 "\n", period);
3950 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003951
3952 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003953 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003954 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003955 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003956 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003957 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003958 }
Robert Carr2047fae2016-11-28 14:09:09 -08003959 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003960 }
3961}
3962
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003963void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003964 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003965{
3966 String8 name;
3967 if (index < args.size()) {
3968 name = String8(args[index]);
3969 index++;
3970 }
3971
Robert Carr2047fae2016-11-28 14:09:09 -08003972 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003973 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003974 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003975 }
Robert Carr2047fae2016-11-28 14:09:09 -08003976 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003977
Svetoslavd85084b2014-03-20 10:28:31 -07003978 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003979}
3980
Jamie Gennis6547ff42013-07-16 20:12:42 -07003981// This should only be called from the main thread. Otherwise it would need
3982// the lock and should use mCurrentState rather than mDrawingState.
3983void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003984 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003985 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003986 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003987
3988 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3989}
3990
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003991void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003992{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003993 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003994
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003995 if (isLayerTripleBufferingDisabled())
3996 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003997
3998 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003999 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004000 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004001 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004002 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4003 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004004 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004005}
4006
Dan Stozab90cf072015-03-05 11:05:59 -08004007void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4008{
4009 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004010 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4011 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004012 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004013 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004014 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4015 b + 1, bucketTimeSec, percent);
4016 }
David Sodman4a36e932017-11-07 14:29:47 -08004017 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004018 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004019 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004020 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004021 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004022}
4023
Dan Stozae77c7662016-05-13 11:37:28 -07004024void SurfaceFlinger::recordBufferingStats(const char* layerName,
4025 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004026 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4027 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004028 for (const auto& segment : history) {
4029 if (!segment.usedThirdBuffer) {
4030 stats.twoBufferTime += segment.totalTime;
4031 }
4032 if (segment.occupancyAverage < 1.0f) {
4033 stats.doubleBufferedTime += segment.totalTime;
4034 } else if (segment.occupancyAverage < 2.0f) {
4035 stats.tripleBufferedTime += segment.totalTime;
4036 }
4037 ++stats.numSegments;
4038 stats.totalTime += segment.totalTime;
4039 }
4040}
4041
Brian Andersond6927fb2016-07-23 23:37:30 -07004042void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4043 result.appendFormat("Layer frame timestamps:\n");
4044
4045 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4046 const size_t count = currentLayers.size();
4047 for (size_t i=0 ; i<count ; i++) {
4048 currentLayers[i]->dumpFrameEvents(result);
4049 }
4050}
4051
Dan Stozae77c7662016-05-13 11:37:28 -07004052void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4053 result.append("Buffering stats:\n");
4054 result.append(" [Layer name] <Active time> <Two buffer> "
4055 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004056 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004057 typedef std::tuple<std::string, float, float, float> BufferTuple;
4058 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004059 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004060 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004061 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004062 if (stats.numSegments == 0) {
4063 continue;
4064 }
4065 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4066 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4067 stats.totalTime;
4068 float doubleBufferRatio = static_cast<float>(
4069 stats.doubleBufferedTime) / stats.totalTime;
4070 float tripleBufferRatio = static_cast<float>(
4071 stats.tripleBufferedTime) / stats.totalTime;
4072 sorted.insert({activeTime, {name, twoBufferRatio,
4073 doubleBufferRatio, tripleBufferRatio}});
4074 }
4075 for (const auto& sortedPair : sorted) {
4076 float activeTime = sortedPair.first;
4077 const BufferTuple& values = sortedPair.second;
4078 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4079 std::get<0>(values).c_str(), activeTime,
4080 std::get<1>(values), std::get<2>(values),
4081 std::get<3>(values));
4082 }
4083 result.append("\n");
4084}
4085
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004086void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004087 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004088 const int32_t displayId = display->getId();
4089 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4090 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004091 continue;
4092 }
4093
Dominik Laskowski7e045462018-05-30 13:02:02 -07004094 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004095 uint8_t port;
4096 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004097 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004098 result.append("no identification data\n");
4099 continue;
4100 }
4101
4102 if (!isEdid(data)) {
4103 result.append("unknown identification data: ");
4104 for (uint8_t byte : data) {
4105 result.appendFormat("%x ", byte);
4106 }
4107 result.append("\n");
4108 continue;
4109 }
4110
4111 const auto edid = parseEdid(data);
4112 if (!edid) {
4113 result.append("invalid EDID: ");
4114 for (uint8_t byte : data) {
4115 result.appendFormat("%x ", byte);
4116 }
4117 result.append("\n");
4118 continue;
4119 }
4120
4121 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4122 result.append(edid->displayName.data(), edid->displayName.length());
4123 result.append("\"\n");
4124 }
4125 result.append("\n");
4126}
4127
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004128void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4129 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004130 result.appendFormat("DisplayColorSetting: %s\n",
4131 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004132
4133 // TODO: print out if wide-color mode is active or not
4134
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004135 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004136 const int32_t displayId = display->getId();
4137 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004138 continue;
4139 }
4140
Dominik Laskowski7e045462018-05-30 13:02:02 -07004141 result.appendFormat("Display %d color modes:\n", displayId);
4142 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004143 for (auto&& mode : modes) {
4144 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4145 }
4146
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004147 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004148 result.appendFormat(" Current color mode: %s (%d)\n",
4149 decodeColorMode(currentMode).c_str(), currentMode);
4150 }
4151 result.append("\n");
4152}
4153
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004154LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004155 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004156 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4157 const State& state = useDrawing ? mDrawingState : mCurrentState;
4158 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004159 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004160 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004161 });
4162
4163 return layersProto;
4164}
4165
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004166LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004167 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004168
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004169 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004170 resolution->set_w(display.getWidth());
4171 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004172
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004173 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4174 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4175 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004176
Dominik Laskowski7e045462018-05-30 13:02:02 -07004177 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004178 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004179 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004180 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004181 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004182 }
4183 });
4184
4185 return layersProto;
4186}
4187
Mathias Agopian74d211a2013-04-22 16:55:35 +02004188void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4189 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004190{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004191 bool colorize = false;
4192 if (index < args.size()
4193 && (args[index] == String16("--color"))) {
4194 colorize = true;
4195 index++;
4196 }
4197
4198 Colorizer colorizer(colorize);
4199
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004200 // figure out if we're stuck somewhere
4201 const nsecs_t now = systemTime();
4202 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4203 const nsecs_t inTransaction(mDebugInTransaction);
4204 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4205 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4206
4207 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004208 * Dump library configuration.
4209 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004210
4211 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004212 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004213 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004214 appendSfConfigString(result);
4215 appendUiConfigString(result);
4216 appendGuiConfigString(result);
4217 result.append("\n");
4218
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004219 result.append("\nDisplay identification data:\n");
4220 dumpDisplayIdentificationData(result);
4221
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004222 result.append("\nWide-Color information:\n");
4223 dumpWideColorInfo(result);
4224
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004225 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004226 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004227 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004228 result.append(SyncFeatures::getInstance().toString());
4229 result.append("\n");
4230
Andy McFadden41d67d72014-04-25 16:58:34 -07004231 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004232 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004233 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004234
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004235 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4236 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004237 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4238 getHwComposer().isConnected(displayId)) {
4239 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004240 result.appendFormat("Display %d: "
4241 "app phase %" PRId64 " ns, "
4242 "sf phase %" PRId64 " ns, "
4243 "early app phase %" PRId64 " ns, "
4244 "early sf phase %" PRId64 " ns, "
4245 "early app gl phase %" PRId64 " ns, "
4246 "early sf gl phase %" PRId64 " ns, "
4247 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4248 displayId,
4249 vsyncPhaseOffsetNs,
4250 sfVsyncPhaseOffsetNs,
4251 appEarlyOffset,
4252 sfEarlyOffset,
4253 appEarlyGlOffset,
4254 sfEarlyOffset,
4255 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004256 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004257 result.append("\n");
4258
Dan Stozab90cf072015-03-05 11:05:59 -08004259 // Dump static screen stats
4260 result.append("\n");
4261 dumpStaticScreenStats(result);
4262 result.append("\n");
4263
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004264 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4265
Dan Stozae77c7662016-05-13 11:37:28 -07004266 dumpBufferingStats(result);
4267
Andy McFadden4803b742012-09-24 19:07:20 -07004268 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004269 * Dump the visible layer list
4270 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004271 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004272 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004273 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4274 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004275 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004276
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004277 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004278 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004279 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004280 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004281
4282 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004283 * Dump Display state
4284 */
4285
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004286 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004287 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004288 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004289 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004290 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004291 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004292 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004293
4294 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004295 * Dump SurfaceFlinger global state
4296 */
4297
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004298 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004299 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004300 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004301
Mathias Agopian888c8222012-08-04 21:10:38 -07004302 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004303 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004304
David Sodmanbc815282017-11-05 18:57:52 -08004305 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004306
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004307 if (display) {
4308 display->undefinedRegion.dump(result, "undefinedRegion");
4309 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4310 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004311 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004312 result.appendFormat(" last eglSwapBuffers() time: %f us\n"
4313 " last transaction time : %f us\n"
4314 " transaction-flags : %08x\n"
4315 " gpu_to_cpu_unsupported : %d\n",
4316 mLastSwapBufferTime / 1000.0, mLastTransactionTime / 1000.0,
4317 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(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004329 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004330
Mathias Agopian74d211a2013-04-22 16:55:35 +02004331 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004332 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004333
4334 /*
4335 * VSYNC state
4336 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004337 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004338 result.append("\n");
4339
4340 /*
4341 * HWC layer minidump
4342 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004343 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004344 const int32_t displayId = display->getId();
4345 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004346 continue;
4347 }
4348
Dominik Laskowski7e045462018-05-30 13:02:02 -07004349 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004350 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004351 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004352 result.append("\n");
4353 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004354
4355 /*
4356 * Dump HWComposer state
4357 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004358 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004359 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004360 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004361 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004362 result.appendFormat(" h/w composer %s\n",
4363 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004364 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004365
4366 /*
4367 * Dump gralloc state
4368 */
4369 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4370 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004371
4372 /*
4373 * Dump VrFlinger state if in use.
4374 */
4375 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4376 result.append("VrFlinger state:\n");
4377 result.append(mVrFlinger->Dump().c_str());
4378 result.append("\n");
4379 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004380}
4381
Dominik Laskowski7e045462018-05-30 13:02:02 -07004382const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004383 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004384 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004385 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004386 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004387 }
4388 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004389
4390 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4391 static const Vector<sp<Layer>> empty;
4392 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004393}
4394
Keun young Park63f165f2012-08-31 10:53:36 -07004395bool SurfaceFlinger::startDdmConnection()
4396{
4397 void* libddmconnection_dso =
4398 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4399 if (!libddmconnection_dso) {
4400 return false;
4401 }
4402 void (*DdmConnection_start)(const char* name);
4403 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004404 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004405 if (!DdmConnection_start) {
4406 dlclose(libddmconnection_dso);
4407 return false;
4408 }
4409 (*DdmConnection_start)(getServiceName());
4410 return true;
4411}
4412
Chia-I Wu28f320b2018-05-03 11:02:56 -07004413void SurfaceFlinger::updateColorMatrixLocked() {
4414 mat4 colorMatrix;
4415 if (mGlobalSaturationFactor != 1.0f) {
4416 // Rec.709 luma coefficients
4417 float3 luminance{0.213f, 0.715f, 0.072f};
4418 luminance *= 1.0f - mGlobalSaturationFactor;
4419 mat4 saturationMatrix = mat4(
4420 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4421 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4422 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4423 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4424 );
4425 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4426 } else {
4427 colorMatrix = mClientColorMatrix * mDaltonizer();
4428 }
4429
4430 if (mCurrentState.colorMatrix != colorMatrix) {
4431 mCurrentState.colorMatrix = colorMatrix;
4432 mCurrentState.colorMatrixChanged = true;
4433 setTransactionFlags(eTransactionNeeded);
4434 }
4435}
4436
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004437status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulecfbe2c002018-08-09 22:32:45 +00004438#pragma clang diagnostic push
4439#pragma clang diagnostic error "-Wswitch-enum"
4440 switch (static_cast<ISurfaceComposerTag>(code)) {
4441 // These methods should at minimum make sure that the client requested
4442 // access to SF.
4443 case AUTHENTICATE_SURFACE:
Peiyong Line70e1292018-08-09 14:06:58 -07004444 case BOOT_FINISHED:
4445 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulecfbe2c002018-08-09 22:32:45 +00004446 case CREATE_CONNECTION:
4447 case CREATE_DISPLAY:
4448 case DESTROY_DISPLAY:
Peiyong Line70e1292018-08-09 14:06:58 -07004449 case ENABLE_VSYNC_INJECTIONS:
Ana Krulecfbe2c002018-08-09 22:32:45 +00004450 case GET_ACTIVE_COLOR_MODE:
4451 case GET_ANIMATION_FRAME_STATS:
4452 case GET_HDR_CAPABILITIES:
4453 case SET_ACTIVE_CONFIG:
4454 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004455 case INJECT_VSYNC:
Ana Krulecfbe2c002018-08-09 22:32:45 +00004456 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004457 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4458 IPCThreadState* ipc = IPCThreadState::self();
4459 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4460 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004461 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004462 }
Robert Carr1db73f62016-12-21 12:58:51 -08004463 return OK;
4464 }
Ana Krulecfbe2c002018-08-09 22:32:45 +00004465 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004466 IPCThreadState* ipc = IPCThreadState::self();
4467 const int pid = ipc->getCallingPid();
4468 const int uid = ipc->getCallingUid();
Ana Krulecfbe2c002018-08-09 22:32:45 +00004469 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4470 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004471 return PERMISSION_DENIED;
4472 }
Ana Krulecfbe2c002018-08-09 22:32:45 +00004473 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004474 }
Ana Krulecfbe2c002018-08-09 22:32:45 +00004475 // Used by apps to hook Choreographer to SurfaceFlinger.
4476 case CREATE_DISPLAY_EVENT_CONNECTION:
4477 // The following calls are currently used by clients that do not
4478 // request necessary permissions. However, they do not expose any secret
4479 // information, so it is OK to pass them.
4480 case GET_ACTIVE_CONFIG:
4481 case GET_BUILT_IN_DISPLAY:
4482 case GET_DISPLAY_COLOR_MODES:
4483 case GET_DISPLAY_CONFIGS:
4484 case GET_DISPLAY_STATS:
4485 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4486 // Calling setTransactionState is safe, because you need to have been
4487 // granted a reference to Client* and Handle* to do anything with it.
4488 case SET_TRANSACTION_STATE:
4489 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4490 case CREATE_SCOPED_CONNECTION: {
4491 return OK;
4492 }
4493 case CAPTURE_LAYERS:
4494 case CAPTURE_SCREEN: {
4495 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004496 IPCThreadState* ipc = IPCThreadState::self();
4497 const int pid = ipc->getCallingPid();
4498 const int uid = ipc->getCallingUid();
4499 if ((uid != AID_GRAPHICS) &&
4500 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4501 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4502 return PERMISSION_DENIED;
4503 }
Ana Krulecfbe2c002018-08-09 22:32:45 +00004504 return OK;
4505 }
4506 // The following codes are deprecated and should never be allowed to access SF.
4507 case CONNECT_DISPLAY_UNUSED:
4508 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4509 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4510 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004511 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004512 }
Ana Krulecfbe2c002018-08-09 22:32:45 +00004513
4514 // These codes are used for the IBinder protocol to either interrogate the recipient
4515 // side of the transaction for its canonical interface descriptor or to dump its state.
4516 // We let them pass by default.
4517 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4518 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4519 code == IBinder::SYSPROPS_TRANSACTION) {
4520 return OK;
4521 }
4522 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4523 // in onTransact verifies that the user is root, and has access to use SF.
4524 if (code >= 1000 && code <= 1029) {
4525 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4526 return OK;
4527 }
4528 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4529 return PERMISSION_DENIED;
4530#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004531}
4532
Ana Krulecfbe2c002018-08-09 22:32:45 +00004533status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4534 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004535 status_t credentialCheck = CheckTransactCodeCredentials(code);
4536 if (credentialCheck != OK) {
4537 return credentialCheck;
4538 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004539
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004540 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4541 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004542 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004543 IPCThreadState* ipc = IPCThreadState::self();
4544 const int uid = ipc->getCallingUid();
4545 if (CC_UNLIKELY(uid != AID_SYSTEM
4546 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004547 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004548 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004549 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004550 return PERMISSION_DENIED;
4551 }
4552 int n;
4553 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004554 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004555 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004556 return NO_ERROR;
4557 case 1002: // SHOW_UPDATES
4558 n = data.readInt32();
4559 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004560 invalidateHwcGeometry();
4561 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004562 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004563 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004564 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004565 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004566 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004567 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004568 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004569 setTransactionFlags(
4570 eTransactionNeeded|
4571 eDisplayTransactionNeeded|
4572 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004573 return NO_ERROR;
4574 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004575 case 1006:{ // send empty update
4576 signalRefresh();
4577 return NO_ERROR;
4578 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004579 case 1008: // toggle use of hw composer
4580 n = data.readInt32();
4581 mDebugDisableHWC = n ? 1 : 0;
4582 invalidateHwcGeometry();
4583 repaintEverything();
4584 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004585 case 1009: // toggle use of transform hint
4586 n = data.readInt32();
4587 mDebugDisableTransformHint = n ? 1 : 0;
4588 invalidateHwcGeometry();
4589 repaintEverything();
4590 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004591 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004592 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004593 reply->writeInt32(0);
4594 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004595 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004596 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004597 return NO_ERROR;
4598 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004599 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004600 if (!display) {
4601 return NAME_NOT_FOUND;
4602 }
4603
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004604 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004605 return NO_ERROR;
4606 }
4607 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004608 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004609 // daltonize
4610 n = data.readInt32();
4611 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004612 case 1:
4613 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4614 break;
4615 case 2:
4616 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4617 break;
4618 case 3:
4619 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4620 break;
4621 default:
4622 mDaltonizer.setType(ColorBlindnessType::None);
4623 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004624 }
4625 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004626 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004627 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004628 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004629 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004630
4631 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004632 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004633 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004634 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004635 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004636 // apply a color matrix
4637 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004638 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004639 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004640 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004641 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004642 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004643 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004644 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004645 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004646 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004647 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004648
4649 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4650 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004651 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004652 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4653 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4654 }
4655
Chia-I Wu28f320b2018-05-03 11:02:56 -07004656 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004657 return NO_ERROR;
4658 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004659 // This is an experimental interface
4660 // Needs to be shifted to proper binder interface when we productize
4661 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004662 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07004663 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004664 return NO_ERROR;
4665 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004666 case 1017: {
4667 n = data.readInt32();
4668 mForceFullDamage = static_cast<bool>(n);
4669 return NO_ERROR;
4670 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004671 case 1018: { // Modify Choreographer's phase offset
4672 n = data.readInt32();
4673 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4674 return NO_ERROR;
4675 }
4676 case 1019: { // Modify SurfaceFlinger's phase offset
4677 n = data.readInt32();
4678 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4679 return NO_ERROR;
4680 }
Irvel468051e2016-06-13 16:44:44 -07004681 case 1020: { // Layer updates interceptor
4682 n = data.readInt32();
4683 if (n) {
4684 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004685 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004686 }
4687 else{
4688 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004689 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004690 }
4691 return NO_ERROR;
4692 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004693 case 1021: { // Disable HWC virtual displays
4694 n = data.readInt32();
4695 mUseHwcVirtualDisplays = !n;
4696 return NO_ERROR;
4697 }
Romain Guy0147a172017-06-01 13:53:56 -07004698 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004699 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004700 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004701
Chia-I Wu28f320b2018-05-03 11:02:56 -07004702 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004703 return NO_ERROR;
4704 }
Romain Guy54f154a2017-10-24 21:40:32 +01004705 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004706 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004707 invalidateHwcGeometry();
4708 repaintEverything();
4709 return NO_ERROR;
4710 }
4711 case 1024: { // Is wide color gamut rendering/color management supported?
4712 reply->writeBool(hasWideColorDisplay);
4713 return NO_ERROR;
4714 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004715 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004716 n = data.readInt32();
4717 if (n) {
4718 ALOGV("LayerTracing enabled");
4719 mTracing.enable();
4720 doTracing("tracing.enable");
4721 reply->writeInt32(NO_ERROR);
4722 } else {
4723 ALOGV("LayerTracing disabled");
4724 status_t err = mTracing.disable();
4725 reply->writeInt32(err);
4726 }
4727 return NO_ERROR;
4728 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004729 case 1026: { // Get layer tracing status
4730 reply->writeBool(mTracing.isEnabled());
4731 return NO_ERROR;
4732 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004733 // Is a DisplayColorSetting supported?
4734 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004735 const auto display = getDefaultDisplayDevice();
4736 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004737 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004738 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004739
4740 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4741 switch (setting) {
4742 case DisplayColorSetting::MANAGED:
4743 reply->writeBool(hasWideColorDisplay);
4744 break;
4745 case DisplayColorSetting::UNMANAGED:
4746 reply->writeBool(true);
4747 break;
4748 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004749 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004750 break;
4751 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004752 reply->writeBool(
4753 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004754 break;
4755 }
4756 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004757 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004758 // Is VrFlinger active?
4759 case 1028: {
4760 Mutex::Autolock _l(mStateLock);
4761 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4762 return NO_ERROR;
4763 }
David Sodman6d46c1e2018-07-13 12:59:48 -07004764 case 1029: {
4765 // Code 1029 is an experimental feature that allows applications to
4766 // simulate a high frequency panel by setting a multiplier and divisor
4767 // on the VSYNC-sf clock. If either the multiplier or divisor are
4768 // 0, then the code will set both to 1 to return the VSYNC-sf clock
4769 // to it's normal frequency.
4770 int multiplier = data.readInt32();
4771 int divisor = data.readInt32();
4772
4773 if ((multiplier == 0) || (divisor == 0)) {
4774 multiplier = 1;
4775 divisor = 1;
4776 }
4777
4778 if ((multiplier == 1) && (divisor == 1)) {
4779 enableHardwareVsync();
4780 } else {
4781 disableHardwareVsync(true);
4782 }
4783 getBE().mHwc->getActiveConfig(DisplayDevice::DISPLAY_PRIMARY)
4784 ->scalePanelFrequency(multiplier, divisor);
4785 mPrimaryDispSync->scalePeriod(multiplier, divisor);
4786
4787 ATRACE_INT("PeriodMultiplier", multiplier);
4788 ATRACE_INT("PeriodDivisor", divisor);
4789 return NO_ERROR;
4790 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004791 }
4792 }
4793 return err;
4794}
4795
Steven Thomas6d8110b2017-08-31 18:24:21 -07004796void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004797 android_atomic_or(1, &mRepaintEverything);
4798 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004799}
4800
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004801// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4802class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004803public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004804 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4805 ~WindowDisconnector() {
4806 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004807 }
4808
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004809private:
4810 ANativeWindow* mWindow;
4811 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004812};
4813
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004814status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4815 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4816 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4817 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004818 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004819 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004820
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004821 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004822
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004823 const auto display = getDisplayDeviceLocked(displayToken);
4824 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004825
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004826 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004827
4828 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004829 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004830 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004831}
4832
4833status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004834 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004835 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004836 ATRACE_CALL();
4837
4838 class LayerRenderArea : public RenderArea {
4839 public:
Robert Carr578038f2018-03-09 12:25:24 -08004840 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4841 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004842 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004843 mLayer(layer),
4844 mCrop(crop),
4845 mFlinger(flinger),
4846 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004847 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004848 Rect getBounds() const override {
4849 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07004850 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07004851 }
Marissa Wall61c58622018-07-18 10:12:20 -07004852 int getHeight() const override {
4853 return mLayer->getActiveHeight(mLayer->getDrawingState());
4854 }
4855 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07004856 bool isSecure() const override { return false; }
4857 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004858 Rect getSourceCrop() const override {
4859 if (mCrop.isEmpty()) {
4860 return getBounds();
4861 } else {
4862 return mCrop;
4863 }
4864 }
Robert Carr578038f2018-03-09 12:25:24 -08004865 class ReparentForDrawing {
4866 public:
4867 const sp<Layer>& oldParent;
4868 const sp<Layer>& newParent;
4869
4870 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4871 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004872 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004873 }
Robert Carr15eae092018-03-23 13:43:53 -07004874 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004875 };
4876
4877 void render(std::function<void()> drawLayers) override {
4878 if (!mChildrenOnly) {
4879 mTransform = mLayer->getTransform().inverse();
4880 drawLayers();
4881 } else {
4882 Rect bounds = getBounds();
4883 screenshotParentLayer =
4884 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4885 bounds.getWidth(), bounds.getHeight(), 0);
4886
4887 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4888 drawLayers();
4889 }
4890 }
chaviwa76b2712017-09-20 12:02:26 -07004891
chaviwa76b2712017-09-20 12:02:26 -07004892 private:
chaviw7206d492017-11-10 16:16:12 -08004893 const sp<Layer> mLayer;
4894 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004895
4896 // In the "childrenOnly" case we reparent the children to a screenshot
4897 // layer which has no properties set and which does not draw.
4898 sp<ContainerLayer> screenshotParentLayer;
4899 Transform mTransform;
4900
4901 SurfaceFlinger* mFlinger;
4902 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004903 };
4904
4905 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4906 auto parent = layerHandle->owner.promote();
4907
chaviw7206d492017-11-10 16:16:12 -08004908 if (parent == nullptr || parent->isPendingRemoval()) {
4909 ALOGE("captureLayers called with a removed parent");
4910 return NAME_NOT_FOUND;
4911 }
4912
Robert Carr578038f2018-03-09 12:25:24 -08004913 const int uid = IPCThreadState::self()->getCallingUid();
4914 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4915 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4916 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4917 return PERMISSION_DENIED;
4918 }
4919
chaviw7206d492017-11-10 16:16:12 -08004920 Rect crop(sourceCrop);
4921 if (sourceCrop.width() <= 0) {
4922 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07004923 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08004924 }
4925
4926 if (sourceCrop.height() <= 0) {
4927 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07004928 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08004929 }
4930
4931 int32_t reqWidth = crop.width() * frameScale;
4932 int32_t reqHeight = crop.height() * frameScale;
4933
Robert Carr578038f2018-03-09 12:25:24 -08004934 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004935
Robert Carr578038f2018-03-09 12:25:24 -08004936 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004937 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4938 if (!layer->isVisible()) {
4939 return;
Robert Carr578038f2018-03-09 12:25:24 -08004940 } else if (childrenOnly && layer == parent.get()) {
4941 return;
chaviwa76b2712017-09-20 12:02:26 -07004942 }
4943 visitor(layer);
4944 });
4945 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004946 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004947}
4948
4949status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4950 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004951 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004952 bool useIdentityTransform) {
4953 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004954
Iris Chang7501ed62018-04-30 14:45:42 +08004955 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004956
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004957 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4958 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4959 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4960 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004961
4962 // This mutex protects syncFd and captureResult for communication of the return values from the
4963 // main thread back to this Binder thread
4964 std::mutex captureMutex;
4965 std::condition_variable captureCondition;
4966 std::unique_lock<std::mutex> captureLock(captureMutex);
4967 int syncFd = -1;
4968 std::optional<status_t> captureResult;
4969
Robert Carr03480e22018-01-04 16:02:06 -08004970 const int uid = IPCThreadState::self()->getCallingUid();
4971 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4972
Dominik Laskowski8c001672018-05-30 16:52:06 -07004973 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004974 // If there is a refresh pending, bug out early and tell the binder thread to try again
4975 // after the refresh.
4976 if (mRefreshPending) {
4977 ATRACE_NAME("Skipping screenshot for now");
4978 std::unique_lock<std::mutex> captureLock(captureMutex);
4979 captureResult = std::make_optional<status_t>(EAGAIN);
4980 captureCondition.notify_one();
4981 return;
4982 }
4983
4984 status_t result = NO_ERROR;
4985 int fd = -1;
4986 {
4987 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07004988 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08004989 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4990 useIdentityTransform, forSystem, &fd);
4991 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004992 }
4993
4994 {
4995 std::unique_lock<std::mutex> captureLock(captureMutex);
4996 syncFd = fd;
4997 captureResult = std::make_optional<status_t>(result);
4998 captureCondition.notify_one();
4999 }
5000 });
5001
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005002 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005003 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005004 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005005 while (*captureResult == EAGAIN) {
5006 captureResult.reset();
5007 result = postMessageAsync(message);
5008 if (result != NO_ERROR) {
5009 return result;
5010 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005011 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005012 }
5013 result = *captureResult;
5014 }
5015
5016 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005017 sync_wait(syncFd, -1);
5018 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005019 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005020
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005021 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005022}
5023
chaviwa76b2712017-09-20 12:02:26 -07005024void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5025 TraverseLayersFunction traverseLayers, bool yswap,
5026 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005027 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005028
Lloyd Pique144e1162017-12-20 16:44:52 -08005029 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005030
5031 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005032 const auto raWidth = renderArea.getWidth();
5033 const auto raHeight = renderArea.getHeight();
5034
5035 const auto reqWidth = renderArea.getReqWidth();
5036 const auto reqHeight = renderArea.getReqHeight();
5037 Rect sourceCrop = renderArea.getSourceCrop();
5038
Iris Chang7501ed62018-04-30 14:45:42 +08005039 bool filtering = false;
5040 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5041 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5042 static_cast<int32_t>(reqHeight) != raWidth;
5043 } else {
5044 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5045 static_cast<int32_t>(reqHeight) != raHeight;
5046 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005047
Dan Stozac1879002014-05-22 15:59:05 -07005048 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005049 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005050 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005051 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005052 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5053 Transform tr;
5054 uint32_t flags = 0x00;
5055 switch (mPrimaryDisplayOrientation) {
5056 case DisplayState::eOrientation90:
5057 flags = Transform::ROT_90;
5058 break;
5059 case DisplayState::eOrientation180:
5060 flags = Transform::ROT_180;
5061 break;
5062 case DisplayState::eOrientation270:
5063 flags = Transform::ROT_270;
5064 break;
5065 }
5066 tr.set(flags, raWidth, raHeight);
5067 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005068 }
5069
5070 // ensure that sourceCrop is inside screen
5071 if (sourceCrop.left < 0) {
5072 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5073 }
chaviwa76b2712017-09-20 12:02:26 -07005074 if (sourceCrop.right > raWidth) {
5075 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005076 }
5077 if (sourceCrop.top < 0) {
5078 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5079 }
chaviwa76b2712017-09-20 12:02:26 -07005080 if (sourceCrop.bottom > raHeight) {
5081 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005082 }
5083
Chia-I Wu36574d92018-05-16 10:54:36 -07005084 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5085 engine.setOutputDataSpace(Dataspace::SRGB);
5086 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005087
Mathias Agopian180f10d2013-04-10 22:55:41 -07005088 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005089 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005090
Iris Chang7501ed62018-04-30 14:45:42 +08005091 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5092 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5093 // convert hw orientation into flag presentation
5094 // here inverse transform needed
5095 uint8_t hw_rot_90 = 0x00;
5096 uint8_t hw_flip_hv = 0x00;
5097 switch (mPrimaryDisplayOrientation) {
5098 case DisplayState::eOrientation90:
5099 hw_rot_90 = Transform::ROT_90;
5100 hw_flip_hv = Transform::ROT_180;
5101 break;
5102 case DisplayState::eOrientation180:
5103 hw_flip_hv = Transform::ROT_180;
5104 break;
5105 case DisplayState::eOrientation270:
5106 hw_rot_90 = Transform::ROT_90;
5107 break;
5108 }
5109
5110 // transform flags operation
5111 // 1) flip H V if both have ROT_90 flag
5112 // 2) XOR these flags
5113 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5114 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5115 if (rotation_rot_90 & hw_rot_90) {
5116 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5117 }
5118 rotation = static_cast<Transform::orientation_flags>
5119 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5120 }
5121
Mathias Agopian180f10d2013-04-10 22:55:41 -07005122 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005123 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005124 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005125 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005126
chaviw50da5042018-04-09 13:49:37 -07005127 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005128 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005129 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005130
chaviwa76b2712017-09-20 12:02:26 -07005131 traverseLayers([&](Layer* layer) {
5132 if (filtering) layer->setFiltering(true);
David Sodmanca10ed22018-04-16 14:10:25 -07005133 layer->drawNow(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005134 if (filtering) layer->setFiltering(false);
5135 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005136}
5137
chaviwa76b2712017-09-20 12:02:26 -07005138status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5139 TraverseLayersFunction traverseLayers,
5140 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005141 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005142 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005143 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005144 ATRACE_CALL();
5145
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005146 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005147
5148 traverseLayers([&](Layer* layer) {
5149 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5150 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005151
Robert Carr03480e22018-01-04 16:02:06 -08005152 // We allow the system server to take screenshots of secure layers for
5153 // use in situations like the Screen-rotation animation and place
5154 // the impetus on WindowManager to not persist them.
5155 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005156 ALOGW("FB is protected: PERMISSION_DENIED");
5157 return PERMISSION_DENIED;
5158 }
5159
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005160 // this binds the given EGLImage as a framebuffer for the
5161 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005162 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005163 if (bufferBond.getStatus() != NO_ERROR) {
5164 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005165 return INVALID_OPERATION;
5166 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005167
Dan Stozaabcda352017-06-01 14:37:39 -07005168 // this will in fact render into our dequeued buffer
5169 // via an FBO, which means we didn't have to create
5170 // an EGLSurface and therefore we're not
5171 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005172 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005173
Dan Stozaabcda352017-06-01 14:37:39 -07005174 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005175 getRenderEngine().finish();
5176 *outSyncFd = -1;
5177
chaviwa76b2712017-09-20 12:02:26 -07005178 const auto reqWidth = renderArea.getReqWidth();
5179 const auto reqHeight = renderArea.getReqHeight();
5180
Dan Stozaabcda352017-06-01 14:37:39 -07005181 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5182 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005183 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005184 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005185 } else {
5186 base::unique_fd syncFd = getRenderEngine().flush();
5187 if (syncFd < 0) {
5188 getRenderEngine().finish();
5189 }
5190 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005191 }
5192
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005193 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005194}
5195
Mathias Agopiand5556842013-09-19 17:08:37 -07005196void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005197 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005198 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005199 for (size_t y = 0; y < h; y++) {
5200 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5201 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005202 if (p[x] != 0xFF000000) return;
5203 }
5204 }
chaviwa76b2712017-09-20 12:02:26 -07005205 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005206
Robert Carr2047fae2016-11-28 14:09:09 -08005207 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005208 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005209 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005210 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5211 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5212 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5213 static_cast<float>(state.color.a));
5214 i++;
5215 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005216 }
5217}
5218
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005219// ---------------------------------------------------------------------------
5220
Dan Stoza412903f2017-04-27 13:42:17 -07005221void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5222 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005223}
5224
Dan Stoza412903f2017-04-27 13:42:17 -07005225void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5226 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005227}
5228
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005229void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5230 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005231 const LayerVector::Visitor& visitor) {
5232 // We loop through the first level of layers without traversing,
5233 // as we need to interpret min/max layer Z in the top level Z space.
5234 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005235 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005236 continue;
5237 }
5238 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005239 // relative layers are traversed in Layer::traverseInZOrder
5240 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005241 continue;
5242 }
5243 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005244 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005245 return;
5246 }
chaviwa76b2712017-09-20 12:02:26 -07005247 if (!layer->isVisible()) {
5248 return;
5249 }
5250 visitor(layer);
5251 });
5252 }
5253}
5254
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005255}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005256
Lloyd Pique074e8122018-07-26 12:57:23 -07005257
Mathias Agopian3f844832013-08-07 21:24:32 -07005258#if defined(__gl_h_)
5259#error "don't include gl/gl.h in this file"
5260#endif
5261
5262#if defined(__gl2_h_)
5263#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005264#endif