blob: 41c7f22bc7c9f3f460fb2f0084605411603b4ac6 [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 }
tangrobin6753a022018-08-10 10:58:54 +08002204 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002205
tangrobin6753a022018-08-10 10:58:54 +08002206 if (displayId >= 0) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002207 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2208 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2209 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002210
2211 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2212 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2213
2214 /*
2215 * Create our display's surface
2216 */
2217 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2218 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002219 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002220 renderSurface->setNativeWindow(nativeWindow.get());
2221 const int displayWidth = renderSurface->queryWidth();
2222 const int displayHeight = renderSurface->queryHeight();
2223
2224 // Make sure that composition can never be stalled by a virtual display
2225 // consumer that isn't processing buffers fast enough. We have to do this
2226 // in two places:
2227 // * Here, in case the display is composed entirely by HWC.
2228 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2229 // window's swap interval in eglMakeCurrent, so they'll override the
2230 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002231 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002232 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2233 }
2234
2235 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002236 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002237
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002238 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002239 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2240 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2241 displayHeight, hasWideColorGamut, hdrCapabilities,
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002242 supportedPerFrameMetadata, hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002243
2244 if (maxFrameBufferAcquiredBuffers >= 3) {
2245 nativeWindowSurface->preallocateBuffers();
2246 }
2247
2248 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002249 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2250 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002251 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002252 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002253 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002254 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002255 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002256 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002257 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002258 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002259 display->setLayerStack(state.layerStack);
2260 display->setProjection(state.orientation, state.viewport, state.frame);
2261 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002262
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002263 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002264}
2265
Lloyd Pique347200f2017-12-14 17:00:15 -08002266void SurfaceFlinger::processDisplayChangesLocked() {
2267 // here we take advantage of Vector's copy-on-write semantics to
2268 // improve performance by skipping the transaction entirely when
2269 // know that the lists are identical
2270 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2271 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2272 if (!curr.isIdenticalTo(draw)) {
2273 mVisibleRegionsDirty = true;
2274 const size_t cc = curr.size();
2275 size_t dc = draw.size();
2276
2277 // find the displays that were removed
2278 // (ie: in drawing state but not in current state)
2279 // also handle displays that changed
2280 // (ie: displays that are in both lists)
2281 for (size_t i = 0; i < dc;) {
2282 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2283 if (j < 0) {
2284 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002285 // Call makeCurrent() on the primary display so we can
2286 // be sure that nothing associated with this display
2287 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002288 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2289 defaultDisplay->makeCurrent();
2290 }
2291 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2292 display->disconnect(getHwComposer());
2293 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002294 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2295 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2296 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2297 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2298 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002299 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002300 } else {
2301 // this display is in both lists. see if something changed.
2302 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002303 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002304 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2305 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2306 if (state_binder != draw_binder) {
2307 // changing the surface is like destroying and
2308 // recreating the DisplayDevice, so we just remove it
2309 // from the drawing state, so that it get re-added
2310 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002311 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2312 display->disconnect(getHwComposer());
2313 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002314 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002315 mDrawingState.displays.removeItemsAt(i);
2316 dc--;
2317 // at this point we must loop to the next item
2318 continue;
2319 }
2320
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002321 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002322 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002323 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002324 }
2325 if ((state.orientation != draw[i].orientation) ||
2326 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002327 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002328 }
2329 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002330 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002331 }
2332 }
2333 }
2334 ++i;
2335 }
2336
2337 // find displays that were added
2338 // (ie: in current state but not in drawing state)
2339 for (size_t i = 0; i < cc; i++) {
2340 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2341 const DisplayDeviceState& state(curr[i]);
2342
2343 sp<DisplaySurface> dispSurface;
2344 sp<IGraphicBufferProducer> producer;
2345 sp<IGraphicBufferProducer> bqProducer;
2346 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002347 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002348
Dominik Laskowski7e045462018-05-30 13:02:02 -07002349 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002350 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002351 // Virtual displays without a surface are dormant:
2352 // they have external state (layer stack, projection,
2353 // etc.) but no internal state (i.e. a DisplayDevice).
2354 if (state.surface != nullptr) {
2355 // Allow VR composer to use virtual displays.
2356 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2357 int width = 0;
2358 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2359 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2360 int height = 0;
2361 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2362 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2363 int intFormat = 0;
2364 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2365 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002366 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002367
Dominik Laskowski7e045462018-05-30 13:02:02 -07002368 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2369 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002370 }
2371
2372 // TODO: Plumb requested format back up to consumer
2373
2374 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002375 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002376 bqProducer, bqConsumer,
2377 state.displayName);
2378
2379 dispSurface = vds;
2380 producer = vds;
2381 }
2382 } else {
2383 ALOGE_IF(state.surface != nullptr,
2384 "adding a supported display, but rendering "
2385 "surface is provided (%p), ignoring it",
2386 state.surface.get());
2387
Dominik Laskowski7e045462018-05-30 13:02:02 -07002388 displayId = state.type;
2389 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002390 producer = bqProducer;
2391 }
2392
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002393 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002394 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002395 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002396 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002397 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002398 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002399 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2400 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2401 true);
2402 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2403 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2404 true);
2405 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002406 }
2407 }
2408 }
2409 }
2410 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002411
2412 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002413}
2414
Mathias Agopian87baae12012-07-31 12:38:26 -07002415void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002416{
Dan Stoza7dde5992015-05-22 09:51:44 -07002417 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002418 mCurrentState.traverseInZOrder([](Layer* layer) {
2419 layer->notifyAvailableFrames();
2420 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002421
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002422 /*
2423 * Traversal of the children
2424 * (perform the transaction for each of them if needed)
2425 */
2426
Mathias Agopian3559b072012-08-15 13:46:03 -07002427 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002428 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002429 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002430 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002431
2432 const uint32_t flags = layer->doTransaction(0);
2433 if (flags & Layer::eVisibleRegion)
2434 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002435 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002436 }
2437
2438 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002439 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002440 */
2441
Mathias Agopiane57f2922012-08-09 16:29:12 -07002442 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002443 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002444 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002445 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002446
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002447 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002448 // The transform hint might have changed for some layers
2449 // (either because a display has changed, or because a layer
2450 // as changed).
2451 //
2452 // Walk through all the layers in currentLayers,
2453 // and update their transform hint.
2454 //
2455 // If a layer is visible only on a single display, then that
2456 // display is used to calculate the hint, otherwise we use the
2457 // default display.
2458 //
2459 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2460 // the hint is set before we acquire a buffer from the surface texture.
2461 //
2462 // NOTE: layer transactions have taken place already, so we use their
2463 // drawing state. However, SurfaceFlinger's own transaction has not
2464 // happened yet, so we must use the current state layer list
2465 // (soon to become the drawing state list).
2466 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002467 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002468 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002469 bool first = true;
2470 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002471 // NOTE: we rely on the fact that layers are sorted by
2472 // layerStack first (so we don't have to traverse the list
2473 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002474 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002475 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002476 currentlayerStack = layerStack;
2477 // figure out if this layerstack is mirrored
2478 // (more than one display) if so, pick the default display,
2479 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002480 hintDisplay = nullptr;
2481 for (const auto& [token, display] : mDisplays) {
2482 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2483 if (hintDisplay) {
2484 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002485 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002486 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002487 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002488 }
2489 }
2490 }
2491 }
Chet Haase91d25932013-04-11 15:24:55 -07002492
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002493 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002494 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2495 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002496
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002497 // could be null when this layer is using a layerStack
2498 // that is not visible on any display. Also can occur at
2499 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002500 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002501 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002502
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002503 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002504 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002505 if (hintDisplay) {
2506 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002507 }
Robert Carr2047fae2016-11-28 14:09:09 -08002508
2509 first = false;
2510 });
Mathias Agopian84300952012-11-21 16:02:13 -08002511 }
2512
2513
Mathias Agopian3559b072012-08-15 13:46:03 -07002514 /*
2515 * Perform our own transaction if needed
2516 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002517
2518 if (mLayersAdded) {
2519 mLayersAdded = false;
2520 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002521 mVisibleRegionsDirty = true;
2522 }
2523
2524 // some layers might have been removed, so
2525 // we need to update the regions they're exposing.
2526 if (mLayersRemoved) {
2527 mLayersRemoved = false;
2528 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002529 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002530 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002531 // this layer is not visible anymore
2532 // TODO: we could traverse the tree from front to back and
2533 // compute the actual visible region
2534 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002535 Region visibleReg;
2536 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002537 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002538 }
Robert Carr2047fae2016-11-28 14:09:09 -08002539 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002540 }
2541
2542 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002543
2544 updateCursorAsync();
2545}
2546
2547void SurfaceFlinger::updateCursorAsync()
2548{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002549 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002550 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002551 continue;
2552 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002553
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002554 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2555 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002556 }
2557 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002558}
2559
2560void SurfaceFlinger::commitTransaction()
2561{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002562 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002563 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002564 for (const auto& l : mLayersPendingRemoval) {
2565 recordBufferingStats(l->getName().string(),
2566 l->getOccupancyHistory(true));
2567 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002568 }
2569 mLayersPendingRemoval.clear();
2570 }
2571
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002572 // If this transaction is part of a window animation then the next frame
2573 // we composite should be considered an animation as well.
2574 mAnimCompositionPending = mAnimTransactionPending;
2575
Mathias Agopian4fec8732012-06-29 14:12:52 -07002576 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002577 // clear the "changed" flags in current state
2578 mCurrentState.colorMatrixChanged = false;
2579
Robert Carr1f0a16a2016-10-24 16:27:39 -07002580 mDrawingState.traverseInZOrder([](Layer* layer) {
2581 layer->commitChildList();
2582 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002583 mTransactionPending = false;
2584 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002585 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002586}
2587
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002588void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2589 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002590 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002591 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002592
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002593 Region aboveOpaqueLayers;
2594 Region aboveCoveredLayers;
2595 Region dirty;
2596
Mathias Agopian87baae12012-07-31 12:38:26 -07002597 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002598
Robert Carr2047fae2016-11-28 14:09:09 -08002599 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002600 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002601 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002602
Jesse Hall01e29052013-02-19 16:13:35 -08002603 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002604 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002605 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002606 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002607
Mathias Agopianab028732010-03-16 16:41:46 -07002608 /*
2609 * opaqueRegion: area of a surface that is fully opaque.
2610 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002611 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002612
2613 /*
2614 * visibleRegion: area of a surface that is visible on screen
2615 * and not fully transparent. This is essentially the layer's
2616 * footprint minus the opaque regions above it.
2617 * Areas covered by a translucent surface are considered visible.
2618 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002619 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002620
2621 /*
2622 * coveredRegion: area of a surface that is covered by all
2623 * visible regions above it (which includes the translucent areas).
2624 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002625 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002626
Jesse Halla8026d22012-09-25 13:25:04 -07002627 /*
2628 * transparentRegion: area of a surface that is hinted to be completely
2629 * transparent. This is only used to tell when the layer has no visible
2630 * non-transparent regions and can be removed from the layer list. It
2631 * does not affect the visibleRegion of this layer or any layers
2632 * beneath it. The hint may not be correct if apps don't respect the
2633 * SurfaceView restrictions (which, sadly, some don't).
2634 */
2635 Region transparentRegion;
2636
Mathias Agopianab028732010-03-16 16:41:46 -07002637
2638 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002639 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002640 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002641 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002642 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002643 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002644 if (!visibleRegion.isEmpty()) {
2645 // Remove the transparent area from the visible region
2646 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002647 if (tr.preserveRects()) {
2648 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002649 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002650 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002651 // transformation too complex, can't do the
2652 // transparent region optimization.
2653 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002654 }
Mathias Agopianab028732010-03-16 16:41:46 -07002655 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002656
Mathias Agopianab028732010-03-16 16:41:46 -07002657 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002658 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002659 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002660 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2661 // the opaque region is the layer's footprint
2662 opaqueRegion = visibleRegion;
2663 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002664 }
2665 }
2666
Robert Carre5f4f692018-01-12 13:12:28 -08002667 if (visibleRegion.isEmpty()) {
2668 layer->clearVisibilityRegions();
2669 return;
2670 }
2671
Mathias Agopianab028732010-03-16 16:41:46 -07002672 // Clip the covered region to the visible region
2673 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2674
2675 // Update aboveCoveredLayers for next (lower) layer
2676 aboveCoveredLayers.orSelf(visibleRegion);
2677
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002678 // subtract the opaque region covered by the layers above us
2679 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002680
2681 // compute this layer's dirty region
2682 if (layer->contentDirty) {
2683 // we need to invalidate the whole region
2684 dirty = visibleRegion;
2685 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002686 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002687 layer->contentDirty = false;
2688 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002689 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002690 * the exposed region consists of two components:
2691 * 1) what's VISIBLE now and was COVERED before
2692 * 2) what's EXPOSED now less what was EXPOSED before
2693 *
2694 * note that (1) is conservative, we start with the whole
2695 * visible region but only keep what used to be covered by
2696 * something -- which mean it may have been exposed.
2697 *
2698 * (2) handles areas that were not covered by anything but got
2699 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002700 */
Mathias Agopianab028732010-03-16 16:41:46 -07002701 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002702 const Region oldVisibleRegion = layer->visibleRegion;
2703 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002704 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2705 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002706 }
2707 dirty.subtractSelf(aboveOpaqueLayers);
2708
2709 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002710 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002711
Mathias Agopianab028732010-03-16 16:41:46 -07002712 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002713 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002714
Jesse Halla8026d22012-09-25 13:25:04 -07002715 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002716 layer->setVisibleRegion(visibleRegion);
2717 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002718 layer->setVisibleNonTransparentRegion(
2719 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002720 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002721
Mathias Agopian87baae12012-07-31 12:38:26 -07002722 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002723}
2724
Chia-I Wuab0c3192017-08-01 11:29:00 -07002725void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002726 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002727 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2728 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002729 }
2730 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002731}
2732
Dan Stoza6b9454d2014-11-07 16:00:59 -08002733bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002734{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002735 ALOGV("handlePageFlip");
2736
Brian Andersond6927fb2016-07-23 23:37:30 -07002737 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002738
Mathias Agopian4fec8732012-06-29 14:12:52 -07002739 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002740 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002741 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002742
2743 // Store the set of layers that need updates. This set must not change as
2744 // buffers are being latched, as this could result in a deadlock.
2745 // Example: Two producers share the same command stream and:
2746 // 1.) Layer 0 is latched
2747 // 2.) Layer 0 gets a new frame
2748 // 2.) Layer 1 gets a new frame
2749 // 3.) Layer 1 is latched.
2750 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2751 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002752 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002753 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002754 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07002755 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002756 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002757 } else {
2758 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002759 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002760 } else {
2761 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002762 }
Robert Carr2047fae2016-11-28 14:09:09 -08002763 });
2764
Dan Stoza9e56aa02015-11-02 13:00:03 -08002765 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002766 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002767 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002768 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002769 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002770 newDataLatched = true;
2771 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002772 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002773
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002774 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002775
2776 // If we will need to wake up at some time in the future to deal with a
2777 // queued frame that shouldn't be displayed during this vsync period, wake
2778 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002779 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002780 signalLayerUpdate();
2781 }
2782
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002783 // enter boot animation on first buffer latch
2784 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2785 ALOGI("Enter boot animation");
2786 mBootStage = BootStage::BOOTANIMATION;
2787 }
2788
Dan Stoza6b9454d2014-11-07 16:00:59 -08002789 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002790 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002791}
2792
Mathias Agopianad456f92011-01-13 17:53:01 -08002793void SurfaceFlinger::invalidateHwcGeometry()
2794{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002795 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002796}
2797
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002798void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2799 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002800 // We only need to actually compose the display if:
2801 // 1) It is being handled by hardware composer, which may need this to
2802 // keep its virtual display state machine in sync, or
2803 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002804 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002805 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002806 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002807 return;
2808 }
2809
Dan Stoza9e56aa02015-11-02 13:00:03 -08002810 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002811 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002812
2813 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002814 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002815}
2816
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002817bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002818 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002819
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002820 const Region bounds(display->bounds());
2821 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002822 const auto displayId = display->getId();
2823 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002824 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002825
Chia-I Wu8e50e692018-05-04 10:12:37 -07002826 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002827 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002828
Dan Stoza9e56aa02015-11-02 13:00:03 -08002829 if (hasClientComposition) {
2830 ALOGV("hasClientComposition");
2831
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002832 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002833 if (display->hasWideColorGamut()) {
2834 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002835 }
2836 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002837 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002838 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002839
Dominik Laskowski7e045462018-05-30 13:02:02 -07002840 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002841 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2842 HWC2::Capability::SkipClientColorTransform);
2843
Chia-I Wud49d6692018-06-27 07:17:41 +08002844 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002845 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2846 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08002847 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002848 }
2849
Chia-I Wud49d6692018-06-27 07:17:41 +08002850 // The current enhanced saturation matrix is designed to enhance Display P3,
2851 // thus we only apply this matrix when the render intent is not colorimetric
2852 // and the output color space is Display P3.
2853 needsEnhancedColorMatrix =
2854 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2855 outputDataspace == Dataspace::DISPLAY_P3);
2856 if (needsEnhancedColorMatrix) {
2857 colorMatrix *= mEnhancedSaturationMatrix;
2858 }
2859
2860 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002861
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002862 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002863 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002864 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002865 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002866
2867 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002868 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
2869 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
2870 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07002871 }
2872 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002873 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002874
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002875 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002876 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002877 // when using overlays, we assume a fully transparent framebuffer
2878 // NOTE: we could reduce how much we need to clear, for instance
2879 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002880 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002881 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002882 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002883 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002884 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002885 // we're left with the letterbox region
2886 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002887 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07002888
2889 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002890 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07002891
Mathias Agopianb9494d52012-04-18 02:28:45 -07002892 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002893 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002894 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002895 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002896 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002897 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002898
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002899 if (!display->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002900 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002901 // scissor on the main display. It should never be needed
2902 // anyways (though in theory it could since the API allows it).
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002903 const Rect& bounds = display->getBounds();
2904 const Rect& scissor = display->getScissor();
Mathias Agopianf45c5102012-10-24 16:29:17 -07002905 if (scissor != bounds) {
2906 // scissor doesn't match the screen's dimensions, so we
2907 // need to clear everything outside of it and enable
2908 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002909
Mathias Agopianf45c5102012-10-24 16:29:17 -07002910 // enable scissor for this frame
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002911 const uint32_t height = display->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08002912 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002913 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002914 }
2915 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002916 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002917
Mathias Agopian85d751c2012-08-29 16:59:24 -07002918 /*
2919 * and then, render the layers targeted at the framebuffer
2920 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002921
Dan Stoza9e56aa02015-11-02 13:00:03 -08002922 ALOGV("Rendering client layers");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002923 const Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002924 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002925 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002926 const Region clip(bounds.intersect(
2927 displayTransform.transform(layer->visibleRegion)));
2928 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002929 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002930 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002931 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002932 case HWC2::Composition::Cursor:
2933 case HWC2::Composition::Device:
2934 case HWC2::Composition::Sideband:
2935 case HWC2::Composition::SolidColor: {
2936 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002937 if (layer->getClearClientTarget(displayId) && !firstLayer &&
Rajavenu Kyatham2eae6d32018-04-10 12:34:05 +05302938 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
2939 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002940 // never clear the very first layer since we're
2941 // guaranteed the FB is already cleared
2942 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002943 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002944 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002945 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002946 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002947 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002948 break;
2949 }
2950 default:
2951 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002952 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002953 } else {
2954 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002955 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002956 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002957 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002958
Chia-I Wud49d6692018-06-27 07:17:41 +08002959 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07002960 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002961 }
2962
Mathias Agopianf45c5102012-10-24 16:29:17 -07002963 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002964 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002965 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002966}
2967
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002968void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
2969 const Region& region) const {
2970 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002971 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002972 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002973}
2974
Dan Stoza7d89d062015-04-30 13:29:25 -07002975status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002976 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002977 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002978 const sp<Layer>& lbc,
2979 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002980{
Dan Stoza7d89d062015-04-30 13:29:25 -07002981 // add this layer to the current state list
2982 {
2983 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002984 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002985 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2986 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002987 return NO_MEMORY;
2988 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002989 if (parent == nullptr) {
2990 mCurrentState.layersSortedByZ.add(lbc);
2991 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08002992 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002993 ALOGE("addClientLayer called with a removed parent");
2994 return NAME_NOT_FOUND;
2995 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002996 parent->addChild(lbc);
2997 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002998
Yiwei Zhang243b3782018-05-15 17:40:04 -07002999 if (gbc != nullptr) {
3000 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3001 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3002 mMaxGraphicBufferProducerListSize,
3003 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3004 mGraphicBufferProducerList.size(),
3005 mMaxGraphicBufferProducerListSize, mNumLayers);
3006 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003007 mLayersAdded = true;
3008 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003009 }
3010
Mathias Agopian96f08192010-06-02 23:28:45 -07003011 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003012 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003013
Dan Stoza7d89d062015-04-30 13:29:25 -07003014 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003015}
3016
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003017status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003018 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003019 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3020}
Robert Carr7f9b8992017-03-10 11:08:39 -08003021
chaviwca27f252018-02-06 16:46:39 -08003022status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3023 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003024 if (layer->isPendingRemoval()) {
3025 return NO_ERROR;
3026 }
3027
Robert Carr1f0a16a2016-10-24 16:27:39 -07003028 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003029 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003030 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003031 if (topLevelOnly) {
3032 return NO_ERROR;
3033 }
3034
Chia-I Wu98f1c102017-05-30 14:54:08 -07003035 sp<Layer> ancestor = p;
3036 while (ancestor->getParent() != nullptr) {
3037 ancestor = ancestor->getParent();
3038 }
3039 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3040 ALOGE("removeLayer called with a layer whose parent has been removed");
3041 return NAME_NOT_FOUND;
3042 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003043
3044 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003045 } else {
3046 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003047 }
3048
Robert Carr136e2f62017-02-08 17:54:29 -08003049 // As a matter of normal operation, the LayerCleaner will produce a second
3050 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3051 // so we will succeed in promoting it, but it's already been removed
3052 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3053 // otherwise something has gone wrong and we are leaking the layer.
3054 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003055 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3056 layer->getName().string(),
3057 (p != nullptr) ? p->getName().string() : "no-parent");
3058 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003059 } else if (index < 0) {
3060 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003061 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003062
Chia-I Wuc6657022017-08-15 11:18:17 -07003063 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003064 mLayersPendingRemoval.add(layer);
3065 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003066 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003067 setTransactionFlags(eTransactionNeeded);
3068 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003069}
3070
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003071uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003072 return android_atomic_release_load(&mTransactionFlags);
3073}
3074
Mathias Agopian3f844832013-08-07 21:24:32 -07003075uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003076 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3077}
3078
Mathias Agopian3f844832013-08-07 21:24:32 -07003079uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003080 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3081}
3082
3083uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3084 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003085 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003086 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003087 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003088 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003089 }
3090 return old;
3091}
3092
chaviwca27f252018-02-06 16:46:39 -08003093bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3094 for (const ComposerState& state : states) {
3095 // Here we need to check that the interface we're given is indeed
3096 // one of our own. A malicious client could give us a nullptr
3097 // IInterface, or one of its own or even one of our own but a
3098 // different type. All these situations would cause us to crash.
3099 if (state.client == nullptr) {
3100 return true;
3101 }
3102
3103 sp<IBinder> binder = IInterface::asBinder(state.client);
3104 if (binder == nullptr) {
3105 return true;
3106 }
3107
3108 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3109 return true;
3110 }
3111 }
3112 return false;
3113}
3114
Mathias Agopian8b33f032012-07-24 20:43:54 -07003115void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003116 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003117 const Vector<DisplayState>& displays,
3118 uint32_t flags)
3119{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003120 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003121 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003122 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003123
chaviwca27f252018-02-06 16:46:39 -08003124 if (containsAnyInvalidClientState(states)) {
3125 return;
3126 }
3127
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003128 if (flags & eAnimation) {
3129 // For window updates that are part of an animation we must wait for
3130 // previous animation "frames" to be handled.
3131 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003132 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003133 if (CC_UNLIKELY(err != NO_ERROR)) {
3134 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003135 // caller after a few seconds.
3136 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3137 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003138 mAnimTransactionPending = false;
3139 break;
3140 }
3141 }
3142 }
3143
chaviwca27f252018-02-06 16:46:39 -08003144 for (const DisplayState& display : displays) {
3145 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003146 }
3147
chaviwca27f252018-02-06 16:46:39 -08003148 for (const ComposerState& state : states) {
3149 transactionFlags |= setClientStateLocked(state);
3150 }
3151
3152 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3153 // as destroyed should only occur after setting all other states. This is to allow for a
3154 // child re-parent to happen before marking its original parent as destroyed (which would
3155 // then mark the child as destroyed).
3156 for (const ComposerState& state : states) {
3157 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003158 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003159
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003160 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3161 // anyway. This can be used as a flush mechanism for previous async transactions.
3162 // Empty animation transaction can be used to simulate back-pressure, so also force a
3163 // transaction for empty animation transactions.
3164 if (transactionFlags == 0 &&
3165 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003166 transactionFlags = eTransactionNeeded;
3167 }
3168
Mathias Agopian386aa982011-11-07 21:58:03 -08003169 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003170 if (mInterceptor->isEnabled()) {
3171 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003172 }
Irvel468051e2016-06-13 16:44:44 -07003173
Mathias Agopian386aa982011-11-07 21:58:03 -08003174 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003175 const auto start = (flags & eEarlyWakeup)
3176 ? VSyncModulator::TransactionStart::EARLY
3177 : VSyncModulator::TransactionStart::NORMAL;
3178 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003179
3180 // if this is a synchronous transaction, wait for it to take effect
3181 // before returning.
3182 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003183 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003184 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003185 if (flags & eAnimation) {
3186 mAnimTransactionPending = true;
3187 }
3188 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003189 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3190 if (CC_UNLIKELY(err != NO_ERROR)) {
3191 // just in case something goes wrong in SF, return to the
3192 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003193 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3194 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003195 break;
3196 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003197 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003198 }
3199}
3200
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003201uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3202 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3203 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003204
Mathias Agopiane57f2922012-08-09 16:29:12 -07003205 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003206 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3207
3208 const uint32_t what = s.what;
3209 if (what & DisplayState::eSurfaceChanged) {
3210 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3211 state.surface = s.surface;
3212 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003213 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003214 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003215 if (what & DisplayState::eLayerStackChanged) {
3216 if (state.layerStack != s.layerStack) {
3217 state.layerStack = s.layerStack;
3218 flags |= eDisplayTransactionNeeded;
3219 }
3220 }
3221 if (what & DisplayState::eDisplayProjectionChanged) {
3222 if (state.orientation != s.orientation) {
3223 state.orientation = s.orientation;
3224 flags |= eDisplayTransactionNeeded;
3225 }
3226 if (state.frame != s.frame) {
3227 state.frame = s.frame;
3228 flags |= eDisplayTransactionNeeded;
3229 }
3230 if (state.viewport != s.viewport) {
3231 state.viewport = s.viewport;
3232 flags |= eDisplayTransactionNeeded;
3233 }
3234 }
3235 if (what & DisplayState::eDisplaySizeChanged) {
3236 if (state.width != s.width) {
3237 state.width = s.width;
3238 flags |= eDisplayTransactionNeeded;
3239 }
3240 if (state.height != s.height) {
3241 state.height = s.height;
3242 flags |= eDisplayTransactionNeeded;
3243 }
3244 }
3245
Mathias Agopiane57f2922012-08-09 16:29:12 -07003246 return flags;
3247}
3248
Robert Carrd4ae7f32018-06-07 16:10:57 -07003249bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3250 IPCThreadState* ipc = IPCThreadState::self();
3251 const int pid = ipc->getCallingPid();
3252 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003253 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulecfbe2c002018-08-09 22:32:45 +00003254 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003255 return false;
3256 }
3257 return true;
3258}
3259
chaviwca27f252018-02-06 16:46:39 -08003260uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3261 const layer_state_t& s = composerState.state;
3262 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3263
Mathias Agopian13127d82013-03-05 17:47:11 -08003264 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003265 if (layer == nullptr) {
3266 return 0;
3267 }
3268
3269 if (layer->isPendingRemoval()) {
3270 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3271 return 0;
3272 }
3273
3274 uint32_t flags = 0;
3275
3276 const uint32_t what = s.what;
3277 bool geometryAppliesWithResize =
3278 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003279
3280 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3281 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003282 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003283 layer->pushPendingState();
3284 }
3285
chaviw8b3871a2017-11-01 17:41:01 -07003286 if (what & layer_state_t::ePositionChanged) {
3287 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3288 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003289 }
chaviw8b3871a2017-11-01 17:41:01 -07003290 }
3291 if (what & layer_state_t::eLayerChanged) {
3292 // NOTE: index needs to be calculated before we update the state
3293 const auto& p = layer->getParent();
3294 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003295 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003296 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003297 mCurrentState.layersSortedByZ.removeAt(idx);
3298 mCurrentState.layersSortedByZ.add(layer);
3299 // we need traversal (state changed)
3300 // AND transaction (list changed)
3301 flags |= eTransactionNeeded|eTraversalNeeded;
3302 }
chaviw8b3871a2017-11-01 17:41:01 -07003303 } else {
3304 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003305 flags |= eTransactionNeeded|eTraversalNeeded;
3306 }
3307 }
chaviw8b3871a2017-11-01 17:41:01 -07003308 }
3309 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003310 // NOTE: index needs to be calculated before we update the state
3311 const auto& p = layer->getParent();
3312 if (p == nullptr) {
3313 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3314 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3315 mCurrentState.layersSortedByZ.removeAt(idx);
3316 mCurrentState.layersSortedByZ.add(layer);
3317 // we need traversal (state changed)
3318 // AND transaction (list changed)
3319 flags |= eTransactionNeeded|eTraversalNeeded;
3320 }
3321 } else {
3322 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3323 flags |= eTransactionNeeded|eTraversalNeeded;
3324 }
chaviw8b3871a2017-11-01 17:41:01 -07003325 }
3326 }
3327 if (what & layer_state_t::eSizeChanged) {
3328 if (layer->setSize(s.w, s.h)) {
3329 flags |= eTraversalNeeded;
3330 }
3331 }
3332 if (what & layer_state_t::eAlphaChanged) {
3333 if (layer->setAlpha(s.alpha))
3334 flags |= eTraversalNeeded;
3335 }
3336 if (what & layer_state_t::eColorChanged) {
3337 if (layer->setColor(s.color))
3338 flags |= eTraversalNeeded;
3339 }
3340 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003341 // TODO: b/109894387
3342 //
3343 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3344 // rotation. To see the problem observe that if we have a square parent, and a child
3345 // of the same size, then we rotate the child 45 degrees around it's center, the child
3346 // must now be cropped to a non rectangular 8 sided region.
3347 //
3348 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3349 // private API, and the WindowManager only uses rotation in one case, which is on a top
3350 // level layer in which cropping is not an issue.
3351 //
3352 // However given that abuse of rotation matrices could lead to surfaces extending outside
3353 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3354 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3355 // transformations.
3356 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003357 flags |= eTraversalNeeded;
3358 }
3359 if (what & layer_state_t::eTransparentRegionChanged) {
3360 if (layer->setTransparentRegionHint(s.transparentRegion))
3361 flags |= eTraversalNeeded;
3362 }
3363 if (what & layer_state_t::eFlagsChanged) {
3364 if (layer->setFlags(s.flags, s.mask))
3365 flags |= eTraversalNeeded;
3366 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003367 if (what & layer_state_t::eCropChanged_legacy) {
3368 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003369 flags |= eTraversalNeeded;
3370 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003371 if (what & layer_state_t::eFinalCropChanged_legacy) {
3372 if (layer->setFinalCrop_legacy(s.finalCrop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003373 flags |= eTraversalNeeded;
3374 }
3375 if (what & layer_state_t::eLayerStackChanged) {
3376 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3377 // We only allow setting layer stacks for top level layers,
3378 // everything else inherits layer stack from its parent.
3379 if (layer->hasParent()) {
3380 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3381 layer->getName().string());
3382 } else if (idx < 0) {
3383 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3384 "that also does not appear in the top level layer list. Something"
3385 " has gone wrong.", layer->getName().string());
3386 } else if (layer->setLayerStack(s.layerStack)) {
3387 mCurrentState.layersSortedByZ.removeAt(idx);
3388 mCurrentState.layersSortedByZ.add(layer);
3389 // we need traversal (state changed)
3390 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003391 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003392 }
3393 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003394 if (what & layer_state_t::eDeferTransaction_legacy) {
3395 if (s.barrierHandle_legacy != nullptr) {
3396 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3397 } else if (s.barrierGbp_legacy != nullptr) {
3398 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003399 if (authenticateSurfaceTextureLocked(gbp)) {
3400 const auto& otherLayer =
3401 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003402 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003403 } else {
3404 ALOGE("Attempt to defer transaction to to an"
3405 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003406 }
3407 }
chaviw8b3871a2017-11-01 17:41:01 -07003408 // We don't trigger a traversal here because if no other state is
3409 // changed, we don't want this to cause any more work
3410 }
3411 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003412 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003413 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003414 if (!hadParent) {
3415 mCurrentState.layersSortedByZ.remove(layer);
3416 }
chaviw8b3871a2017-11-01 17:41:01 -07003417 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003418 }
chaviw8b3871a2017-11-01 17:41:01 -07003419 }
3420 if (what & layer_state_t::eReparentChildren) {
3421 if (layer->reparentChildren(s.reparentHandle)) {
3422 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003423 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003424 }
chaviw8b3871a2017-11-01 17:41:01 -07003425 if (what & layer_state_t::eDetachChildren) {
3426 layer->detachChildren();
3427 }
3428 if (what & layer_state_t::eOverrideScalingModeChanged) {
3429 layer->setOverrideScalingMode(s.overrideScalingMode);
3430 // We don't trigger a traversal here because if no other state is
3431 // changed, we don't want this to cause any more work
3432 }
Marissa Wall61c58622018-07-18 10:12:20 -07003433 if (what & layer_state_t::eTransformChanged) {
3434 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3435 }
3436 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3437 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3438 flags |= eTraversalNeeded;
3439 }
3440 if (what & layer_state_t::eCropChanged) {
3441 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3442 }
3443 if (what & layer_state_t::eBufferChanged) {
3444 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3445 }
3446 if (what & layer_state_t::eAcquireFenceChanged) {
3447 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3448 }
3449 if (what & layer_state_t::eDataspaceChanged) {
3450 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3451 }
3452 if (what & layer_state_t::eHdrMetadataChanged) {
3453 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3454 }
3455 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3456 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3457 }
3458 if (what & layer_state_t::eApiChanged) {
3459 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3460 }
3461 if (what & layer_state_t::eSidebandStreamChanged) {
3462 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3463 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003464 return flags;
3465}
3466
chaviwca27f252018-02-06 16:46:39 -08003467void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3468 const layer_state_t& state = composerState.state;
3469 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3470
3471 sp<Layer> layer(client->getLayerUser(state.surface));
3472 if (layer == nullptr) {
3473 return;
3474 }
3475
3476 if (layer->isPendingRemoval()) {
3477 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3478 return;
3479 }
3480
3481 if (state.what & layer_state_t::eDestroySurface) {
3482 removeLayerLocked(mStateLock, layer);
3483 }
3484}
3485
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003486status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003487 const String8& name,
3488 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003489 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003490 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003491 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003492{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003493 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003494 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003495 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003496 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003497 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003498
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003499 status_t result = NO_ERROR;
3500
3501 sp<Layer> layer;
3502
Cody Northropbc755282017-03-31 12:00:08 -06003503 String8 uniqueName = getUniqueLayerName(name);
3504
Mathias Agopian3165cc22012-08-08 19:42:09 -07003505 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003506 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003507 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3508 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003509
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003510 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003511 case ISurfaceComposerClient::eFXSurfaceBufferState:
3512 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3513 break;
chaviw13fdc492017-06-27 12:40:18 -07003514 case ISurfaceComposerClient::eFXSurfaceColor:
3515 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003516 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003517 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003518 break;
3519 default:
3520 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003521 break;
3522 }
3523
Dan Stoza7d89d062015-04-30 13:29:25 -07003524 if (result != NO_ERROR) {
3525 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003526 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003527
Chia-I Wuab0c3192017-08-01 11:29:00 -07003528 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3529 // TODO b/64227542
3530 if (windowType == 441731) {
3531 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3532 layer->setPrimaryDisplayOnly();
3533 }
3534
Albert Chaulk479c60c2017-01-27 14:21:34 -05003535 layer->setInfo(windowType, ownerUid);
3536
Robert Carr1f0a16a2016-10-24 16:27:39 -07003537 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003538 if (result != NO_ERROR) {
3539 return result;
3540 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003541 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003542
3543 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003544 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003545}
3546
Cody Northropbc755282017-03-31 12:00:08 -06003547String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3548{
3549 bool matchFound = true;
3550 uint32_t dupeCounter = 0;
3551
3552 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3553 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3554
Dan Stoza436ccf32018-06-21 12:10:12 -07003555 // Grab the state lock since we're accessing mCurrentState
3556 Mutex::Autolock lock(mStateLock);
3557
Cody Northropbc755282017-03-31 12:00:08 -06003558 // Loop over layers until we're sure there is no matching name
3559 while (matchFound) {
3560 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003561 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003562 if (layer->getName() == uniqueName) {
3563 matchFound = true;
3564 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3565 }
3566 });
3567 }
3568
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003569 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3570 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003571
3572 return uniqueName;
3573}
3574
Marissa Wallfd668622018-05-10 10:21:13 -07003575status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3576 uint32_t w, uint32_t h, uint32_t flags,
3577 PixelFormat& format, sp<IBinder>* handle,
3578 sp<IGraphicBufferProducer>* gbp,
3579 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003580 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003581 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003582 case PIXEL_FORMAT_TRANSPARENT:
3583 case PIXEL_FORMAT_TRANSLUCENT:
3584 format = PIXEL_FORMAT_RGBA_8888;
3585 break;
3586 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003587 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003588 break;
3589 }
3590
Marissa Wallfd668622018-05-10 10:21:13 -07003591 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3592 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003593 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003594 *handle = layer->getHandle();
3595 *gbp = layer->getProducer();
3596 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003597 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003598
Marissa Wallfd668622018-05-10 10:21:13 -07003599 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003600 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003601}
3602
Marissa Wall61c58622018-07-18 10:12:20 -07003603status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3604 uint32_t w, uint32_t h, uint32_t flags,
3605 sp<IBinder>* handle, sp<Layer>* outLayer) {
3606 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3607 *handle = layer->getHandle();
3608 *outLayer = layer;
3609
3610 return NO_ERROR;
3611}
3612
chaviw13fdc492017-06-27 12:40:18 -07003613status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003614 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003615 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003616{
chaviw13fdc492017-06-27 12:40:18 -07003617 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003618 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003619 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003620}
3621
Mathias Agopianac9fa422013-02-11 16:40:36 -08003622status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003623{
Robert Carr9524cb32017-02-13 11:32:32 -08003624 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003625 status_t err = NO_ERROR;
3626 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003627 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003628 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003629 err = removeLayer(l);
3630 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3631 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003632 }
3633 return err;
3634}
3635
Mathias Agopian13127d82013-03-05 17:47:11 -08003636status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003637{
Mathias Agopian67106042013-03-14 19:18:13 -07003638 // called by ~LayerCleaner() when all references to the IBinder (handle)
3639 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003640 sp<Layer> l = layer.promote();
3641 if (l == nullptr) {
3642 // The layer has already been removed, carry on
3643 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003644 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003645 // If we have a parent, then we can continue to live as long as it does.
3646 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003647}
3648
Mathias Agopianb60314a2012-04-10 22:09:54 -07003649// ---------------------------------------------------------------------------
3650
Andy McFadden13a082e2012-08-24 10:16:42 -07003651void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003652 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3653 if (!displayToken) return;
3654
Jesse Hall01e29052013-02-19 16:13:35 -08003655 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003656 Vector<ComposerState> state;
3657 Vector<DisplayState> displays;
3658 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003659 d.what = DisplayState::eDisplayProjectionChanged |
3660 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003661 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003662 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003663 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003664 d.frame.makeInvalid();
3665 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003666 d.width = 0;
3667 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003668 displays.add(d);
3669 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003670
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003671 const auto display = getDisplayDevice(displayToken);
3672 if (!display) return;
3673
3674 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3675
3676 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003677 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003678 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003679
Brian Andersond0010582017-03-07 13:20:31 -08003680 // Use phase of 0 since phase is not known.
3681 // Use latency of 0, which will snap to the ideal latency.
3682 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003683}
3684
3685void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003686 // Async since we may be called from the main thread.
3687 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003688}
3689
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003690void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3691 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003692 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003693 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003694
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003695 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003696 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003697 return;
3698 }
3699
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003700 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003701 ALOGW("Trying to set power mode for virtual display");
3702 return;
3703 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003704
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003705 display->setPowerMode(mode);
3706
Lloyd Pique4dccc412018-01-22 17:21:36 -08003707 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003708 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003709 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003710 if (idx < 0) {
3711 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3712 return;
3713 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003714 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003715 }
3716
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003717 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003718 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003719 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003720 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003721 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003722 // FIXME: eventthread only knows about the main display right now
3723 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003724 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003725 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003726
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003727 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003728 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003729 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003730
3731 struct sched_param param = {0};
3732 param.sched_priority = 1;
3733 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3734 ALOGW("Couldn't set SCHED_FIFO on display on");
3735 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003736 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003737 // Turn off the display
3738 struct sched_param param = {0};
3739 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3740 ALOGW("Couldn't set SCHED_OTHER on display off");
3741 }
3742
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003743 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003744 disableHardwareVsync(true); // also cancels any in-progress resync
3745
Mathias Agopiancde87a32012-09-13 14:09:01 -07003746 // FIXME: eventthread only knows about the main display right now
3747 mEventThread->onScreenReleased();
3748 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003749
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003750 getHwComposer().setPowerMode(type, mode);
3751 mVisibleRegionsDirty = true;
3752 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003753 } else if (mode == HWC_POWER_MODE_DOZE ||
3754 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003755 // Update display while dozing
3756 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003757 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003758 // FIXME: eventthread only knows about the main display right now
3759 mEventThread->onScreenAcquired();
3760 resyncToHardwareVsync(true);
3761 }
3762 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3763 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003764 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003765 disableHardwareVsync(true); // also cancels any in-progress resync
3766 // FIXME: eventthread only knows about the main display right now
3767 mEventThread->onScreenReleased();
3768 }
3769 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003770 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003771 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003772 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003773 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003774
3775 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003776}
3777
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003778void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003779 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003780 const auto display = getDisplayDevice(displayToken);
3781 if (!display) {
3782 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3783 displayToken.get());
3784 } else if (display->isVirtual()) {
3785 ALOGW("Attempt to set power mode %d for virtual display", mode);
3786 } else {
3787 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003788 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003789 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003790}
3791
3792// ---------------------------------------------------------------------------
3793
Lloyd Pique755e3192018-01-31 16:46:15 -08003794status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3795 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003796 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003797
Mathias Agopianbd115332013-04-18 16:41:04 -07003798 IPCThreadState* ipc = IPCThreadState::self();
3799 const int pid = ipc->getCallingPid();
3800 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003801
Mathias Agopianbd115332013-04-18 16:41:04 -07003802 if ((uid != AID_SHELL) &&
3803 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003804 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003805 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003806 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003807 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003808 // (this would indicate SF is stuck, but we want to be able to
3809 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003810 status_t err = mStateLock.timedLock(s2ns(1));
3811 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003812 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003813 result.appendFormat(
3814 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3815 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003816 }
3817
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003818 bool dumpAll = true;
3819 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003820 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003821
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003822 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003823 if ((index < numArgs) &&
3824 (args[index] == String16("--list"))) {
3825 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003826 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003827 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003828 }
3829
3830 if ((index < numArgs) &&
3831 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003832 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003833 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003834 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003835 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003836
3837 if ((index < numArgs) &&
3838 (args[index] == String16("--latency-clear"))) {
3839 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003840 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003841 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003842 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003843
3844 if ((index < numArgs) &&
3845 (args[index] == String16("--dispsync"))) {
3846 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07003847 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07003848 dumpAll = false;
3849 }
Dan Stozab90cf072015-03-05 11:05:59 -08003850
3851 if ((index < numArgs) &&
3852 (args[index] == String16("--static-screen"))) {
3853 index++;
3854 dumpStaticScreenStats(result);
3855 dumpAll = false;
3856 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003857
3858 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003859 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003860 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003861 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003862 dumpAll = false;
3863 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003864
3865 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3866 index++;
3867 dumpWideColorInfo(result);
3868 dumpAll = false;
3869 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003870
3871 if ((index < numArgs) &&
3872 (args[index] == String16("--enable-layer-stats"))) {
3873 index++;
3874 mLayerStats.enable();
3875 dumpAll = false;
3876 }
3877
3878 if ((index < numArgs) &&
3879 (args[index] == String16("--disable-layer-stats"))) {
3880 index++;
3881 mLayerStats.disable();
3882 dumpAll = false;
3883 }
3884
3885 if ((index < numArgs) &&
3886 (args[index] == String16("--clear-layer-stats"))) {
3887 index++;
3888 mLayerStats.clear();
3889 dumpAll = false;
3890 }
3891
3892 if ((index < numArgs) &&
3893 (args[index] == String16("--dump-layer-stats"))) {
3894 index++;
3895 mLayerStats.dump(result);
3896 dumpAll = false;
3897 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003898
3899 if ((index < numArgs) &&
3900 (args[index] == String16("--display-identification"))) {
3901 index++;
3902 dumpDisplayIdentificationData(result);
3903 dumpAll = false;
3904 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003905
3906 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3907 index++;
3908 mTimeStats.parseArgs(asProto, args, index, result);
3909 dumpAll = false;
3910 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003911 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003912
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003913 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003914 if (asProto) {
3915 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3916 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3917 } else {
3918 dumpAllLocked(args, index, result);
3919 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003920 }
3921
Mathias Agopian9795c422009-08-26 16:36:26 -07003922 if (locked) {
3923 mStateLock.unlock();
3924 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003925 }
3926 write(fd, result.string(), result.size());
3927 return NO_ERROR;
3928}
3929
Dan Stozac7014012014-02-14 15:03:43 -08003930void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3931 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003932{
Robert Carr2047fae2016-11-28 14:09:09 -08003933 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003934 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003935 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003936}
3937
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003938void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003939 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003940{
3941 String8 name;
3942 if (index < args.size()) {
3943 name = String8(args[index]);
3944 index++;
3945 }
3946
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003947 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
3948 getHwComposer().isConnected(displayId)) {
3949 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
3950 const nsecs_t period = activeConfig->getVsyncPeriod();
3951 result.appendFormat("%" PRId64 "\n", period);
3952 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003953
3954 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003955 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003956 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003957 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003958 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003959 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003960 }
Robert Carr2047fae2016-11-28 14:09:09 -08003961 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003962 }
3963}
3964
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003965void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003966 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003967{
3968 String8 name;
3969 if (index < args.size()) {
3970 name = String8(args[index]);
3971 index++;
3972 }
3973
Robert Carr2047fae2016-11-28 14:09:09 -08003974 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003975 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003976 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003977 }
Robert Carr2047fae2016-11-28 14:09:09 -08003978 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003979
Svetoslavd85084b2014-03-20 10:28:31 -07003980 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003981}
3982
Jamie Gennis6547ff42013-07-16 20:12:42 -07003983// This should only be called from the main thread. Otherwise it would need
3984// the lock and should use mCurrentState rather than mDrawingState.
3985void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003986 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003987 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003988 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003989
3990 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3991}
3992
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003993void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003994{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003995 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003996
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003997 if (isLayerTripleBufferingDisabled())
3998 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003999
4000 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004001 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004002 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004003 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004004 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4005 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004006 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004007}
4008
Dan Stozab90cf072015-03-05 11:05:59 -08004009void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4010{
4011 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004012 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4013 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004014 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004015 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004016 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4017 b + 1, bucketTimeSec, percent);
4018 }
David Sodman4a36e932017-11-07 14:29:47 -08004019 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004020 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004021 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004022 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004023 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004024}
4025
Dan Stozae77c7662016-05-13 11:37:28 -07004026void SurfaceFlinger::recordBufferingStats(const char* layerName,
4027 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004028 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4029 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004030 for (const auto& segment : history) {
4031 if (!segment.usedThirdBuffer) {
4032 stats.twoBufferTime += segment.totalTime;
4033 }
4034 if (segment.occupancyAverage < 1.0f) {
4035 stats.doubleBufferedTime += segment.totalTime;
4036 } else if (segment.occupancyAverage < 2.0f) {
4037 stats.tripleBufferedTime += segment.totalTime;
4038 }
4039 ++stats.numSegments;
4040 stats.totalTime += segment.totalTime;
4041 }
4042}
4043
Brian Andersond6927fb2016-07-23 23:37:30 -07004044void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4045 result.appendFormat("Layer frame timestamps:\n");
4046
4047 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4048 const size_t count = currentLayers.size();
4049 for (size_t i=0 ; i<count ; i++) {
4050 currentLayers[i]->dumpFrameEvents(result);
4051 }
4052}
4053
Dan Stozae77c7662016-05-13 11:37:28 -07004054void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4055 result.append("Buffering stats:\n");
4056 result.append(" [Layer name] <Active time> <Two buffer> "
4057 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004058 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004059 typedef std::tuple<std::string, float, float, float> BufferTuple;
4060 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004061 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004062 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004063 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004064 if (stats.numSegments == 0) {
4065 continue;
4066 }
4067 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4068 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4069 stats.totalTime;
4070 float doubleBufferRatio = static_cast<float>(
4071 stats.doubleBufferedTime) / stats.totalTime;
4072 float tripleBufferRatio = static_cast<float>(
4073 stats.tripleBufferedTime) / stats.totalTime;
4074 sorted.insert({activeTime, {name, twoBufferRatio,
4075 doubleBufferRatio, tripleBufferRatio}});
4076 }
4077 for (const auto& sortedPair : sorted) {
4078 float activeTime = sortedPair.first;
4079 const BufferTuple& values = sortedPair.second;
4080 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4081 std::get<0>(values).c_str(), activeTime,
4082 std::get<1>(values), std::get<2>(values),
4083 std::get<3>(values));
4084 }
4085 result.append("\n");
4086}
4087
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004088void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004089 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004090 const int32_t displayId = display->getId();
4091 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4092 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004093 continue;
4094 }
4095
Dominik Laskowski7e045462018-05-30 13:02:02 -07004096 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004097 uint8_t port;
4098 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004099 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004100 result.append("no identification data\n");
4101 continue;
4102 }
4103
4104 if (!isEdid(data)) {
4105 result.append("unknown identification data: ");
4106 for (uint8_t byte : data) {
4107 result.appendFormat("%x ", byte);
4108 }
4109 result.append("\n");
4110 continue;
4111 }
4112
4113 const auto edid = parseEdid(data);
4114 if (!edid) {
4115 result.append("invalid EDID: ");
4116 for (uint8_t byte : data) {
4117 result.appendFormat("%x ", byte);
4118 }
4119 result.append("\n");
4120 continue;
4121 }
4122
4123 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4124 result.append(edid->displayName.data(), edid->displayName.length());
4125 result.append("\"\n");
4126 }
4127 result.append("\n");
4128}
4129
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004130void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4131 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004132 result.appendFormat("DisplayColorSetting: %s\n",
4133 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004134
4135 // TODO: print out if wide-color mode is active or not
4136
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004137 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004138 const int32_t displayId = display->getId();
4139 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004140 continue;
4141 }
4142
Dominik Laskowski7e045462018-05-30 13:02:02 -07004143 result.appendFormat("Display %d color modes:\n", displayId);
4144 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004145 for (auto&& mode : modes) {
4146 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4147 }
4148
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004149 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004150 result.appendFormat(" Current color mode: %s (%d)\n",
4151 decodeColorMode(currentMode).c_str(), currentMode);
4152 }
4153 result.append("\n");
4154}
4155
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004156LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004157 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004158 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4159 const State& state = useDrawing ? mDrawingState : mCurrentState;
4160 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004161 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004162 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004163 });
4164
4165 return layersProto;
4166}
4167
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004168LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004169 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004170
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004171 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004172 resolution->set_w(display.getWidth());
4173 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004174
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004175 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4176 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4177 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004178
Dominik Laskowski7e045462018-05-30 13:02:02 -07004179 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004180 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004181 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004182 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004183 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004184 }
4185 });
4186
4187 return layersProto;
4188}
4189
Mathias Agopian74d211a2013-04-22 16:55:35 +02004190void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4191 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004192{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004193 bool colorize = false;
4194 if (index < args.size()
4195 && (args[index] == String16("--color"))) {
4196 colorize = true;
4197 index++;
4198 }
4199
4200 Colorizer colorizer(colorize);
4201
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004202 // figure out if we're stuck somewhere
4203 const nsecs_t now = systemTime();
4204 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4205 const nsecs_t inTransaction(mDebugInTransaction);
4206 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4207 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4208
4209 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004210 * Dump library configuration.
4211 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004212
4213 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004214 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004215 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004216 appendSfConfigString(result);
4217 appendUiConfigString(result);
4218 appendGuiConfigString(result);
4219 result.append("\n");
4220
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004221 result.append("\nDisplay identification data:\n");
4222 dumpDisplayIdentificationData(result);
4223
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004224 result.append("\nWide-Color information:\n");
4225 dumpWideColorInfo(result);
4226
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004227 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004228 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004229 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004230 result.append(SyncFeatures::getInstance().toString());
4231 result.append("\n");
4232
Andy McFadden41d67d72014-04-25 16:58:34 -07004233 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004234 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004235 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004236
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004237 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4238 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004239 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4240 getHwComposer().isConnected(displayId)) {
4241 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004242 result.appendFormat("Display %d: "
4243 "app phase %" PRId64 " ns, "
4244 "sf phase %" PRId64 " ns, "
4245 "early app phase %" PRId64 " ns, "
4246 "early sf phase %" PRId64 " ns, "
4247 "early app gl phase %" PRId64 " ns, "
4248 "early sf gl phase %" PRId64 " ns, "
4249 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4250 displayId,
4251 vsyncPhaseOffsetNs,
4252 sfVsyncPhaseOffsetNs,
4253 appEarlyOffset,
4254 sfEarlyOffset,
4255 appEarlyGlOffset,
4256 sfEarlyOffset,
4257 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004258 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004259 result.append("\n");
4260
Dan Stozab90cf072015-03-05 11:05:59 -08004261 // Dump static screen stats
4262 result.append("\n");
4263 dumpStaticScreenStats(result);
4264 result.append("\n");
4265
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004266 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4267
Dan Stozae77c7662016-05-13 11:37:28 -07004268 dumpBufferingStats(result);
4269
Andy McFadden4803b742012-09-24 19:07:20 -07004270 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004271 * Dump the visible layer list
4272 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004273 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004274 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004275 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4276 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004277 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004278
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004279 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004280 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004281 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004282 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004283
4284 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004285 * Dump Display state
4286 */
4287
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004288 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004289 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004290 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004291 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004292 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004293 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004294 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004295
4296 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004297 * Dump SurfaceFlinger global state
4298 */
4299
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004300 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004301 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004302 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004303
Mathias Agopian888c8222012-08-04 21:10:38 -07004304 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004305 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004306
David Sodmanbc815282017-11-05 18:57:52 -08004307 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004308
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004309 if (display) {
4310 display->undefinedRegion.dump(result, "undefinedRegion");
4311 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4312 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004313 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004314 result.appendFormat(" last eglSwapBuffers() time: %f us\n"
4315 " last transaction time : %f us\n"
4316 " transaction-flags : %08x\n"
4317 " gpu_to_cpu_unsupported : %d\n",
4318 mLastSwapBufferTime / 1000.0, mLastTransactionTime / 1000.0,
4319 mTransactionFlags, !mGpuToCpuSupported);
4320
4321 if (display) {
4322 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4323 result.appendFormat(" refresh-rate : %f fps\n"
4324 " x-dpi : %f\n"
4325 " y-dpi : %f\n",
4326 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4327 activeConfig->getDpiY());
4328 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004329
Mathias Agopian74d211a2013-04-22 16:55:35 +02004330 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004331 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004332
Mathias Agopian74d211a2013-04-22 16:55:35 +02004333 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004334 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004335
4336 /*
4337 * VSYNC state
4338 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004339 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004340 result.append("\n");
4341
4342 /*
4343 * HWC layer minidump
4344 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004345 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004346 const int32_t displayId = display->getId();
4347 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004348 continue;
4349 }
4350
Dominik Laskowski7e045462018-05-30 13:02:02 -07004351 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004352 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004353 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004354 result.append("\n");
4355 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004356
4357 /*
4358 * Dump HWComposer state
4359 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004360 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004361 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004362 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004363 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004364 result.appendFormat(" h/w composer %s\n",
4365 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004366 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004367
4368 /*
4369 * Dump gralloc state
4370 */
4371 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4372 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004373
4374 /*
4375 * Dump VrFlinger state if in use.
4376 */
4377 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4378 result.append("VrFlinger state:\n");
4379 result.append(mVrFlinger->Dump().c_str());
4380 result.append("\n");
4381 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004382}
4383
Dominik Laskowski7e045462018-05-30 13:02:02 -07004384const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004385 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004386 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004387 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004388 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004389 }
4390 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004391
4392 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4393 static const Vector<sp<Layer>> empty;
4394 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004395}
4396
Keun young Park63f165f2012-08-31 10:53:36 -07004397bool SurfaceFlinger::startDdmConnection()
4398{
4399 void* libddmconnection_dso =
4400 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4401 if (!libddmconnection_dso) {
4402 return false;
4403 }
4404 void (*DdmConnection_start)(const char* name);
4405 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004406 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004407 if (!DdmConnection_start) {
4408 dlclose(libddmconnection_dso);
4409 return false;
4410 }
4411 (*DdmConnection_start)(getServiceName());
4412 return true;
4413}
4414
Chia-I Wu28f320b2018-05-03 11:02:56 -07004415void SurfaceFlinger::updateColorMatrixLocked() {
4416 mat4 colorMatrix;
4417 if (mGlobalSaturationFactor != 1.0f) {
4418 // Rec.709 luma coefficients
4419 float3 luminance{0.213f, 0.715f, 0.072f};
4420 luminance *= 1.0f - mGlobalSaturationFactor;
4421 mat4 saturationMatrix = mat4(
4422 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4423 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4424 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4425 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4426 );
4427 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4428 } else {
4429 colorMatrix = mClientColorMatrix * mDaltonizer();
4430 }
4431
4432 if (mCurrentState.colorMatrix != colorMatrix) {
4433 mCurrentState.colorMatrix = colorMatrix;
4434 mCurrentState.colorMatrixChanged = true;
4435 setTransactionFlags(eTransactionNeeded);
4436 }
4437}
4438
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004439status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulecfbe2c002018-08-09 22:32:45 +00004440#pragma clang diagnostic push
4441#pragma clang diagnostic error "-Wswitch-enum"
4442 switch (static_cast<ISurfaceComposerTag>(code)) {
4443 // These methods should at minimum make sure that the client requested
4444 // access to SF.
4445 case AUTHENTICATE_SURFACE:
Peiyong Line70e1292018-08-09 14:06:58 -07004446 case BOOT_FINISHED:
4447 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulecfbe2c002018-08-09 22:32:45 +00004448 case CREATE_CONNECTION:
4449 case CREATE_DISPLAY:
4450 case DESTROY_DISPLAY:
Peiyong Line70e1292018-08-09 14:06:58 -07004451 case ENABLE_VSYNC_INJECTIONS:
Ana Krulecfbe2c002018-08-09 22:32:45 +00004452 case GET_ACTIVE_COLOR_MODE:
4453 case GET_ANIMATION_FRAME_STATS:
4454 case GET_HDR_CAPABILITIES:
4455 case SET_ACTIVE_CONFIG:
4456 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004457 case INJECT_VSYNC:
Ana Krulecfbe2c002018-08-09 22:32:45 +00004458 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004459 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4460 IPCThreadState* ipc = IPCThreadState::self();
4461 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4462 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004463 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004464 }
Robert Carr1db73f62016-12-21 12:58:51 -08004465 return OK;
4466 }
Ana Krulecfbe2c002018-08-09 22:32:45 +00004467 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004468 IPCThreadState* ipc = IPCThreadState::self();
4469 const int pid = ipc->getCallingPid();
4470 const int uid = ipc->getCallingUid();
Ana Krulecfbe2c002018-08-09 22:32:45 +00004471 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4472 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004473 return PERMISSION_DENIED;
4474 }
Ana Krulecfbe2c002018-08-09 22:32:45 +00004475 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004476 }
Ana Krulecfbe2c002018-08-09 22:32:45 +00004477 // Used by apps to hook Choreographer to SurfaceFlinger.
4478 case CREATE_DISPLAY_EVENT_CONNECTION:
4479 // The following calls are currently used by clients that do not
4480 // request necessary permissions. However, they do not expose any secret
4481 // information, so it is OK to pass them.
4482 case GET_ACTIVE_CONFIG:
4483 case GET_BUILT_IN_DISPLAY:
4484 case GET_DISPLAY_COLOR_MODES:
4485 case GET_DISPLAY_CONFIGS:
4486 case GET_DISPLAY_STATS:
4487 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4488 // Calling setTransactionState is safe, because you need to have been
4489 // granted a reference to Client* and Handle* to do anything with it.
4490 case SET_TRANSACTION_STATE:
4491 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4492 case CREATE_SCOPED_CONNECTION: {
4493 return OK;
4494 }
4495 case CAPTURE_LAYERS:
4496 case CAPTURE_SCREEN: {
4497 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004498 IPCThreadState* ipc = IPCThreadState::self();
4499 const int pid = ipc->getCallingPid();
4500 const int uid = ipc->getCallingUid();
4501 if ((uid != AID_GRAPHICS) &&
4502 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4503 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4504 return PERMISSION_DENIED;
4505 }
Ana Krulecfbe2c002018-08-09 22:32:45 +00004506 return OK;
4507 }
4508 // The following codes are deprecated and should never be allowed to access SF.
4509 case CONNECT_DISPLAY_UNUSED:
4510 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4511 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4512 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004513 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004514 }
Ana Krulecfbe2c002018-08-09 22:32:45 +00004515
4516 // These codes are used for the IBinder protocol to either interrogate the recipient
4517 // side of the transaction for its canonical interface descriptor or to dump its state.
4518 // We let them pass by default.
4519 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4520 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4521 code == IBinder::SYSPROPS_TRANSACTION) {
4522 return OK;
4523 }
4524 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4525 // in onTransact verifies that the user is root, and has access to use SF.
4526 if (code >= 1000 && code <= 1029) {
4527 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4528 return OK;
4529 }
4530 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4531 return PERMISSION_DENIED;
4532#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004533}
4534
Ana Krulecfbe2c002018-08-09 22:32:45 +00004535status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4536 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004537 status_t credentialCheck = CheckTransactCodeCredentials(code);
4538 if (credentialCheck != OK) {
4539 return credentialCheck;
4540 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004541
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004542 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4543 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004544 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004545 IPCThreadState* ipc = IPCThreadState::self();
4546 const int uid = ipc->getCallingUid();
4547 if (CC_UNLIKELY(uid != AID_SYSTEM
4548 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004549 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004550 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004551 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004552 return PERMISSION_DENIED;
4553 }
4554 int n;
4555 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004556 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004557 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004558 return NO_ERROR;
4559 case 1002: // SHOW_UPDATES
4560 n = data.readInt32();
4561 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004562 invalidateHwcGeometry();
4563 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004564 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004565 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004566 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004567 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004568 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004569 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004570 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004571 setTransactionFlags(
4572 eTransactionNeeded|
4573 eDisplayTransactionNeeded|
4574 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004575 return NO_ERROR;
4576 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004577 case 1006:{ // send empty update
4578 signalRefresh();
4579 return NO_ERROR;
4580 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004581 case 1008: // toggle use of hw composer
4582 n = data.readInt32();
4583 mDebugDisableHWC = n ? 1 : 0;
4584 invalidateHwcGeometry();
4585 repaintEverything();
4586 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004587 case 1009: // toggle use of transform hint
4588 n = data.readInt32();
4589 mDebugDisableTransformHint = n ? 1 : 0;
4590 invalidateHwcGeometry();
4591 repaintEverything();
4592 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004593 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004594 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004595 reply->writeInt32(0);
4596 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004597 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004598 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004599 return NO_ERROR;
4600 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004601 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004602 if (!display) {
4603 return NAME_NOT_FOUND;
4604 }
4605
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004606 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004607 return NO_ERROR;
4608 }
4609 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004610 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004611 // daltonize
4612 n = data.readInt32();
4613 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004614 case 1:
4615 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4616 break;
4617 case 2:
4618 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4619 break;
4620 case 3:
4621 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4622 break;
4623 default:
4624 mDaltonizer.setType(ColorBlindnessType::None);
4625 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004626 }
4627 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004628 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004629 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004630 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004631 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004632
4633 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004634 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004635 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004636 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004637 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004638 // apply a color matrix
4639 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004640 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004641 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004642 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004643 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004644 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004645 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004646 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004647 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004648 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004649 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004650
4651 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4652 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004653 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004654 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4655 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4656 }
4657
Chia-I Wu28f320b2018-05-03 11:02:56 -07004658 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004659 return NO_ERROR;
4660 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004661 // This is an experimental interface
4662 // Needs to be shifted to proper binder interface when we productize
4663 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004664 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07004665 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004666 return NO_ERROR;
4667 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004668 case 1017: {
4669 n = data.readInt32();
4670 mForceFullDamage = static_cast<bool>(n);
4671 return NO_ERROR;
4672 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004673 case 1018: { // Modify Choreographer's phase offset
4674 n = data.readInt32();
4675 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4676 return NO_ERROR;
4677 }
4678 case 1019: { // Modify SurfaceFlinger's phase offset
4679 n = data.readInt32();
4680 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4681 return NO_ERROR;
4682 }
Irvel468051e2016-06-13 16:44:44 -07004683 case 1020: { // Layer updates interceptor
4684 n = data.readInt32();
4685 if (n) {
4686 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004687 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004688 }
4689 else{
4690 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004691 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004692 }
4693 return NO_ERROR;
4694 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004695 case 1021: { // Disable HWC virtual displays
4696 n = data.readInt32();
4697 mUseHwcVirtualDisplays = !n;
4698 return NO_ERROR;
4699 }
Romain Guy0147a172017-06-01 13:53:56 -07004700 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004701 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004702 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004703
Chia-I Wu28f320b2018-05-03 11:02:56 -07004704 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004705 return NO_ERROR;
4706 }
Romain Guy54f154a2017-10-24 21:40:32 +01004707 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004708 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004709 invalidateHwcGeometry();
4710 repaintEverything();
4711 return NO_ERROR;
4712 }
4713 case 1024: { // Is wide color gamut rendering/color management supported?
4714 reply->writeBool(hasWideColorDisplay);
4715 return NO_ERROR;
4716 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004717 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004718 n = data.readInt32();
4719 if (n) {
4720 ALOGV("LayerTracing enabled");
4721 mTracing.enable();
4722 doTracing("tracing.enable");
4723 reply->writeInt32(NO_ERROR);
4724 } else {
4725 ALOGV("LayerTracing disabled");
4726 status_t err = mTracing.disable();
4727 reply->writeInt32(err);
4728 }
4729 return NO_ERROR;
4730 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004731 case 1026: { // Get layer tracing status
4732 reply->writeBool(mTracing.isEnabled());
4733 return NO_ERROR;
4734 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004735 // Is a DisplayColorSetting supported?
4736 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004737 const auto display = getDefaultDisplayDevice();
4738 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004739 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004740 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004741
4742 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4743 switch (setting) {
4744 case DisplayColorSetting::MANAGED:
4745 reply->writeBool(hasWideColorDisplay);
4746 break;
4747 case DisplayColorSetting::UNMANAGED:
4748 reply->writeBool(true);
4749 break;
4750 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004751 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004752 break;
4753 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004754 reply->writeBool(
4755 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004756 break;
4757 }
4758 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004759 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004760 // Is VrFlinger active?
4761 case 1028: {
4762 Mutex::Autolock _l(mStateLock);
4763 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4764 return NO_ERROR;
4765 }
David Sodman6d46c1e2018-07-13 12:59:48 -07004766 case 1029: {
4767 // Code 1029 is an experimental feature that allows applications to
4768 // simulate a high frequency panel by setting a multiplier and divisor
4769 // on the VSYNC-sf clock. If either the multiplier or divisor are
4770 // 0, then the code will set both to 1 to return the VSYNC-sf clock
4771 // to it's normal frequency.
4772 int multiplier = data.readInt32();
4773 int divisor = data.readInt32();
4774
4775 if ((multiplier == 0) || (divisor == 0)) {
4776 multiplier = 1;
4777 divisor = 1;
4778 }
4779
4780 if ((multiplier == 1) && (divisor == 1)) {
4781 enableHardwareVsync();
4782 } else {
4783 disableHardwareVsync(true);
4784 }
4785 getBE().mHwc->getActiveConfig(DisplayDevice::DISPLAY_PRIMARY)
4786 ->scalePanelFrequency(multiplier, divisor);
4787 mPrimaryDispSync->scalePeriod(multiplier, divisor);
4788
4789 ATRACE_INT("PeriodMultiplier", multiplier);
4790 ATRACE_INT("PeriodDivisor", divisor);
4791 return NO_ERROR;
4792 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004793 }
4794 }
4795 return err;
4796}
4797
Steven Thomas6d8110b2017-08-31 18:24:21 -07004798void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004799 android_atomic_or(1, &mRepaintEverything);
4800 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004801}
4802
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004803// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4804class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004805public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004806 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4807 ~WindowDisconnector() {
4808 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004809 }
4810
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004811private:
4812 ANativeWindow* mWindow;
4813 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004814};
4815
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004816status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4817 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4818 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4819 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004820 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004821 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004822
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004823 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004824
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004825 const auto display = getDisplayDeviceLocked(displayToken);
4826 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004827
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004828 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004829
4830 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004831 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004832 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004833}
4834
4835status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004836 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004837 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004838 ATRACE_CALL();
4839
4840 class LayerRenderArea : public RenderArea {
4841 public:
Robert Carr578038f2018-03-09 12:25:24 -08004842 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4843 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004844 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004845 mLayer(layer),
4846 mCrop(crop),
4847 mFlinger(flinger),
4848 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004849 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004850 Rect getBounds() const override {
4851 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07004852 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07004853 }
Marissa Wall61c58622018-07-18 10:12:20 -07004854 int getHeight() const override {
4855 return mLayer->getActiveHeight(mLayer->getDrawingState());
4856 }
4857 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07004858 bool isSecure() const override { return false; }
4859 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004860 Rect getSourceCrop() const override {
4861 if (mCrop.isEmpty()) {
4862 return getBounds();
4863 } else {
4864 return mCrop;
4865 }
4866 }
Robert Carr578038f2018-03-09 12:25:24 -08004867 class ReparentForDrawing {
4868 public:
4869 const sp<Layer>& oldParent;
4870 const sp<Layer>& newParent;
4871
4872 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4873 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004874 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004875 }
Robert Carr15eae092018-03-23 13:43:53 -07004876 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004877 };
4878
4879 void render(std::function<void()> drawLayers) override {
4880 if (!mChildrenOnly) {
4881 mTransform = mLayer->getTransform().inverse();
4882 drawLayers();
4883 } else {
4884 Rect bounds = getBounds();
4885 screenshotParentLayer =
4886 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4887 bounds.getWidth(), bounds.getHeight(), 0);
4888
4889 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4890 drawLayers();
4891 }
4892 }
chaviwa76b2712017-09-20 12:02:26 -07004893
chaviwa76b2712017-09-20 12:02:26 -07004894 private:
chaviw7206d492017-11-10 16:16:12 -08004895 const sp<Layer> mLayer;
4896 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004897
4898 // In the "childrenOnly" case we reparent the children to a screenshot
4899 // layer which has no properties set and which does not draw.
4900 sp<ContainerLayer> screenshotParentLayer;
4901 Transform mTransform;
4902
4903 SurfaceFlinger* mFlinger;
4904 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004905 };
4906
4907 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4908 auto parent = layerHandle->owner.promote();
4909
chaviw7206d492017-11-10 16:16:12 -08004910 if (parent == nullptr || parent->isPendingRemoval()) {
4911 ALOGE("captureLayers called with a removed parent");
4912 return NAME_NOT_FOUND;
4913 }
4914
Robert Carr578038f2018-03-09 12:25:24 -08004915 const int uid = IPCThreadState::self()->getCallingUid();
4916 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4917 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4918 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4919 return PERMISSION_DENIED;
4920 }
4921
chaviw7206d492017-11-10 16:16:12 -08004922 Rect crop(sourceCrop);
4923 if (sourceCrop.width() <= 0) {
4924 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07004925 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08004926 }
4927
4928 if (sourceCrop.height() <= 0) {
4929 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07004930 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08004931 }
4932
4933 int32_t reqWidth = crop.width() * frameScale;
4934 int32_t reqHeight = crop.height() * frameScale;
4935
Robert Carr578038f2018-03-09 12:25:24 -08004936 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004937
Robert Carr578038f2018-03-09 12:25:24 -08004938 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004939 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4940 if (!layer->isVisible()) {
4941 return;
Robert Carr578038f2018-03-09 12:25:24 -08004942 } else if (childrenOnly && layer == parent.get()) {
4943 return;
chaviwa76b2712017-09-20 12:02:26 -07004944 }
4945 visitor(layer);
4946 });
4947 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004948 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004949}
4950
4951status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4952 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004953 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004954 bool useIdentityTransform) {
4955 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004956
Iris Chang7501ed62018-04-30 14:45:42 +08004957 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004958
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004959 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4960 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4961 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4962 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004963
4964 // This mutex protects syncFd and captureResult for communication of the return values from the
4965 // main thread back to this Binder thread
4966 std::mutex captureMutex;
4967 std::condition_variable captureCondition;
4968 std::unique_lock<std::mutex> captureLock(captureMutex);
4969 int syncFd = -1;
4970 std::optional<status_t> captureResult;
4971
Robert Carr03480e22018-01-04 16:02:06 -08004972 const int uid = IPCThreadState::self()->getCallingUid();
4973 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4974
Dominik Laskowski8c001672018-05-30 16:52:06 -07004975 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004976 // If there is a refresh pending, bug out early and tell the binder thread to try again
4977 // after the refresh.
4978 if (mRefreshPending) {
4979 ATRACE_NAME("Skipping screenshot for now");
4980 std::unique_lock<std::mutex> captureLock(captureMutex);
4981 captureResult = std::make_optional<status_t>(EAGAIN);
4982 captureCondition.notify_one();
4983 return;
4984 }
4985
4986 status_t result = NO_ERROR;
4987 int fd = -1;
4988 {
4989 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07004990 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08004991 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
4992 useIdentityTransform, forSystem, &fd);
4993 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004994 }
4995
4996 {
4997 std::unique_lock<std::mutex> captureLock(captureMutex);
4998 syncFd = fd;
4999 captureResult = std::make_optional<status_t>(result);
5000 captureCondition.notify_one();
5001 }
5002 });
5003
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005004 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005005 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005006 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005007 while (*captureResult == EAGAIN) {
5008 captureResult.reset();
5009 result = postMessageAsync(message);
5010 if (result != NO_ERROR) {
5011 return result;
5012 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005013 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005014 }
5015 result = *captureResult;
5016 }
5017
5018 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005019 sync_wait(syncFd, -1);
5020 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005021 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005022
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005023 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005024}
5025
chaviwa76b2712017-09-20 12:02:26 -07005026void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5027 TraverseLayersFunction traverseLayers, bool yswap,
5028 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005029 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005030
Lloyd Pique144e1162017-12-20 16:44:52 -08005031 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005032
5033 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005034 const auto raWidth = renderArea.getWidth();
5035 const auto raHeight = renderArea.getHeight();
5036
5037 const auto reqWidth = renderArea.getReqWidth();
5038 const auto reqHeight = renderArea.getReqHeight();
5039 Rect sourceCrop = renderArea.getSourceCrop();
5040
Iris Chang7501ed62018-04-30 14:45:42 +08005041 bool filtering = false;
5042 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5043 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5044 static_cast<int32_t>(reqHeight) != raWidth;
5045 } else {
5046 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5047 static_cast<int32_t>(reqHeight) != raHeight;
5048 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005049
Dan Stozac1879002014-05-22 15:59:05 -07005050 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005051 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005052 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005053 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005054 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5055 Transform tr;
5056 uint32_t flags = 0x00;
5057 switch (mPrimaryDisplayOrientation) {
5058 case DisplayState::eOrientation90:
5059 flags = Transform::ROT_90;
5060 break;
5061 case DisplayState::eOrientation180:
5062 flags = Transform::ROT_180;
5063 break;
5064 case DisplayState::eOrientation270:
5065 flags = Transform::ROT_270;
5066 break;
5067 }
5068 tr.set(flags, raWidth, raHeight);
5069 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005070 }
5071
5072 // ensure that sourceCrop is inside screen
5073 if (sourceCrop.left < 0) {
5074 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5075 }
chaviwa76b2712017-09-20 12:02:26 -07005076 if (sourceCrop.right > raWidth) {
5077 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005078 }
5079 if (sourceCrop.top < 0) {
5080 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5081 }
chaviwa76b2712017-09-20 12:02:26 -07005082 if (sourceCrop.bottom > raHeight) {
5083 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005084 }
5085
Chia-I Wu36574d92018-05-16 10:54:36 -07005086 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5087 engine.setOutputDataSpace(Dataspace::SRGB);
5088 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005089
Mathias Agopian180f10d2013-04-10 22:55:41 -07005090 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005091 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005092
Iris Chang7501ed62018-04-30 14:45:42 +08005093 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5094 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5095 // convert hw orientation into flag presentation
5096 // here inverse transform needed
5097 uint8_t hw_rot_90 = 0x00;
5098 uint8_t hw_flip_hv = 0x00;
5099 switch (mPrimaryDisplayOrientation) {
5100 case DisplayState::eOrientation90:
5101 hw_rot_90 = Transform::ROT_90;
5102 hw_flip_hv = Transform::ROT_180;
5103 break;
5104 case DisplayState::eOrientation180:
5105 hw_flip_hv = Transform::ROT_180;
5106 break;
5107 case DisplayState::eOrientation270:
5108 hw_rot_90 = Transform::ROT_90;
5109 break;
5110 }
5111
5112 // transform flags operation
5113 // 1) flip H V if both have ROT_90 flag
5114 // 2) XOR these flags
5115 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5116 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5117 if (rotation_rot_90 & hw_rot_90) {
5118 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5119 }
5120 rotation = static_cast<Transform::orientation_flags>
5121 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5122 }
5123
Mathias Agopian180f10d2013-04-10 22:55:41 -07005124 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005125 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005126 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005127 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005128
chaviw50da5042018-04-09 13:49:37 -07005129 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005130 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005131 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005132
chaviwa76b2712017-09-20 12:02:26 -07005133 traverseLayers([&](Layer* layer) {
5134 if (filtering) layer->setFiltering(true);
David Sodmanca10ed22018-04-16 14:10:25 -07005135 layer->drawNow(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005136 if (filtering) layer->setFiltering(false);
5137 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005138}
5139
chaviwa76b2712017-09-20 12:02:26 -07005140status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5141 TraverseLayersFunction traverseLayers,
5142 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005143 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005144 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005145 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005146 ATRACE_CALL();
5147
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005148 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005149
5150 traverseLayers([&](Layer* layer) {
5151 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5152 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005153
Robert Carr03480e22018-01-04 16:02:06 -08005154 // We allow the system server to take screenshots of secure layers for
5155 // use in situations like the Screen-rotation animation and place
5156 // the impetus on WindowManager to not persist them.
5157 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005158 ALOGW("FB is protected: PERMISSION_DENIED");
5159 return PERMISSION_DENIED;
5160 }
5161
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005162 // this binds the given EGLImage as a framebuffer for the
5163 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005164 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005165 if (bufferBond.getStatus() != NO_ERROR) {
5166 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005167 return INVALID_OPERATION;
5168 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005169
Dan Stozaabcda352017-06-01 14:37:39 -07005170 // this will in fact render into our dequeued buffer
5171 // via an FBO, which means we didn't have to create
5172 // an EGLSurface and therefore we're not
5173 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005174 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005175
Dan Stozaabcda352017-06-01 14:37:39 -07005176 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005177 getRenderEngine().finish();
5178 *outSyncFd = -1;
5179
chaviwa76b2712017-09-20 12:02:26 -07005180 const auto reqWidth = renderArea.getReqWidth();
5181 const auto reqHeight = renderArea.getReqHeight();
5182
Dan Stozaabcda352017-06-01 14:37:39 -07005183 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5184 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005185 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005186 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005187 } else {
5188 base::unique_fd syncFd = getRenderEngine().flush();
5189 if (syncFd < 0) {
5190 getRenderEngine().finish();
5191 }
5192 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005193 }
5194
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005195 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005196}
5197
Mathias Agopiand5556842013-09-19 17:08:37 -07005198void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005199 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005200 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005201 for (size_t y = 0; y < h; y++) {
5202 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5203 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005204 if (p[x] != 0xFF000000) return;
5205 }
5206 }
chaviwa76b2712017-09-20 12:02:26 -07005207 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005208
Robert Carr2047fae2016-11-28 14:09:09 -08005209 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005210 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005211 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005212 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5213 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5214 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5215 static_cast<float>(state.color.a));
5216 i++;
5217 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005218 }
5219}
5220
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005221// ---------------------------------------------------------------------------
5222
Dan Stoza412903f2017-04-27 13:42:17 -07005223void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5224 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005225}
5226
Dan Stoza412903f2017-04-27 13:42:17 -07005227void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5228 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005229}
5230
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005231void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5232 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005233 const LayerVector::Visitor& visitor) {
5234 // We loop through the first level of layers without traversing,
5235 // as we need to interpret min/max layer Z in the top level Z space.
5236 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005237 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005238 continue;
5239 }
5240 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005241 // relative layers are traversed in Layer::traverseInZOrder
5242 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005243 continue;
5244 }
5245 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005246 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005247 return;
5248 }
chaviwa76b2712017-09-20 12:02:26 -07005249 if (!layer->isVisible()) {
5250 return;
5251 }
5252 visitor(layer);
5253 });
5254 }
5255}
5256
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005257}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005258
Lloyd Pique074e8122018-07-26 12:57:23 -07005259
Mathias Agopian3f844832013-08-07 21:24:32 -07005260#if defined(__gl_h_)
5261#error "don't include gl/gl.h in this file"
5262#endif
5263
5264#if defined(__gl2_h_)
5265#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005266#endif