blob: ad8a4dcf72b5b24bc3dfa31224add4934686a4d1 [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>
Peiyong Lincbc184f2018-08-22 13:24:10 -070050#include <renderengine/RenderEngine.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070051#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Robert Carr578038f2018-03-09 12:25:24 -080065#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070066#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070067#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020070#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080072#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080073#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Steven Thomasb02664d2017-07-26 18:48:28 -070079#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070080#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070084#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070085#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070086#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070087#include "Scheduler/EventControlThread.h"
88#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070089#include "Scheduler/InjectVSyncSource.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070090#include "Scheduler/Scheduler.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070091
Mathias Agopianff2ed702013-09-01 21:36:12 -070092#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070093
David Sodman7e4ae112018-02-09 15:02:28 -080094#include "android-base/stringprintf.h"
95
Jiyong Park4b20c2e2017-01-14 19:45:11 +090096#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080097#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -070098#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080099#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900100#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900101
chaviw1d044282017-09-27 12:19:28 -0700102#include <layerproto/LayerProtoParser.h>
103
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800104#define DISPLAY_COUNT 1
105
106namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700107
Jaesoo Lee43518572017-01-23 19:03:16 +0900108using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900109using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700110using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700111using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700112using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700113using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900114
Steven Thomasb02664d2017-07-26 18:48:28 -0700115namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700116
117#pragma clang diagnostic push
118#pragma clang diagnostic error "-Wswitch-enum"
119
120bool isWideColorMode(const ColorMode colorMode) {
121 switch (colorMode) {
122 case ColorMode::DISPLAY_P3:
123 case ColorMode::ADOBE_RGB:
124 case ColorMode::DCI_P3:
125 case ColorMode::BT2020:
126 case ColorMode::BT2100_PQ:
127 case ColorMode::BT2100_HLG:
128 return true;
129 case ColorMode::NATIVE:
130 case ColorMode::STANDARD_BT601_625:
131 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
132 case ColorMode::STANDARD_BT601_525:
133 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
134 case ColorMode::STANDARD_BT709:
135 case ColorMode::SRGB:
136 return false;
137 }
138 return false;
139}
140
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700141ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
142 switch (rotation) {
143 case ISurfaceComposer::eRotateNone:
144 return ui::Transform::ROT_0;
145 case ISurfaceComposer::eRotate90:
146 return ui::Transform::ROT_90;
147 case ISurfaceComposer::eRotate180:
148 return ui::Transform::ROT_180;
149 case ISurfaceComposer::eRotate270:
150 return ui::Transform::ROT_270;
151 }
152 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
153 return ui::Transform::ROT_0;
154}
155
Peiyong Linfca547f2018-07-09 13:03:33 -0700156#pragma clang diagnostic pop
157
Steven Thomasb02664d2017-07-26 18:48:28 -0700158class ConditionalLock {
159public:
160 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
161 if (lock) {
162 mMutex.lock();
163 }
164 }
165 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
166private:
167 Mutex& mMutex;
168 bool mLocked;
169};
Peiyong Linfca547f2018-07-09 13:03:33 -0700170
Steven Thomasb02664d2017-07-26 18:48:28 -0700171} // namespace anonymous
172
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800173// ---------------------------------------------------------------------------
174
Mathias Agopian99b49842011-06-27 16:05:52 -0700175const String16 sHardwareTest("android.permission.HARDWARE_TEST");
176const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
177const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
178const String16 sDump("android.permission.DUMP");
179
180// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800181int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
182int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700183int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700184bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800185uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800186bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800187bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800188int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800189// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600190bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700191int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700192bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700193bool SurfaceFlinger::useContextPriority;
Peiyong Lin0256f722018-08-31 15:45:10 -0700194Dataspace SurfaceFlinger::compositionDataSpace = Dataspace::V0_SRGB;
195ui::PixelFormat SurfaceFlinger::compositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700196
Kalle Raitaa099a242017-01-11 11:17:29 -0800197std::string getHwcServiceName() {
198 char value[PROPERTY_VALUE_MAX] = {};
199 property_get("debug.sf.hwc_service_name", value, "default");
200 ALOGI("Using HWComposer service: '%s'", value);
201 return std::string(value);
202}
203
204bool useTrebleTestingOverride() {
205 char value[PROPERTY_VALUE_MAX] = {};
206 property_get("debug.sf.treble_testing_override", value, "false");
207 ALOGI("Treble testing override: '%s'", value);
208 return std::string(value) == "true";
209}
210
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800211std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
212 switch(displayColorSetting) {
213 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700214 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800215 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700216 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800217 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700218 return std::string("Enhanced");
219 default:
220 return std::string("Unknown ") +
221 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800222 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800223}
224
Lloyd Pique99d3da52018-01-22 17:48:03 -0800225NativeWindowSurface::~NativeWindowSurface() = default;
226
227namespace impl {
228
229class NativeWindowSurface final : public android::NativeWindowSurface {
230public:
231 static std::unique_ptr<android::NativeWindowSurface> create(
232 const sp<IGraphicBufferProducer>& producer) {
233 return std::make_unique<NativeWindowSurface>(producer);
234 }
235
236 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
237 : surface(new Surface(producer, false)) {}
238
239 ~NativeWindowSurface() override = default;
240
241private:
242 sp<ANativeWindow> getNativeWindow() const override { return surface; }
243
244 void preallocateBuffers() override { surface->allocateBuffers(); }
245
246 sp<Surface> surface;
247};
248
249} // namespace impl
250
David Sodmanbc815282017-11-05 18:57:52 -0800251SurfaceFlingerBE::SurfaceFlingerBE()
252 : mHwcServiceName(getHwcServiceName()),
253 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800254 mFrameBuckets(),
255 mTotalTime(0),
256 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800257 mComposerSequenceId(0) {
258}
259
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800260SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800261 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800262 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700263 mTransactionPending(false),
264 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700265 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700266 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700267 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800268 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700269 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800270 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800271 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800272 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800273 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800274 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700275 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700276 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700277 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700278 mDebugInTransaction(0),
279 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700280 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700281 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700282 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800283 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800284 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800285 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700286 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800287 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800288 mCreateBufferQueue(&BufferQueue::createBufferQueue),
289 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800290
291SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800292 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800293
294 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
295 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
296
297 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
298 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
299
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800300 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
301 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800302
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700303 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
304 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
305
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700306 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
307 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
308
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800309 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
310 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
311
Steven Thomas050b2c82017-03-06 11:45:16 -0800312 // Vr flinger is only enabled on Daydream ready devices.
313 useVrFlinger = getBool< ISurfaceFlingerConfigs,
314 &ISurfaceFlingerConfigs::useVrFlinger>(false);
315
Fabien Sanglard1971b632017-03-10 14:50:03 -0800316 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
317 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
318
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600319 hasWideColorDisplay =
320 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700321 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700322 getBool<V1_2::ISurfaceFlingerConfigs,
323 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
324
325 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
326 if (surfaceFlingerConfigsServiceV1_2) {
327 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
328 [&](Dataspace tmpDataSpace, ui::PixelFormat tmpPixelFormat) {
329 compositionDataSpace = tmpDataSpace;
330 compositionPixelFormat = tmpPixelFormat;
331 });
332 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600333
Peiyong Linb3839ad2018-09-05 15:37:19 -0700334 useContextPriority = getBool<ISurfaceFlingerConfigs,
335 &ISurfaceFlingerConfigs::useContextPriority>(true);
336
Iris Chang7501ed62018-04-30 14:45:42 +0800337 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700338 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
339 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800340 V1_1::DisplayOrientation::ORIENTATION_0);
341
342 switch (primaryDisplayOrientation) {
343 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700344 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800345 break;
346 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700347 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800348 break;
349 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700350 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800351 break;
352 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700353 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800354 break;
355 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700356 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800357
Lloyd Pique41be5d22018-06-21 13:11:48 -0700358 // Note: We create a local temporary with the real DispSync implementation
359 // type temporarily so we can initialize it with the configured values,
360 // before storing it for more generic use using the interface type.
361 auto primaryDispSync = std::make_unique<impl::DispSync>("PrimaryDispSync");
362 primaryDispSync->init(SurfaceFlinger::hasSyncFramework,
363 SurfaceFlinger::dispSyncPresentTimeOffset);
364 mPrimaryDispSync = std::move(primaryDispSync);
Saurabh Shahf4174532017-07-13 10:45:07 -0700365
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800366 // debugging stuff...
367 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700368
Mathias Agopianb4b17302013-03-20 18:36:41 -0700369 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700370 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700371
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800372 property_get("debug.sf.showupdates", value, "0");
373 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700374
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700375 property_get("debug.sf.ddms", value, "0");
376 mDebugDDMS = atoi(value);
377 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700378 if (!startDdmConnection()) {
379 // start failed, and DDMS debugging not enabled
380 mDebugDDMS = 0;
381 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700382 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700383 ALOGI_IF(mDebugRegion, "showupdates enabled");
384 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700385
386 property_get("debug.sf.disable_backpressure", value, "0");
387 mPropagateBackpressure = !atoi(value);
388 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700389
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800390 property_get("debug.sf.enable_hwc_vds", value, "0");
391 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800392 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800393
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800394 property_get("ro.sf.disable_triple_buffer", value, "1");
395 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800396 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700397
Yiwei Zhang243b3782018-05-15 17:40:04 -0700398 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700399 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
400 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
401
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200402 property_get("debug.sf.early_phase_offset_ns", value, "-1");
403 const int earlySfOffsetNs = atoi(value);
404
405 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
406 const int earlyGlSfOffsetNs = atoi(value);
407
408 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
409 const int earlyAppOffsetNs = atoi(value);
410
411 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
412 const int earlyGlAppOffsetNs = atoi(value);
413
Ana Krulec98b5b242018-08-10 15:03:23 -0700414 property_get("debug.sf.use_scheduler", value, "0");
415 mUseScheduler = atoi(value);
416
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200417 const VSyncModulator::Offsets earlyOffsets =
418 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
419 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
420 const VSyncModulator::Offsets earlyGlOffsets =
421 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
422 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
423 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
424 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700425
Romain Guy11d63f42017-07-20 12:47:14 -0700426 // We should be reading 'persist.sys.sf.color_saturation' here
427 // but since /data may be encrypted, we need to wait until after vold
428 // comes online to attempt to read the property. The property is
429 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800430
431 if (useTrebleTestingOverride()) {
432 // Without the override SurfaceFlinger cannot connect to HIDL
433 // services that are not listed in the manifests. Considered
434 // deriving the setting from the set service name, but it
435 // would be brittle if the name that's not 'default' is used
436 // for production purposes later on.
437 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
438 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800439}
440
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800441void SurfaceFlinger::onFirstRef()
442{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800443 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800444}
445
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800446SurfaceFlinger::~SurfaceFlinger()
447{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800448}
449
Dan Stozac7014012014-02-14 15:03:43 -0800450void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800451{
452 // the window manager died on us. prepare its eulogy.
453
Andy McFadden13a082e2012-08-24 10:16:42 -0700454 // restore initial conditions (default device unblank, etc)
455 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800456
457 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700458 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800459}
460
Robert Carr1db73f62016-12-21 12:58:51 -0800461static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700462 status_t err = client->initCheck();
463 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800464 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800465 }
Robert Carr1db73f62016-12-21 12:58:51 -0800466 return nullptr;
467}
468
469sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
470 return initClient(new Client(this));
471}
472
473sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
474 const sp<IGraphicBufferProducer>& gbp) {
475 if (authenticateSurfaceTexture(gbp) == false) {
476 return nullptr;
477 }
478 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
479 if (layer == nullptr) {
480 return nullptr;
481 }
482
483 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800484}
485
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700486sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
487 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700488{
489 class DisplayToken : public BBinder {
490 sp<SurfaceFlinger> flinger;
491 virtual ~DisplayToken() {
492 // no more references, this display must be terminated
493 Mutex::Autolock _l(flinger->mStateLock);
494 flinger->mCurrentState.displays.removeItem(this);
495 flinger->setTransactionFlags(eDisplayTransactionNeeded);
496 }
497 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700498 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700499 : flinger(flinger) {
500 }
501 };
502
503 sp<BBinder> token = new DisplayToken(this);
504
505 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700506 DisplayDeviceState info;
507 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700508 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700509 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700510 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800511 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700512 return token;
513}
514
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700515void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700516 Mutex::Autolock _l(mStateLock);
517
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700518 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700519 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700520 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700521 return;
522 }
523
524 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700525 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700526 ALOGE("destroyDisplay called for non-virtual display");
527 return;
528 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700529 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700530 mCurrentState.displays.removeItemsAt(idx);
531 setTransactionFlags(eDisplayTransactionNeeded);
532}
533
Mathias Agopiane57f2922012-08-09 16:29:12 -0700534sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700535 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700536 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800537 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700538 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700539 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700540}
541
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800542void SurfaceFlinger::bootFinished()
543{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700544 if (mStartPropertySetThread->join() != NO_ERROR) {
545 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800546 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800547 const nsecs_t now = systemTime();
548 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000549 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700550
551 // wait patiently for the window manager death
552 const String16 name("window");
553 sp<IBinder> window(defaultServiceManager()->getService(name));
554 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700555 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700556 }
557
Steven Thomas050b2c82017-03-06 11:45:16 -0800558 if (mVrFlinger) {
559 mVrFlinger->OnBootFinished();
560 }
561
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700562 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700563 // formerly we would just kill the process, but we now ask it to exit so it
564 // can choose where to stop the animation.
565 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700566
567 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
568 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
569 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700570
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800571 postMessageAsync(new LambdaMessage([this] {
572 readPersistentProperties();
573 mBootStage = BootStage::FINISHED;
574 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800575}
576
Dan Stoza436ccf32018-06-21 12:10:12 -0700577uint32_t SurfaceFlinger::getNewTexture() {
578 {
579 std::lock_guard lock(mTexturePoolMutex);
580 if (!mTexturePool.empty()) {
581 uint32_t name = mTexturePool.back();
582 mTexturePool.pop_back();
583 ATRACE_INT("TexturePoolSize", mTexturePool.size());
584 return name;
585 }
586
587 // The pool was too small, so increase it for the future
588 ++mTexturePoolSize;
589 }
590
591 // The pool was empty, so we need to get a new texture name directly using a
592 // blocking call to the main thread
593 uint32_t name = 0;
594 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
595 return name;
596}
597
Mathias Agopian3f844832013-08-07 21:24:32 -0700598void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700599 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700600}
601
Wei Wangf9b05ee2017-07-19 20:59:39 -0700602// Do not call property_set on main thread which will be blocked by init
603// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700604void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700605 ALOGI( "SurfaceFlinger's main thread ready to run. "
606 "Initializing graphics H/W...");
607
Thierry Strudel2924d012017-08-14 15:19:37 -0700608 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900609
Steven Thomasb02664d2017-07-26 18:48:28 -0700610 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800611
Steven Thomasb02664d2017-07-26 18:48:28 -0700612 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700613 if (mUseScheduler) {
614 mScheduler = std::make_unique<Scheduler>();
615 mAppConnectionHandle =
616 mScheduler->createConnection("appConnection", mPrimaryDispSync.get(),
617 SurfaceFlinger::vsyncPhaseOffsetNs,
618 [this] { resyncWithRateLimit(); },
619 impl::EventThread::InterceptVSyncsCallback());
620 mSfConnectionHandle =
621 mScheduler->createConnection("sfConnection", mPrimaryDispSync.get(),
622 SurfaceFlinger::sfVsyncPhaseOffsetNs,
623 [this] { resyncWithRateLimit(); },
624 [this](nsecs_t timestamp) {
625 mInterceptor->saveVSyncEvent(timestamp);
626 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800627
Ana Krulec98b5b242018-08-10 15:03:23 -0700628 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700629 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
630 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700631 } else {
632 mEventThreadSource =
633 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
634 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
635 mEventThread =
636 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
637 [this] { resyncWithRateLimit(); },
638 impl::EventThread::InterceptVSyncsCallback(),
639 "appEventThread");
640 mSfEventThreadSource =
641 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
642 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
643
644 mSFEventThread =
645 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
646 [this] { resyncWithRateLimit(); },
647 [this](nsecs_t timestamp) {
648 mInterceptor->saveVSyncEvent(timestamp);
649 },
650 "sfEventThread");
651 mEventQueue->setEventThread(mSFEventThread.get());
652 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
653 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800654
Steven Thomasb02664d2017-07-26 18:48:28 -0700655 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700656 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700657 renderEngineFeature |= (useColorManagement ?
658 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700659 renderEngineFeature |= (useContextPriority ?
660 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700661
662 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
663 getBE().mRenderEngine =
Peiyong Linf11f39b2018-09-05 14:37:41 -0700664 renderengine::RenderEngine::create(static_cast<int32_t>(compositionPixelFormat),
665 renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800666 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700667
668 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
669 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800670 getBE().mHwc.reset(
671 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700672 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800673 // Process any initial hotplug and resulting display changes.
674 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700675 const auto display = getDefaultDisplayDeviceLocked();
676 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
677 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
678 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800679
Lloyd Piquefcd86612017-12-14 17:15:36 -0800680 // make the default display GLContext current so that we can create textures
681 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700682 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800683
Steven Thomas050b2c82017-03-06 11:45:16 -0800684 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700685 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700686 // This callback is called from the vr flinger dispatch thread. We
687 // need to call signalTransaction(), which requires holding
688 // mStateLock when we're not on the main thread. Acquiring
689 // mStateLock from the vr flinger dispatch thread might trigger a
690 // deadlock in surface flinger (see b/66916578), so post a message
691 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700692 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700693 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
694 mVrFlingerRequestsDisplay = requestDisplay;
695 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700696 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800697 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700698 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
699 getHwComposer()
700 .getHwcDisplayId(display->getId())
701 .value_or(0),
702 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800703 if (!mVrFlinger) {
704 ALOGE("Failed to start vrflinger");
705 }
706 }
707
Lloyd Pique379adc12018-01-22 17:31:47 -0800708 mEventControlThread = std::make_unique<impl::EventControlThread>(
709 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700710
Mathias Agopian92a979a2012-08-02 18:32:23 -0700711 // initialize our drawing state
712 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700713
Andy McFadden13a082e2012-08-24 10:16:42 -0700714 // set initial conditions (e.g. unblank default device)
715 initializeDisplays();
716
David Sodmanbc815282017-11-05 18:57:52 -0800717 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700718
Wei Wangf9b05ee2017-07-19 20:59:39 -0700719 // Inform native graphics APIs whether the present timestamp is supported:
720 if (getHwComposer().hasCapability(
721 HWC2::Capability::PresentFenceIsNotReliable)) {
722 mStartPropertySetThread = new StartPropertySetThread(false);
723 } else {
724 mStartPropertySetThread = new StartPropertySetThread(true);
725 }
726
727 if (mStartPropertySetThread->Start() != NO_ERROR) {
728 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800729 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800730
Chia-I Wud49d6692018-06-27 07:17:41 +0800731 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
732 // is used to saturate legacy sRGB content. However, to make sure the same color under
733 // Display P3 will be saturated to the same color, we intentionally break the API spec
734 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
735 // such saturation matrix on Display P3 is understood fully, the API should always return
736 // identify matrix.
737 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
738 Dataspace::SRGB_LINEAR);
739
740 // we will apply this on Display P3.
741 if (mEnhancedSaturationMatrix != mat4()) {
742 ColorSpace srgb(ColorSpace::sRGB());
743 ColorSpace displayP3(ColorSpace::DisplayP3());
744 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
745 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
746 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
747 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800748
Dan Stoza9e56aa02015-11-02 13:00:03 -0800749 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700750}
751
Romain Guy11d63f42017-07-20 12:47:14 -0700752void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700753 Mutex::Autolock _l(mStateLock);
754
Romain Guy11d63f42017-07-20 12:47:14 -0700755 char value[PROPERTY_VALUE_MAX];
756
757 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800758 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700759 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800760 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100761
762 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700763 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700764}
765
Mathias Agopiana67e4182012-06-19 17:26:12 -0700766void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800767 // Start boot animation service by setting a property mailbox
768 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700769 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800770 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700771 if (mStartPropertySetThread->join() != NO_ERROR) {
772 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800773 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700774}
775
Mathias Agopian875d8e12013-06-07 15:35:48 -0700776size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800777 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700778}
779
Mathias Agopian875d8e12013-06-07 15:35:48 -0700780size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800781 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700782}
783
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800784// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800785
Jamie Gennis582270d2011-08-17 18:19:00 -0700786bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800787 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800788 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800789 return authenticateSurfaceTextureLocked(bufferProducer);
790}
791
792bool SurfaceFlinger::authenticateSurfaceTextureLocked(
793 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800794 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800795 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800796}
797
Brian Anderson6b376712017-04-04 10:51:39 -0700798status_t SurfaceFlinger::getSupportedFrameTimestamps(
799 std::vector<FrameEvent>* outSupported) const {
800 *outSupported = {
801 FrameEvent::REQUESTED_PRESENT,
802 FrameEvent::ACQUIRE,
803 FrameEvent::LATCH,
804 FrameEvent::FIRST_REFRESH_START,
805 FrameEvent::LAST_REFRESH_START,
806 FrameEvent::GPU_COMPOSITION_DONE,
807 FrameEvent::DEQUEUE_READY,
808 FrameEvent::RELEASE,
809 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700810 ConditionalLock _l(mStateLock,
811 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700812 if (!getHwComposer().hasCapability(
813 HWC2::Capability::PresentFenceIsNotReliable)) {
814 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
815 }
816 return NO_ERROR;
817}
818
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700819status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
820 Vector<DisplayInfo>* configs) {
821 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700822 return BAD_VALUE;
823 }
824
Jesse Hall692c7232012-11-08 15:41:56 -0800825 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700826 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
827 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700828 type = i;
829 break;
830 }
831 }
832
833 if (type < 0) {
834 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700835 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700836
Mathias Agopian8b736f12012-08-13 17:54:26 -0700837 // TODO: Not sure if display density should handled by SF any longer
838 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700839 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700840 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700841 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800842 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700843 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700844 }
845 return density;
846 }
847 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700848 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700849 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700850 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700851 return getDensityFromProperty("ro.sf.lcd_density"); }
852 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700853
Dan Stoza7f7da322014-05-02 15:26:25 -0700854 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700855
Steven Thomas6d8110b2017-08-31 18:24:21 -0700856 ConditionalLock _l(mStateLock,
857 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800858 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700859 DisplayInfo info = DisplayInfo();
860
Dan Stoza9e56aa02015-11-02 13:00:03 -0800861 float xdpi = hwConfig->getDpiX();
862 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700863
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700864 info.w = hwConfig->getWidth();
865 info.h = hwConfig->getHeight();
866 // Default display viewport to display width and height
867 info.viewportW = info.w;
868 info.viewportH = info.h;
869
Dan Stoza7f7da322014-05-02 15:26:25 -0700870 if (type == DisplayDevice::DISPLAY_PRIMARY) {
871 // The density of the device is provided by a build property
872 float density = Density::getBuildDensity() / 160.0f;
873 if (density == 0) {
874 // the build doesn't provide a density -- this is wrong!
875 // use xdpi instead
876 ALOGE("ro.sf.lcd_density must be defined as a build property");
877 density = xdpi / 160.0f;
878 }
879 if (Density::getEmuDensity()) {
880 // if "qemu.sf.lcd_density" is specified, it overrides everything
881 xdpi = ydpi = density = Density::getEmuDensity();
882 density /= 160.0f;
883 }
884 info.density = density;
885
886 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700887 const auto display = getDefaultDisplayDeviceLocked();
888 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700889
890 // This is for screenrecord
891 const Rect viewport = display->getViewport();
892 if (viewport.isValid()) {
893 info.viewportW = uint32_t(viewport.getWidth());
894 info.viewportH = uint32_t(viewport.getHeight());
895 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700896 } else {
897 // TODO: where should this value come from?
898 static const int TV_DENSITY = 213;
899 info.density = TV_DENSITY / 160.0f;
900 info.orientation = 0;
901 }
902
Dan Stoza7f7da322014-05-02 15:26:25 -0700903 info.xdpi = xdpi;
904 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800905 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900906 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800907
Andy McFadden91b2ca82014-06-13 14:04:23 -0700908 // This is how far in advance a buffer must be queued for
909 // presentation at a given time. If you want a buffer to appear
910 // on the screen at time N, you must submit the buffer before
911 // (N - presentationDeadline).
912 //
913 // Normally it's one full refresh period (to give SF a chance to
914 // latch the buffer), but this can be reduced by configuring a
915 // DispSync offset. Any additional delays introduced by the hardware
916 // composer or panel must be accounted for here.
917 //
918 // We add an additional 1ms to allow for processing time and
919 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800920 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800921 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700922
923 // All non-virtual displays are currently considered secure.
924 info.secure = true;
925
Iris Chang7501ed62018-04-30 14:45:42 +0800926 if (type == DisplayDevice::DISPLAY_PRIMARY &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700927 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800928 std::swap(info.w, info.h);
929 }
930
Michael Wright28f24d02016-07-12 13:30:53 -0700931 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700932 }
933
Dan Stoza7f7da322014-05-02 15:26:25 -0700934 return NO_ERROR;
935}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700936
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700937status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
938 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700939 return BAD_VALUE;
940 }
941
942 // FIXME for now we always return stats for the primary display
943 memset(stats, 0, sizeof(*stats));
Lloyd Pique41be5d22018-06-21 13:11:48 -0700944 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
945 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700946 return NO_ERROR;
947}
948
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700949int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
950 const auto display = getDisplayDevice(displayToken);
951 if (!display) {
952 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800953 return BAD_VALUE;
954 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700955
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700956 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700957}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700958
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700959void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
960 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700961 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700962 return;
963 }
964
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700965 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700966 ALOGW("Trying to set config for virtual display");
967 return;
968 }
969
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700970 display->setActiveConfig(mode);
971 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700972}
973
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700974status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700975 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700976 Vector<DisplayInfo> configs;
977 getDisplayConfigs(displayToken, &configs);
978 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
979 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
980 configs.size());
981 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700982 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700983 const auto display = getDisplayDevice(displayToken);
984 if (!display) {
985 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
986 displayToken.get());
987 } else if (display->isVirtual()) {
988 ALOGW("Attempt to set active config %d for virtual display", mode);
989 } else {
990 setActiveConfigInternal(display, mode);
991 }
992 }));
993
Mathias Agopian888c8222012-08-04 21:10:38 -0700994 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700995}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700996status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
997 Vector<ColorMode>* outColorModes) {
998 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700999 return BAD_VALUE;
1000 }
1001
Michael Wright28f24d02016-07-12 13:30:53 -07001002 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001003 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
1004 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -07001005 type = i;
1006 break;
1007 }
1008 }
1009
1010 if (type < 0) {
1011 return type;
1012 }
1013
Peiyong Lina52f0292018-03-14 17:26:31 -07001014 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001015 {
1016 ConditionalLock _l(mStateLock,
1017 std::this_thread::get_id() != mMainThreadId);
1018 modes = getHwComposer().getColorModes(type);
1019 }
Michael Wright28f24d02016-07-12 13:30:53 -07001020 outColorModes->clear();
1021 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1022
1023 return NO_ERROR;
1024}
1025
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001026ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1027 if (const auto display = getDisplayDevice(displayToken)) {
1028 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001029 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001030 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001031}
1032
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001033void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1034 Dataspace dataSpace, RenderIntent renderIntent) {
1035 ColorMode currentMode = display->getActiveColorMode();
1036 Dataspace currentDataSpace = display->getCompositionDataSpace();
1037 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001038
Peiyong Lin38e9a562018-04-10 16:24:20 -07001039 if (mode == currentMode && dataSpace == currentDataSpace &&
1040 renderIntent == currentRenderIntent) {
1041 return;
1042 }
1043
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001044 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001045 ALOGW("Trying to set config for virtual display");
1046 return;
1047 }
1048
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001049 display->setActiveColorMode(mode);
1050 display->setCompositionDataSpace(dataSpace);
1051 display->setActiveRenderIntent(renderIntent);
1052 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001053
1054 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001055 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1056 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001057}
1058
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001059status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001060 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001061 Vector<ColorMode> modes;
1062 getDisplayColorModes(displayToken, &modes);
1063 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1064 if (mode < ColorMode::NATIVE || !exists) {
1065 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1066 decodeColorMode(mode).c_str(), mode, displayToken.get());
1067 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001068 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001069 const auto display = getDisplayDevice(displayToken);
1070 if (!display) {
1071 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1072 decodeColorMode(mode).c_str(), mode, displayToken.get());
1073 } else if (display->isVirtual()) {
1074 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1075 decodeColorMode(mode).c_str(), mode);
1076 } else {
1077 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1078 RenderIntent::COLORIMETRIC);
1079 }
1080 }));
1081
Michael Wright28f24d02016-07-12 13:30:53 -07001082 return NO_ERROR;
1083}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001084
Svetoslavd85084b2014-03-20 10:28:31 -07001085status_t SurfaceFlinger::clearAnimationFrameStats() {
1086 Mutex::Autolock _l(mStateLock);
1087 mAnimFrameTracker.clearStats();
1088 return NO_ERROR;
1089}
1090
1091status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1092 Mutex::Autolock _l(mStateLock);
1093 mAnimFrameTracker.getStats(outStats);
1094 return NO_ERROR;
1095}
1096
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001097status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1098 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001099 Mutex::Autolock _l(mStateLock);
1100
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001101 const auto display = getDisplayDeviceLocked(displayToken);
1102 if (!display) {
1103 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001104 return BAD_VALUE;
1105 }
1106
Peiyong Linfb069302018-04-25 14:34:31 -07001107 // At this point the DisplayDeivce should already be set up,
1108 // meaning the luminance information is already queried from
1109 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001110 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001111 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1112 capabilities.getDesiredMaxLuminance(),
1113 capabilities.getDesiredMaxAverageLuminance(),
1114 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001115
1116 return NO_ERROR;
1117}
1118
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001119status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001120 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001121 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001122
Chia-I Wu90f669f2017-10-05 14:24:41 -07001123 if (mInjectVSyncs == enable) {
1124 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001125 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001126
Ana Krulec98b5b242018-08-10 15:03:23 -07001127 // TODO(akrulec): Part of the Injector should be refactored, so that it
1128 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001129 if (enable) {
1130 ALOGV("VSync Injections enabled");
1131 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001132 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001133 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001134 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001135 impl::EventThread::InterceptVSyncsCallback(),
1136 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001137 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001138 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001139 } else {
1140 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001141 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001142 }
1143
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001144 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001145 }));
1146
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001147 return NO_ERROR;
1148}
1149
1150status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001151 Mutex::Autolock _l(mStateLock);
1152
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001153 if (!mInjectVSyncs) {
1154 ALOGE("VSync Injections not enabled");
1155 return BAD_VALUE;
1156 }
1157 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1158 ALOGV("Injecting VSync inside SurfaceFlinger");
1159 mVSyncInjector->onInjectSyncEvent(when);
1160 }
1161 return NO_ERROR;
1162}
1163
Lloyd Pique755e3192018-01-31 16:46:15 -08001164status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1165 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001166 // Try to acquire a lock for 1s, fail gracefully
1167 const status_t err = mStateLock.timedLock(s2ns(1));
1168 const bool locked = (err == NO_ERROR);
1169 if (!locked) {
1170 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1171 return TIMED_OUT;
1172 }
1173
1174 outLayers->clear();
1175 mCurrentState.traverseInZOrder([&](Layer* layer) {
1176 outLayers->push_back(layer->getLayerDebugInfo());
1177 });
1178
1179 mStateLock.unlock();
1180 return NO_ERROR;
1181}
1182
Peiyong Lin0256f722018-08-31 15:45:10 -07001183status_t SurfaceFlinger::getCompositionPreference(Dataspace* outDataSpace,
1184 ui::PixelFormat* outPixelFormat) const {
1185 *outDataSpace = compositionDataSpace;
1186 *outPixelFormat = compositionPixelFormat;
1187 return NO_ERROR;
1188}
1189
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001190// ----------------------------------------------------------------------------
1191
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001192sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1193 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001194 if (mUseScheduler) {
1195 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1196 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1197 } else {
1198 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1199 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001200 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001201 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1202 return mSFEventThread->createEventConnection();
1203 } else {
1204 return mEventThread->createEventConnection();
1205 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001206 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001207}
1208
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001209// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001210
1211void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001212 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001213}
1214
1215void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001216 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001217}
1218
1219void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001220 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001221}
1222
1223void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001224 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001225 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001226}
1227
1228status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001229 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001230 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001231}
1232
1233status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001234 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001235 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001236 if (res == NO_ERROR) {
1237 msg->wait();
1238 }
1239 return res;
1240}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001241
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001242void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001243 do {
1244 waitForEvent();
1245 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001246}
1247
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001248void SurfaceFlinger::enableHardwareVsync() {
1249 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001250 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001251 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001252 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001253 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001254 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001255}
1256
Jesse Hall948fe0c2013-10-14 12:56:09 -07001257void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001258 Mutex::Autolock _l(mHWVsyncLock);
1259
Jesse Hall948fe0c2013-10-14 12:56:09 -07001260 if (makeAvailable) {
1261 mHWVsyncAvailable = true;
1262 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001263 // Hardware vsync is not currently available, so abort the resync
1264 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001265 return;
1266 }
1267
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001268 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1269 if (!getHwComposer().isConnected(displayId)) {
1270 return;
1271 }
1272
1273 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001274 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001275
Lloyd Pique41be5d22018-06-21 13:11:48 -07001276 mPrimaryDispSync->reset();
1277 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001278
1279 if (!mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001280 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001281 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001282 mPrimaryHWVsyncEnabled = true;
1283 }
1284}
1285
Jesse Hall948fe0c2013-10-14 12:56:09 -07001286void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001287 Mutex::Autolock _l(mHWVsyncLock);
1288 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001289 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001290 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001291 mPrimaryHWVsyncEnabled = false;
1292 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001293 if (makeUnavailable) {
1294 mHWVsyncAvailable = false;
1295 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001296}
1297
Tim Murray4a4e4a22016-04-19 16:29:23 +00001298void SurfaceFlinger::resyncWithRateLimit() {
1299 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001300
1301 // No explicit locking is needed here since EventThread holds a lock while calling this method
1302 static nsecs_t sLastResyncAttempted = 0;
1303 const nsecs_t now = systemTime();
1304 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001305 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001306 }
Dan Stoza57164302017-05-08 14:03:54 -07001307 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001308}
1309
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001310void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1311 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001312 ATRACE_NAME("SF onVsync");
1313
Steven Thomas3cfac282017-02-06 12:29:30 -08001314 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001315 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001316 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001317 return;
1318 }
1319
1320 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001321 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001322 return;
1323 }
1324
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001325 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1326 // For now, we don't do anything with external display vsyncs.
1327 return;
1328 }
1329
Jamie Gennisd1700752013-10-14 12:22:52 -07001330 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001331
Jamie Gennisd1700752013-10-14 12:22:52 -07001332 { // Scope for the lock
1333 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001334 if (mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001335 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001336 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001337 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001338
1339 if (needsHwVsync) {
1340 enableHardwareVsync();
1341 } else {
1342 disableHardwareVsync(false);
1343 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001344}
1345
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001346void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001347 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1348 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001349}
1350
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001351void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001352 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001353 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001354 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001355
Lloyd Piqueba04e622017-12-14 17:11:26 -08001356 // Ignore events that do not have the right sequenceId.
1357 if (sequenceId != getBE().mComposerSequenceId) {
1358 return;
1359 }
1360
Steven Thomasb02664d2017-07-26 18:48:28 -07001361 // Only lock if we're not on the main thread. This function is normally
1362 // called on a hwbinder thread, but for the primary display it's called on
1363 // the main thread with the state lock already held, so don't attempt to
1364 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001365 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001366
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001367 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001368
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001369 if (std::this_thread::get_id() == mMainThreadId) {
1370 // Process all pending hot plug events immediately if we are on the main thread.
1371 processDisplayHotplugEventsLocked();
1372 }
1373
Lloyd Piqueba04e622017-12-14 17:11:26 -08001374 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001375}
1376
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001377void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001378 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001379 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001380 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001381 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001382 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001383}
1384
Dan Stoza9e56aa02015-11-02 13:00:03 -08001385void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001386 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001387 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001388 getHwComposer().setVsyncEnabled(disp,
1389 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001390}
1391
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001392// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001393void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001394 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001395 // Clear the drawing state so that the logic inside of
1396 // handleTransactionLocked will fire. It will determine the delta between
1397 // mCurrentState and mDrawingState and re-apply all changes when we make the
1398 // transition.
1399 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001400 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001401 mDisplays.clear();
1402}
1403
Steven Thomas050b2c82017-03-06 11:45:16 -08001404void SurfaceFlinger::updateVrFlinger() {
1405 if (!mVrFlinger)
1406 return;
1407 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001408 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001409 return;
1410 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001411
David Sodman105b7dc2017-11-04 20:28:14 -07001412 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001413 ALOGE("Vr flinger is only supported for remote hardware composer"
1414 " service connections. Ignoring request to transition to vr"
1415 " flinger.");
1416 mVrFlingerRequestsDisplay = false;
1417 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001418 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001419
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001420 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001421
Steven Thomas0123ac62018-07-12 11:32:34 -07001422 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001423 LOG_ALWAYS_FATAL_IF(!display);
1424 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001425 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1426 // called below. Clear the reference now so we don't accidentally use it
1427 // later.
1428 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001429
Steven Thomasb02664d2017-07-26 18:48:28 -07001430 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001431 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001432 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001433
Steven Thomasb02664d2017-07-26 18:48:28 -07001434 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001435 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001436 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1437 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001438 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001439
David Sodman105b7dc2017-11-04 20:28:14 -07001440 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1441 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001442
1443 if (vrFlingerRequestsDisplay) {
1444 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001445 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001446
1447 mVisibleRegionsDirty = true;
1448 invalidateHwcGeometry();
1449
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001450 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001451 display = getDefaultDisplayDeviceLocked();
1452 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001453 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001454
Steven Thomasb02664d2017-07-26 18:48:28 -07001455 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001456 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001457 const nsecs_t period = activeConfig->getVsyncPeriod();
1458 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001459
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001460 // The present fences returned from vr_hwc are not an accurate
1461 // representation of vsync times.
Lloyd Pique41be5d22018-06-21 13:11:48 -07001462 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1463 !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001464
Steven Thomasb02664d2017-07-26 18:48:28 -07001465 // Use phase of 0 since phase is not known.
1466 // Use latency of 0, which will snap to the ideal latency.
1467 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001468
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001469 resyncToHardwareVsync(false);
1470
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001471 android_atomic_or(1, &mRepaintEverything);
1472 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001473}
1474
Mathias Agopian4fec8732012-06-29 14:12:52 -07001475void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001476 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001477 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001478 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001479 bool frameMissed = !mHadClientComposition &&
1480 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001481 (mPreviousPresentFence->getSignalTime() ==
1482 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001483 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001484 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001485 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001486 mTimeStats.incrementMissedFrames();
1487 if (mPropagateBackpressure) {
1488 signalLayerUpdate();
1489 break;
1490 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001491 }
Dan Stoza50182882016-07-08 12:02:20 -07001492
Steven Thomas050b2c82017-03-06 11:45:16 -08001493 // Now that we're going to make it to the handleMessageTransaction()
1494 // call below it's safe to call updateVrFlinger(), which will
1495 // potentially trigger a display handoff.
1496 updateVrFlinger();
1497
Dan Stoza6b9454d2014-11-07 16:00:59 -08001498 bool refreshNeeded = handleMessageTransaction();
1499 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001500 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001501 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001502 // Signal a refresh if a transaction modified the window state,
1503 // a new buffer was latched, or if HWC has requested a full
1504 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001505 signalRefresh();
1506 }
1507 break;
1508 }
1509 case MessageQueue::REFRESH: {
1510 handleMessageRefresh();
1511 break;
1512 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001513 }
1514}
1515
Dan Stoza6b9454d2014-11-07 16:00:59 -08001516bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001517 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001518 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001519 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001520 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001521 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001522 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001523}
1524
Mathias Agopian4fec8732012-06-29 14:12:52 -07001525void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001526 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001527
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001528 mRefreshPending = false;
1529
David Sodmanfa9b2af2017-12-24 13:28:59 -08001530 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
David Sodman2b406362017-12-15 13:33:47 -08001531 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001532 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001533 calculateWorkingSet();
David Sodman10a41ff2018-08-05 12:14:17 -07001534
David Sodmanfa9b2af2017-12-24 13:28:59 -08001535 for (const auto& [token, display] : mDisplays) {
David Sodman10a41ff2018-08-05 12:14:17 -07001536 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001537 beginFrame(display);
David Sodman10a41ff2018-08-05 12:14:17 -07001538 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
1539 setUpHWComposer(compositionInfo);
1540 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001541 prepareFrame(display);
1542 doDebugFlashRegions(display, repaintEverything);
1543 doComposition(display, repaintEverything);
1544 }
1545
Adrian Roos1e1a1282017-11-01 19:05:31 +01001546 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001547 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001548
1549 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001550 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001551
Dan Stozabfbffeb2016-07-21 14:49:33 -07001552 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001553 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001554 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001555 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001556 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001557
Jorim Jaggi90535212018-05-23 23:44:06 +02001558 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001559
David Sodman7e4ae112018-02-09 15:02:28 -08001560 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001561 for (const auto& [token, display] : mDisplays) {
1562 const auto displayId = display->getId();
David Sodman7e4ae112018-02-09 15:02:28 -08001563 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[displayId]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001564 compositionInfo.hwc.hwcLayer = nullptr;
1565 }
David Sodmanba340492018-08-05 21:51:33 -07001566 }
David Sodman7e4ae112018-02-09 15:02:28 -08001567
1568 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001569}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001570
David Sodmanfa9b2af2017-12-24 13:28:59 -08001571
1572bool SurfaceFlinger::handleMessageInvalidate() {
1573 ATRACE_CALL();
1574 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001575}
1576
David Sodman79bba0e2018-08-05 18:07:49 -07001577void SurfaceFlinger::calculateWorkingSet() {
1578 ATRACE_CALL();
1579 ALOGV(__FUNCTION__);
1580
David Sodman79bba0e2018-08-05 18:07:49 -07001581 // build the h/w work list
1582 if (CC_UNLIKELY(mGeometryInvalid)) {
1583 mGeometryInvalid = false;
1584 for (const auto& [token, display] : mDisplays) {
1585 const auto displayId = display->getId();
1586 if (displayId >= 0) {
1587 const Vector<sp<Layer>>& currentLayers(
1588 display->getVisibleLayersSortedByZ());
1589 for (size_t i = 0; i < currentLayers.size(); i++) {
1590 const auto& layer = currentLayers[i];
1591
1592 if (!layer->hasHwcLayer(displayId)) {
1593 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1594 layer->forceClientComposition(displayId);
1595 continue;
1596 }
1597 }
1598
1599 layer->setGeometry(display, i);
1600 if (mDebugDisableHWC || mDebugRegion) {
1601 layer->forceClientComposition(displayId);
1602 }
1603 }
1604 }
1605 }
1606 }
1607
1608 // Set the per-frame data
1609 for (const auto& [token, display] : mDisplays) {
1610 const auto displayId = display->getId();
1611 if (displayId < 0) {
1612 continue;
1613 }
1614
1615 if (mDrawingState.colorMatrixChanged) {
1616 display->setColorTransform(mDrawingState.colorMatrix);
1617 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1618 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1619 "display %d: %d", displayId, result);
1620 }
1621 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1622 if (layer->isHdrY410()) {
1623 layer->forceClientComposition(displayId);
1624 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1625 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1626 !display->hasHDR10Support()) {
1627 layer->forceClientComposition(displayId);
1628 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1629 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1630 !display->hasHLGSupport()) {
1631 layer->forceClientComposition(displayId);
1632 }
1633
1634 if (layer->getForceClientComposition(displayId)) {
1635 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1636 layer->setCompositionType(displayId, HWC2::Composition::Client);
1637 continue;
1638 }
1639
1640 layer->setPerFrameData(display);
1641 }
1642
Peiyong Lin13effd12018-07-24 17:01:47 -07001643 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001644 ColorMode colorMode;
1645 Dataspace dataSpace;
1646 RenderIntent renderIntent;
1647 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1648 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1649 }
1650 }
1651
1652 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001653
1654 for (const auto& [token, display] : mDisplays) {
David Sodman15fb96e2018-01-07 10:23:24 -08001655 const auto displayId = display->getId();
1656 getBE().mCompositionInfo[displayId].clear();
David Sodmanba340492018-08-05 21:51:33 -07001657 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1658 auto displayId = display->getId();
1659 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1660 if (!layer->setHwcLayer(displayId)) {
1661 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1662 }
David Sodman15fb96e2018-01-07 10:23:24 -08001663 layer->getBE().compositionInfo.hwc.displayId = displayId;
1664 getBE().mCompositionInfo[displayId].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001665 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1666 }
1667 }
David Sodman79bba0e2018-08-05 18:07:49 -07001668}
1669
David Sodmanfa9b2af2017-12-24 13:28:59 -08001670void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001671{
David Sodmanfb95bcc2017-12-22 15:45:30 -08001672 const auto displayId = display->getId();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001673 // is debugging enabled
1674 if (CC_LIKELY(!mDebugRegion))
1675 return;
1676
David Sodmanfa9b2af2017-12-24 13:28:59 -08001677 if (display->isPoweredOn()) {
1678 // transform the dirty region into this screen's coordinate space
1679 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1680 if (!dirtyRegion.isEmpty()) {
1681 // redraw the whole screen
1682 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001683
David Sodmanfa9b2af2017-12-24 13:28:59 -08001684 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001685 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001686 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001687
David Sodmanfa9b2af2017-12-24 13:28:59 -08001688 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001689 }
1690 }
1691
David Sodmanfa9b2af2017-12-24 13:28:59 -08001692 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001693
1694 if (mDebugRegion > 1) {
1695 usleep(mDebugRegion * 1000);
1696 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001697
David Sodmanfa9b2af2017-12-24 13:28:59 -08001698 if (display->isPoweredOn()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08001699 status_t result = display->prepareFrame(
1700 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001701 ALOGE_IF(result != NO_ERROR,
1702 "prepareFrame for display %d failed:"
1703 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001704 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001705 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001706}
1707
Adrian Roos1e1a1282017-11-01 19:05:31 +01001708void SurfaceFlinger::doTracing(const char* where) {
1709 ATRACE_CALL();
1710 ATRACE_NAME(where);
1711 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001712 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001713 }
1714}
1715
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001716void SurfaceFlinger::logLayerStats() {
1717 ATRACE_CALL();
1718 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001719 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001720 if (display->isPrimary()) {
1721 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001722 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001723 }
1724 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001725
1726 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001727 }
1728}
1729
David Sodman2b406362017-12-15 13:33:47 -08001730void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001731{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001732 ATRACE_CALL();
1733 ALOGV("preComposition");
1734
David Sodman2b406362017-12-15 13:33:47 -08001735 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1736
Mathias Agopiancd60f992012-08-16 16:28:27 -07001737 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001738 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001739 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001740 needExtraInvalidate = true;
1741 }
Robert Carr2047fae2016-11-28 14:09:09 -08001742 });
1743
Mathias Agopiancd60f992012-08-16 16:28:27 -07001744 if (needExtraInvalidate) {
1745 signalLayerUpdate();
1746 }
1747}
1748
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001749void SurfaceFlinger::updateCompositorTiming(
1750 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1751 std::shared_ptr<FenceTime>& presentFenceTime) {
1752 // Update queue of past composite+present times and determine the
1753 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001754 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001755 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001756 while (!getBE().mCompositePresentTimes.empty()) {
1757 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001758 // Cached values should have been updated before calling this method,
1759 // which helps avoid duplicate syscalls.
1760 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1761 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1762 break;
1763 }
1764 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001765 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001766 }
1767
1768 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001769 while (getBE().mCompositePresentTimes.size() > 16) {
1770 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001771 }
1772
Brian Andersond0010582017-03-07 13:20:31 -08001773 setCompositorTimingSnapped(
1774 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1775}
1776
1777void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1778 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001779 // Integer division and modulo round toward 0 not -inf, so we need to
1780 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001781 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001782 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1783 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1784
Brian Andersond0010582017-03-07 13:20:31 -08001785 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1786 if (idealLatency <= 0) {
1787 idealLatency = vsyncInterval;
1788 }
1789
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001790 // Snap the latency to a value that removes scheduling jitter from the
1791 // composition and present times, which often have >1ms of jitter.
1792 // Reducing jitter is important if an app attempts to extrapolate
1793 // something (such as user input) to an accurate diasplay time.
1794 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1795 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001796 nsecs_t bias = vsyncInterval / 2;
1797 int64_t extraVsyncs =
1798 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1799 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1800 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001801
David Sodman99974d22017-11-28 12:04:33 -08001802 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1803 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1804 getBE().mCompositorTiming.interval = vsyncInterval;
1805 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001806}
1807
David Sodman2b406362017-12-15 13:33:47 -08001808void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001809{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001810 ATRACE_CALL();
1811 ALOGV("postComposition");
1812
Brian Anderson3546a3f2016-07-14 11:51:14 -07001813 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001814 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001815 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001816 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001817 }
1818
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001819 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001820 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001821
David Sodman73beded2017-11-15 11:56:06 -08001822 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001823 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001824 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001825 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001826 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001827 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001828 } else {
1829 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1830 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001831
David Sodman73beded2017-11-15 11:56:06 -08001832 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001833 mPreviousPresentFence =
1834 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1835 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001836 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001837
Lloyd Pique41be5d22018-06-21 13:11:48 -07001838 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1839 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001840
David Sodman2b406362017-12-15 13:33:47 -08001841 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001842 // when we started doing work for this frame, but that should be okay
1843 // since updateCompositorTiming has snapping logic.
1844 updateCompositorTiming(
David Sodman2b406362017-12-15 13:33:47 -08001845 vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001846 CompositorTiming compositorTiming;
1847 {
David Sodman99974d22017-11-28 12:04:33 -08001848 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1849 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001850 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001851
Robert Carr2047fae2016-11-28 14:09:09 -08001852 mDrawingState.traverseInZOrder([&](Layer* layer) {
1853 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001854 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001855 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001856 recordBufferingStats(layer->getName().string(),
1857 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001858 }
Robert Carr2047fae2016-11-28 14:09:09 -08001859 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001860
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001861 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001862 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001863 enableHardwareVsync();
1864 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001865 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001866 }
1867 }
1868
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001869 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001870 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001871 enableHardwareVsync();
1872 }
1873 }
1874
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001875 if (mAnimCompositionPending) {
1876 mAnimCompositionPending = false;
1877
Brian Anderson4e606e32017-03-16 15:34:57 -07001878 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001879 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001880 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001881 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001882 // The HWC doesn't support present fences, so use the refresh
1883 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001884 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001885 mAnimFrameTracker.setActualPresentTime(presentTime);
1886 }
1887 mAnimFrameTracker.advanceFrame();
1888 }
Dan Stozab90cf072015-03-05 11:05:59 -08001889
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001890 mTimeStats.incrementTotalFrames();
1891 if (mHadClientComposition) {
1892 mTimeStats.incrementClientCompositionFrames();
1893 }
1894
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001895 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001896 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001897 return;
1898 }
1899
1900 nsecs_t currentTime = systemTime();
1901 if (mHasPoweredOff) {
1902 mHasPoweredOff = false;
1903 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001904 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001905 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001906 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1907 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001908 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001909 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001910 }
David Sodman4a36e932017-11-07 14:29:47 -08001911 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001912 }
David Sodman4a36e932017-11-07 14:29:47 -08001913 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001914
1915 {
1916 std::lock_guard lock(mTexturePoolMutex);
1917 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1918 if (refillCount > 0) {
1919 const size_t offset = mTexturePool.size();
1920 mTexturePool.resize(mTexturePoolSize);
1921 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1922 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1923 }
1924 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001925}
1926
1927void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001928 ATRACE_CALL();
1929 ALOGV("rebuildLayerStacks");
1930
Mathias Agopiancd60f992012-08-16 16:28:27 -07001931 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001932 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001933 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001934 mVisibleRegionsDirty = false;
1935 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001936
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001937 for (const auto& pair : mDisplays) {
1938 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001939 Region opaqueRegion;
1940 Region dirtyRegion;
1941 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001942 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001943 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001944 const Rect bounds = display->getBounds();
1945 if (display->isPoweredOn()) {
1946 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001947
Jeff Sharkey76488112017-02-27 14:15:18 -07001948 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001949 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001950 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001951 Region drawRegion(tr.transform(
1952 layer->visibleNonTransparentRegion));
1953 drawRegion.andSelf(bounds);
1954 if (!drawRegion.isEmpty()) {
1955 layersSortedByZ.add(layer);
1956 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001957 // Clear out the HWC layer if this layer was
1958 // previously visible, but no longer is
1959 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001960 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001961 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001962 // WM changes display->layerStack upon sleep/awake.
1963 // Here we make sure we delete the HWC layers even if
1964 // WM changed their layer stack.
1965 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001966 }
1967
1968 // If a layer is not going to get a release fence because
1969 // it is invisible, but it is also going to release its
1970 // old buffer, add it to the list of layers needing
1971 // fences.
1972 if (hwcLayerDestroyed) {
1973 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1974 mLayersWithQueuedFrames.cend(), layer);
1975 if (found != mLayersWithQueuedFrames.cend()) {
1976 layersNeedingFences.add(layer);
1977 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001978 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001979 });
1980 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001981 display->setVisibleLayersSortedByZ(layersSortedByZ);
1982 display->setLayersNeedingFences(layersNeedingFences);
1983 display->undefinedRegion.set(bounds);
1984 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1985 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001986 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001987 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001988}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001989
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001990// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001991// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001992// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001993// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001994// The returned HDR data space is one of
1995// - Dataspace::UNKNOWN
1996// - Dataspace::BT2020_HLG
1997// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001998Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1999 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07002000 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002001 *outHdrDataSpace = Dataspace::UNKNOWN;
2002
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002003 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002004 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002005 case Dataspace::V0_SCRGB:
2006 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002007 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002008 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002009 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002010 case Dataspace::BT2020_PQ:
2011 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002012 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002013 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002014 case Dataspace::BT2020_HLG:
2015 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002016 // When there's mixed PQ content and HLG content, we set the HDR
2017 // data space to be BT2020_PQ and convert HLG to PQ.
2018 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2019 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002020 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002021 break;
2022 default:
2023 break;
2024 }
Romain Guy54f154a2017-10-24 21:40:32 +01002025 }
2026
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002027 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002028}
2029
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002030// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002031void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2032 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002033 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2034 *outMode = ColorMode::NATIVE;
2035 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002036 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002037 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002038 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002039
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002040 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002041 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002042
Peiyong Lindfde5112018-06-05 10:58:41 -07002043 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002044 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002045 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002046 if (isHdr) {
2047 bestDataSpace = hdrDataSpace;
2048 }
2049
Chia-I Wu0d711262018-05-21 15:19:35 -07002050 RenderIntent intent;
2051 switch (mDisplayColorSetting) {
2052 case DisplayColorSetting::MANAGED:
2053 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002054 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002055 break;
2056 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002057 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002058 break;
2059 default: // vendor display color setting
2060 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2061 break;
2062 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002063
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002064 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002065}
2066
David Sodman10a41ff2018-08-05 12:14:17 -07002067void SurfaceFlinger::configureSidebandComposition(const CompositionInfo& compositionInfo) const
2068{
2069 HWC2::Error error;
2070 LOG_ALWAYS_FATAL_IF(compositionInfo.hwc.sidebandStream == nullptr,
2071 "CompositionType is sideband, but sideband stream is nullptr");
2072 error = (compositionInfo.hwc.hwcLayer)
2073 ->setSidebandStream(compositionInfo.hwc.sidebandStream->handle());
2074 if (error != HWC2::Error::None) {
2075 ALOGE("[SF] Failed to set sideband stream %p: %s (%d)",
2076 compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
2077 static_cast<int32_t>(error));
2078 }
2079}
2080
2081void SurfaceFlinger::configureHwcCommonData(const CompositionInfo& compositionInfo) const
2082{
2083 HWC2::Error error;
2084
2085 if (!compositionInfo.hwc.skipGeometry) {
2086 error = (compositionInfo.hwc.hwcLayer)->setBlendMode(compositionInfo.hwc.blendMode);
2087 ALOGE_IF(error != HWC2::Error::None,
2088 "[SF] Failed to set blend mode %s:"
2089 " %s (%d)",
2090 to_string(compositionInfo.hwc.blendMode).c_str(), to_string(error).c_str(),
2091 static_cast<int32_t>(error));
2092
2093 error = (compositionInfo.hwc.hwcLayer)->setDisplayFrame(compositionInfo.hwc.displayFrame);
2094 ALOGE_IF(error != HWC2::Error::None,
2095 "[SF] Failed to set the display frame [%d, %d, %d, %d] %s (%d)",
2096 compositionInfo.hwc.displayFrame.left,
2097 compositionInfo.hwc.displayFrame.right,
2098 compositionInfo.hwc.displayFrame.top,
2099 compositionInfo.hwc.displayFrame.bottom,
2100 to_string(error).c_str(), static_cast<int32_t>(error));
2101
2102 error = (compositionInfo.hwc.hwcLayer)->setSourceCrop(compositionInfo.hwc.sourceCrop);
2103 ALOGE_IF(error != HWC2::Error::None,
2104 "[SF] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: %s (%d)",
2105 compositionInfo.hwc.sourceCrop.left,
2106 compositionInfo.hwc.sourceCrop.right,
2107 compositionInfo.hwc.sourceCrop.top,
2108 compositionInfo.hwc.sourceCrop.bottom,
2109 to_string(error).c_str(), static_cast<int32_t>(error));
2110
2111 error = (compositionInfo.hwc.hwcLayer)->setPlaneAlpha(compositionInfo.hwc.alpha);
2112 ALOGE_IF(error != HWC2::Error::None,
2113 "[SF] Failed to set plane alpha %.3f: "
2114 "%s (%d)",
2115 compositionInfo.hwc.alpha,
2116 to_string(error).c_str(), static_cast<int32_t>(error));
2117
2118
2119 error = (compositionInfo.hwc.hwcLayer)->setZOrder(compositionInfo.hwc.z);
2120 ALOGE_IF(error != HWC2::Error::None,
2121 "[SF] Failed to set Z %u: %s (%d)",
2122 compositionInfo.hwc.z,
2123 to_string(error).c_str(), static_cast<int32_t>(error));
2124
2125 error = (compositionInfo.hwc.hwcLayer)
2126 ->setInfo(compositionInfo.hwc.type, compositionInfo.hwc.appId);
2127 ALOGE_IF(error != HWC2::Error::None,
2128 "[SF] Failed to set info (%d)",
2129 static_cast<int32_t>(error));
2130
2131 error = (compositionInfo.hwc.hwcLayer)->setTransform(compositionInfo.hwc.transform);
2132 ALOGE_IF(error != HWC2::Error::None,
2133 "[SF] Failed to set transform %s: "
2134 "%s (%d)",
2135 to_string(compositionInfo.hwc.transform).c_str(), to_string(error).c_str(),
2136 static_cast<int32_t>(error));
2137 }
2138
2139 error = (compositionInfo.hwc.hwcLayer)->setCompositionType(compositionInfo.compositionType);
2140 ALOGE_IF(error != HWC2::Error::None,
2141 "[SF] Failed to set composition type: %s (%d)",
2142 to_string(error).c_str(), static_cast<int32_t>(error));
2143
2144 error = (compositionInfo.hwc.hwcLayer)->setDataspace(compositionInfo.hwc.dataspace);
2145 ALOGE_IF(error != HWC2::Error::None,
2146 "[SF] Failed to set dataspace: %s (%d)",
2147 to_string(error).c_str(), static_cast<int32_t>(error));
2148
2149 error = (compositionInfo.hwc.hwcLayer)->setPerFrameMetadata(
2150 compositionInfo.hwc.supportedPerFrameMetadata, compositionInfo.hwc.hdrMetadata);
2151 ALOGE_IF(error != HWC2::Error::None && error != HWC2::Error::Unsupported,
2152 "[SF] Failed to set hdrMetadata: %s (%d)",
2153 to_string(error).c_str(), static_cast<int32_t>(error));
2154
2155 if (compositionInfo.compositionType == HWC2::Composition::SolidColor) {
2156 error = (compositionInfo.hwc.hwcLayer)->setColor(compositionInfo.hwc.color);
2157 ALOGE_IF(error != HWC2::Error::None,
2158 "[SF] Failed to set color: %s (%d)",
2159 to_string(error).c_str(), static_cast<int32_t>(error));
2160 }
2161
2162 error = (compositionInfo.hwc.hwcLayer)->setVisibleRegion(compositionInfo.hwc.visibleRegion);
2163 ALOGE_IF(error != HWC2::Error::None,
2164 "[SF] Failed to set visible region: %s (%d)",
2165 to_string(error).c_str(), static_cast<int32_t>(error));
2166
2167 error = (compositionInfo.hwc.hwcLayer)->setSurfaceDamage(compositionInfo.hwc.surfaceDamage);
2168 ALOGE_IF(error != HWC2::Error::None,
2169 "[SF] Failed to set surface damage: %s (%d)",
2170 to_string(error).c_str(), static_cast<int32_t>(error));
2171}
2172
2173void SurfaceFlinger::configureDeviceComposition(const CompositionInfo& compositionInfo) const
2174{
2175 HWC2::Error error;
2176
2177 if (compositionInfo.hwc.fence) {
2178 error = (compositionInfo.hwc.hwcLayer)->setBuffer(compositionInfo.mBufferSlot,
2179 compositionInfo.mBuffer, compositionInfo.hwc.fence);
2180 ALOGE_IF(error != HWC2::Error::None,
2181 "[SF] Failed to set buffer: %s (%d)",
2182 to_string(error).c_str(), static_cast<int32_t>(error));
2183 }
2184}
2185
David Sodmanfa9b2af2017-12-24 13:28:59 -08002186void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002187{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002188 bool dirty = !display->getDirtyRegion(false).isEmpty();
2189 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2190 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002191
David Sodmanfa9b2af2017-12-24 13:28:59 -08002192 // If nothing has changed (!dirty), don't recompose.
2193 // If something changed, but we don't currently have any visible layers,
2194 // and didn't when we last did a composition, then skip it this time.
2195 // The second rule does two things:
2196 // - When all layers are removed from a display, we'll emit one black
2197 // frame, then nothing more until we get new layers.
2198 // - When a display is created with a private layer stack, we won't
2199 // emit any black frames until a layer is added to the layer stack.
2200 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002201
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002202 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2203 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002204 mustRecompose ? "doing" : "skipping",
2205 dirty ? "+" : "-",
2206 empty ? "+" : "-",
2207 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002208
David Sodmanfa9b2af2017-12-24 13:28:59 -08002209 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002210
David Sodmanfa9b2af2017-12-24 13:28:59 -08002211 if (mustRecompose) {
2212 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002213 }
2214}
2215
David Sodmanfa9b2af2017-12-24 13:28:59 -08002216void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002217{
David Sodmanfb95bcc2017-12-22 15:45:30 -08002218 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002219 if (!display->isPoweredOn()) {
2220 return;
David Sodman2b406362017-12-15 13:33:47 -08002221 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002222
David Sodmanfb95bcc2017-12-22 15:45:30 -08002223 status_t result = display->prepareFrame(
2224 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08002225 ALOGE_IF(result != NO_ERROR,
2226 "prepareFrame for display %d failed:"
2227 " %d (%s)",
2228 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002229}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002230
David Sodman10a41ff2018-08-05 12:14:17 -07002231void SurfaceFlinger::setUpHWComposer(const CompositionInfo& compositionInfo) {
2232 ATRACE_CALL();
2233 ALOGV("setUpHWComposer");
2234
2235 switch (compositionInfo.compositionType)
2236 {
2237 case HWC2::Composition::Invalid:
David Sodmana6d42332018-08-29 14:07:04 -07002238 break;
2239
David Sodman10a41ff2018-08-05 12:14:17 -07002240 case HWC2::Composition::Client:
David Sodmana6d42332018-08-29 14:07:04 -07002241 if (compositionInfo.hwc.hwcLayer) {
2242 auto error = (compositionInfo.hwc.hwcLayer)->
2243 setCompositionType(compositionInfo.compositionType);
2244 ALOGE_IF(error != HWC2::Error::None,
2245 "[SF] Failed to set composition type: %s (%d)",
2246 to_string(error).c_str(), static_cast<int32_t>(error));
2247 }
David Sodman10a41ff2018-08-05 12:14:17 -07002248 break;
2249
2250 case HWC2::Composition::Sideband:
2251 configureHwcCommonData(compositionInfo);
2252 configureSidebandComposition(compositionInfo);
2253 break;
2254
2255 case HWC2::Composition::SolidColor:
2256 configureHwcCommonData(compositionInfo);
2257 break;
2258
2259 case HWC2::Composition::Device:
2260 case HWC2::Composition::Cursor:
2261 configureHwcCommonData(compositionInfo);
2262 configureDeviceComposition(compositionInfo);
2263 break;
2264 }
2265}
2266
David Sodmanfa9b2af2017-12-24 13:28:59 -08002267void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002268 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002269 ALOGV("doComposition");
2270
David Sodmanfa9b2af2017-12-24 13:28:59 -08002271 if (display->isPoweredOn()) {
2272 // transform the dirty region into this screen's coordinate space
2273 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002274
David Sodmanfa9b2af2017-12-24 13:28:59 -08002275 // repaint the framebuffer (if needed)
2276 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002277
David Sodmanfa9b2af2017-12-24 13:28:59 -08002278 display->dirtyRegion.clear();
2279 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002280 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002281 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002282}
2283
David Sodmanfa9b2af2017-12-24 13:28:59 -08002284void SurfaceFlinger::postFrame()
2285{
2286 // |mStateLock| not needed as we are on the main thread
2287 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2288 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2289 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2290 logFrameStats();
2291 }
2292 }
2293}
2294
2295void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002296{
Mathias Agopian841cde52012-03-01 15:44:37 -08002297 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002298 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002299
David Sodmanfa9b2af2017-12-24 13:28:59 -08002300 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002301
David Sodmanfa9b2af2017-12-24 13:28:59 -08002302 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002303 const auto displayId = display->getId();
2304 if (displayId >= 0) {
2305 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002306 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002307 display->onSwapBuffersCompleted();
2308 display->makeCurrent();
David Sodman10a41ff2018-08-05 12:14:17 -07002309 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002310 sp<Fence> releaseFence = Fence::NO_FENCE;
Chia-I Wu7b549592017-11-15 09:14:57 -08002311 // The layer buffer from the previous frame (if any) is released
2312 // by HWC only when the release fence from this frame (if any) is
2313 // signaled. Always get the release fence from HWC first.
David Sodman10a41ff2018-08-05 12:14:17 -07002314 auto hwcLayer = compositionInfo.hwc.hwcLayer;
2315 if ((displayId >= 0) && hwcLayer) {
2316 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer.get());
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002317 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002318
2319 // If the layer was client composited in the previous frame, we
2320 // need to merge with the previous client target acquire fence.
2321 // Since we do not track that, always merge with the current
2322 // client target acquire fence when it is available, even though
2323 // this is suboptimal.
David Sodman10a41ff2018-08-05 12:14:17 -07002324 if (compositionInfo.compositionType == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002325 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002326 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002327 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002328
David Sodman10a41ff2018-08-05 12:14:17 -07002329 if (compositionInfo.layer) {
2330 compositionInfo.layer->onLayerDisplayed(releaseFence);
2331 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002332 }
Chia-I Wu83806892017-11-16 10:50:20 -08002333
2334 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002335 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002336 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002337 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002338 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002339 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002340 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002341 }
2342 }
2343
Dominik Laskowski7e045462018-05-30 13:02:02 -07002344 if (displayId >= 0) {
2345 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002346 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002347 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002348}
2349
Mathias Agopian87baae12012-07-31 12:38:26 -07002350void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002351{
Mathias Agopian841cde52012-03-01 15:44:37 -08002352 ATRACE_CALL();
2353
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002354 // here we keep a copy of the drawing state (that is the state that's
2355 // going to be overwritten by handleTransactionLocked()) outside of
2356 // mStateLock so that the side-effects of the State assignment
2357 // don't happen with mStateLock held (which can cause deadlocks).
2358 State drawingState(mDrawingState);
2359
Mathias Agopianca4d3602011-05-19 15:38:14 -07002360 Mutex::Autolock _l(mStateLock);
2361 const nsecs_t now = systemTime();
2362 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002363
Mathias Agopianca4d3602011-05-19 15:38:14 -07002364 // Here we're guaranteed that some transaction flags are set
2365 // so we can call handleTransactionLocked() unconditionally.
2366 // We call getTransactionFlags(), which will also clear the flags,
2367 // with mStateLock held to guarantee that mCurrentState won't change
2368 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002369
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002370 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002371 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002372 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002373
Mathias Agopianca4d3602011-05-19 15:38:14 -07002374 mLastTransactionTime = systemTime() - now;
2375 mDebugInTransaction = 0;
2376 invalidateHwcGeometry();
2377 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002378}
2379
Dominik Laskowski7e045462018-05-30 13:02:02 -07002380DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002381 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002382 // Figure out whether the event is for the primary display or an
2383 // external display by matching the Hwc display id against one for a
2384 // connected display. If we did not find a match, we then check what
2385 // displays are not already connected to determine the type. If we don't
2386 // have a connected primary display, we assume the new display is meant to
2387 // be the primary display, and then if we don't have an external display,
2388 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002389 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2390 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002391 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002392 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002393 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002394 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002395 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002396 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002397 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002398 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002399 return DisplayDevice::DISPLAY_EXTERNAL;
2400 }
2401
2402 return DisplayDevice::DISPLAY_ID_INVALID;
2403}
2404
Lloyd Piqueba04e622017-12-14 17:11:26 -08002405void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2406 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002407 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002408 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002409 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002410 continue;
2411 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002412
2413 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2414 ALOGE("External displays are not supported by the vr hardware composer.");
2415 continue;
2416 }
2417
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002418 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002419 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002420 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002421 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002422 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002423
2424 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002425 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002426 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002427 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002428 DisplayDeviceState info;
2429 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002430 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2431 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002432 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002433 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002434 mInterceptor->saveDisplayCreation(info);
2435 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002436 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002437 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002438
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002439 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002440 if (idx >= 0) {
2441 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002442 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002443 mCurrentState.displays.removeItemsAt(idx);
2444 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002445 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002446 }
2447
2448 processDisplayChangesLocked();
2449 }
2450
2451 mPendingHotplugEvents.clear();
2452}
2453
Lloyd Pique99d3da52018-01-22 17:48:03 -08002454sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002455 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002456 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002457 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002458 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002459 HdrCapabilities hdrCapabilities;
2460 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002461
Peiyong Lin13effd12018-07-24 17:01:47 -07002462 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002463 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002464 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002465 if (isWideColorMode(colorMode)) {
2466 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002467 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002468
Dominik Laskowski7e045462018-05-30 13:02:02 -07002469 std::vector<RenderIntent> renderIntents =
2470 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002471 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002472 }
tangrobin6753a022018-08-10 10:58:54 +08002473 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002474
tangrobin6753a022018-08-10 10:58:54 +08002475 if (displayId >= 0) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002476 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2477 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2478 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002479
2480 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2481 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2482
2483 /*
2484 * Create our display's surface
2485 */
Peiyong Lin833074a2018-08-28 11:53:54 -07002486 std::unique_ptr<renderengine::Surface> renderSurface = getRenderEngine().createSurface();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002487 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002488 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002489 renderSurface->setNativeWindow(nativeWindow.get());
Alec Mouri05483a02018-09-10 21:03:42 +00002490 const int displayWidth = renderSurface->getWidth();
2491 const int displayHeight = renderSurface->getHeight();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002492
2493 // Make sure that composition can never be stalled by a virtual display
2494 // consumer that isn't processing buffers fast enough. We have to do this
2495 // in two places:
2496 // * Here, in case the display is composed entirely by HWC.
2497 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2498 // window's swap interval in eglMakeCurrent, so they'll override the
2499 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002500 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002501 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2502 }
2503
Chia-I Wua02871c2018-08-27 14:38:23 -07002504 const int displayInstallOrientation = state.type == DisplayDevice::DISPLAY_PRIMARY ?
2505 primaryDisplayOrientation : DisplayState::eOrientationDefault;
2506
Lloyd Pique99d3da52018-01-22 17:48:03 -08002507 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002508 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002509
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002510 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002511 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2512 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
Chia-I Wua02871c2018-08-27 14:38:23 -07002513 displayHeight, displayInstallOrientation, hasWideColorGamut,
2514 hdrCapabilities, supportedPerFrameMetadata, hwcColorModes,
2515 initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002516
2517 if (maxFrameBufferAcquiredBuffers >= 3) {
2518 nativeWindowSurface->preallocateBuffers();
2519 }
2520
2521 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002522 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2523 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002524 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002525 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002526 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002527 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002528 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002529 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002530 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002531 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002532 display->setLayerStack(state.layerStack);
2533 display->setProjection(state.orientation, state.viewport, state.frame);
2534 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002535
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002536 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002537}
2538
Lloyd Pique347200f2017-12-14 17:00:15 -08002539void SurfaceFlinger::processDisplayChangesLocked() {
2540 // here we take advantage of Vector's copy-on-write semantics to
2541 // improve performance by skipping the transaction entirely when
2542 // know that the lists are identical
2543 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2544 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2545 if (!curr.isIdenticalTo(draw)) {
2546 mVisibleRegionsDirty = true;
2547 const size_t cc = curr.size();
2548 size_t dc = draw.size();
2549
2550 // find the displays that were removed
2551 // (ie: in drawing state but not in current state)
2552 // also handle displays that changed
2553 // (ie: displays that are in both lists)
2554 for (size_t i = 0; i < dc;) {
2555 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2556 if (j < 0) {
2557 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002558 // Call makeCurrent() on the primary display so we can
2559 // be sure that nothing associated with this display
2560 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002561 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2562 defaultDisplay->makeCurrent();
2563 }
2564 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2565 display->disconnect(getHwComposer());
2566 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002567 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002568 if (mUseScheduler) {
2569 mScheduler->hotplugReceived(mAppConnectionHandle,
2570 EventThread::DisplayType::Primary, false);
2571 } else {
2572 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2573 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002574 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002575 if (mUseScheduler) {
2576 mScheduler->hotplugReceived(mAppConnectionHandle,
2577 EventThread::DisplayType::External, false);
2578 } else {
2579 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2580 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002581 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002582 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002583 } else {
2584 // this display is in both lists. see if something changed.
2585 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002586 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002587 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2588 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2589 if (state_binder != draw_binder) {
2590 // changing the surface is like destroying and
2591 // recreating the DisplayDevice, so we just remove it
2592 // from the drawing state, so that it get re-added
2593 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002594 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2595 display->disconnect(getHwComposer());
2596 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002597 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002598 mDrawingState.displays.removeItemsAt(i);
2599 dc--;
2600 // at this point we must loop to the next item
2601 continue;
2602 }
2603
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002604 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002605 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002606 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002607 }
2608 if ((state.orientation != draw[i].orientation) ||
2609 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002610 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002611 }
2612 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002613 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002614 }
2615 }
2616 }
2617 ++i;
2618 }
2619
2620 // find displays that were added
2621 // (ie: in current state but not in drawing state)
2622 for (size_t i = 0; i < cc; i++) {
2623 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2624 const DisplayDeviceState& state(curr[i]);
2625
2626 sp<DisplaySurface> dispSurface;
2627 sp<IGraphicBufferProducer> producer;
2628 sp<IGraphicBufferProducer> bqProducer;
2629 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002630 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002631
Dominik Laskowski7e045462018-05-30 13:02:02 -07002632 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002633 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002634 // Virtual displays without a surface are dormant:
2635 // they have external state (layer stack, projection,
2636 // etc.) but no internal state (i.e. a DisplayDevice).
2637 if (state.surface != nullptr) {
2638 // Allow VR composer to use virtual displays.
2639 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2640 int width = 0;
2641 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2642 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2643 int height = 0;
2644 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2645 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2646 int intFormat = 0;
2647 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2648 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002649 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002650
Dominik Laskowski7e045462018-05-30 13:02:02 -07002651 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2652 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002653 }
2654
2655 // TODO: Plumb requested format back up to consumer
2656
2657 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002658 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002659 bqProducer, bqConsumer,
2660 state.displayName);
2661
2662 dispSurface = vds;
2663 producer = vds;
2664 }
2665 } else {
2666 ALOGE_IF(state.surface != nullptr,
2667 "adding a supported display, but rendering "
2668 "surface is provided (%p), ignoring it",
2669 state.surface.get());
2670
Dominik Laskowski7e045462018-05-30 13:02:02 -07002671 displayId = state.type;
2672 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002673 producer = bqProducer;
2674 }
2675
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002676 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002677 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002678 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002679 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002680 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002681 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002682 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002683 if (mUseScheduler) {
2684 mScheduler->hotplugReceived(mAppConnectionHandle,
2685 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002686 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002687 } else {
2688 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2689 true);
2690 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002691 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002692 if (mUseScheduler) {
2693 mScheduler->hotplugReceived(mAppConnectionHandle,
2694 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002695 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002696 } else {
2697 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2698 true);
2699 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002700 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002701 }
2702 }
2703 }
2704 }
2705 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002706
2707 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002708}
2709
Mathias Agopian87baae12012-07-31 12:38:26 -07002710void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002711{
Dan Stoza7dde5992015-05-22 09:51:44 -07002712 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002713 mCurrentState.traverseInZOrder([](Layer* layer) {
2714 layer->notifyAvailableFrames();
2715 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002716
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002717 /*
2718 * Traversal of the children
2719 * (perform the transaction for each of them if needed)
2720 */
2721
Mathias Agopian3559b072012-08-15 13:46:03 -07002722 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002723 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002724 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002725 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002726
2727 const uint32_t flags = layer->doTransaction(0);
2728 if (flags & Layer::eVisibleRegion)
2729 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002730 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002731 }
2732
2733 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002734 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002735 */
2736
Mathias Agopiane57f2922012-08-09 16:29:12 -07002737 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002738 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002739 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002740 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002741
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002742 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002743 // The transform hint might have changed for some layers
2744 // (either because a display has changed, or because a layer
2745 // as changed).
2746 //
2747 // Walk through all the layers in currentLayers,
2748 // and update their transform hint.
2749 //
2750 // If a layer is visible only on a single display, then that
2751 // display is used to calculate the hint, otherwise we use the
2752 // default display.
2753 //
2754 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2755 // the hint is set before we acquire a buffer from the surface texture.
2756 //
2757 // NOTE: layer transactions have taken place already, so we use their
2758 // drawing state. However, SurfaceFlinger's own transaction has not
2759 // happened yet, so we must use the current state layer list
2760 // (soon to become the drawing state list).
2761 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002762 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002763 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002764 bool first = true;
2765 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002766 // NOTE: we rely on the fact that layers are sorted by
2767 // layerStack first (so we don't have to traverse the list
2768 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002769 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002770 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002771 currentlayerStack = layerStack;
2772 // figure out if this layerstack is mirrored
2773 // (more than one display) if so, pick the default display,
2774 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002775 hintDisplay = nullptr;
2776 for (const auto& [token, display] : mDisplays) {
2777 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2778 if (hintDisplay) {
2779 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002780 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002781 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002782 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002783 }
2784 }
2785 }
2786 }
Chet Haase91d25932013-04-11 15:24:55 -07002787
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002788 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002789 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2790 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002791
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002792 // could be null when this layer is using a layerStack
2793 // that is not visible on any display. Also can occur at
2794 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002795 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002796 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002797
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002798 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002799 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002800 if (hintDisplay) {
2801 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002802 }
Robert Carr2047fae2016-11-28 14:09:09 -08002803
2804 first = false;
2805 });
Mathias Agopian84300952012-11-21 16:02:13 -08002806 }
2807
2808
Mathias Agopian3559b072012-08-15 13:46:03 -07002809 /*
2810 * Perform our own transaction if needed
2811 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002812
2813 if (mLayersAdded) {
2814 mLayersAdded = false;
2815 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002816 mVisibleRegionsDirty = true;
2817 }
2818
2819 // some layers might have been removed, so
2820 // we need to update the regions they're exposing.
2821 if (mLayersRemoved) {
2822 mLayersRemoved = false;
2823 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002824 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002825 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002826 // this layer is not visible anymore
2827 // TODO: we could traverse the tree from front to back and
2828 // compute the actual visible region
2829 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002830 Region visibleReg;
2831 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002832 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002833 }
Robert Carr2047fae2016-11-28 14:09:09 -08002834 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002835 }
2836
2837 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002838
2839 updateCursorAsync();
2840}
2841
2842void SurfaceFlinger::updateCursorAsync()
2843{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002844 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002845 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002846 continue;
2847 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002848
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002849 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2850 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002851 }
2852 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002853}
2854
2855void SurfaceFlinger::commitTransaction()
2856{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002857 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002858 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002859 for (const auto& l : mLayersPendingRemoval) {
2860 recordBufferingStats(l->getName().string(),
2861 l->getOccupancyHistory(true));
2862 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002863 }
2864 mLayersPendingRemoval.clear();
2865 }
2866
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002867 // If this transaction is part of a window animation then the next frame
2868 // we composite should be considered an animation as well.
2869 mAnimCompositionPending = mAnimTransactionPending;
2870
Mathias Agopian4fec8732012-06-29 14:12:52 -07002871 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002872 // clear the "changed" flags in current state
2873 mCurrentState.colorMatrixChanged = false;
2874
Robert Carr1f0a16a2016-10-24 16:27:39 -07002875 mDrawingState.traverseInZOrder([](Layer* layer) {
2876 layer->commitChildList();
2877 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002878 mTransactionPending = false;
2879 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002880 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002881}
2882
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002883void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2884 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002885 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002886 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002887
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002888 Region aboveOpaqueLayers;
2889 Region aboveCoveredLayers;
2890 Region dirty;
2891
Mathias Agopian87baae12012-07-31 12:38:26 -07002892 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002893
Robert Carr2047fae2016-11-28 14:09:09 -08002894 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002895 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002896 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002897
Jesse Hall01e29052013-02-19 16:13:35 -08002898 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002899 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002900 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002901 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002902
Mathias Agopianab028732010-03-16 16:41:46 -07002903 /*
2904 * opaqueRegion: area of a surface that is fully opaque.
2905 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002906 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002907
2908 /*
2909 * visibleRegion: area of a surface that is visible on screen
2910 * and not fully transparent. This is essentially the layer's
2911 * footprint minus the opaque regions above it.
2912 * Areas covered by a translucent surface are considered visible.
2913 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002914 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002915
2916 /*
2917 * coveredRegion: area of a surface that is covered by all
2918 * visible regions above it (which includes the translucent areas).
2919 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002920 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002921
Jesse Halla8026d22012-09-25 13:25:04 -07002922 /*
2923 * transparentRegion: area of a surface that is hinted to be completely
2924 * transparent. This is only used to tell when the layer has no visible
2925 * non-transparent regions and can be removed from the layer list. It
2926 * does not affect the visibleRegion of this layer or any layers
2927 * beneath it. The hint may not be correct if apps don't respect the
2928 * SurfaceView restrictions (which, sadly, some don't).
2929 */
2930 Region transparentRegion;
2931
Mathias Agopianab028732010-03-16 16:41:46 -07002932
2933 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002934 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002935 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002936 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002937 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002938 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002939 if (!visibleRegion.isEmpty()) {
2940 // Remove the transparent area from the visible region
2941 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002942 if (tr.preserveRects()) {
2943 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002944 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002945 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002946 // transformation too complex, can't do the
2947 // transparent region optimization.
2948 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002949 }
Mathias Agopianab028732010-03-16 16:41:46 -07002950 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002951
Mathias Agopianab028732010-03-16 16:41:46 -07002952 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002953 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002954 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002955 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002956 // the opaque region is the layer's footprint
2957 opaqueRegion = visibleRegion;
2958 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002959 }
2960 }
2961
Robert Carre5f4f692018-01-12 13:12:28 -08002962 if (visibleRegion.isEmpty()) {
2963 layer->clearVisibilityRegions();
2964 return;
2965 }
2966
Mathias Agopianab028732010-03-16 16:41:46 -07002967 // Clip the covered region to the visible region
2968 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2969
2970 // Update aboveCoveredLayers for next (lower) layer
2971 aboveCoveredLayers.orSelf(visibleRegion);
2972
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002973 // subtract the opaque region covered by the layers above us
2974 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002975
2976 // compute this layer's dirty region
2977 if (layer->contentDirty) {
2978 // we need to invalidate the whole region
2979 dirty = visibleRegion;
2980 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002981 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002982 layer->contentDirty = false;
2983 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002984 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002985 * the exposed region consists of two components:
2986 * 1) what's VISIBLE now and was COVERED before
2987 * 2) what's EXPOSED now less what was EXPOSED before
2988 *
2989 * note that (1) is conservative, we start with the whole
2990 * visible region but only keep what used to be covered by
2991 * something -- which mean it may have been exposed.
2992 *
2993 * (2) handles areas that were not covered by anything but got
2994 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002995 */
Mathias Agopianab028732010-03-16 16:41:46 -07002996 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002997 const Region oldVisibleRegion = layer->visibleRegion;
2998 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002999 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3000 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003001 }
3002 dirty.subtractSelf(aboveOpaqueLayers);
3003
3004 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003005 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003006
Mathias Agopianab028732010-03-16 16:41:46 -07003007 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003008 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003009
Jesse Halla8026d22012-09-25 13:25:04 -07003010 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003011 layer->setVisibleRegion(visibleRegion);
3012 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003013 layer->setVisibleNonTransparentRegion(
3014 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003015 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003016
Mathias Agopian87baae12012-07-31 12:38:26 -07003017 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003018}
3019
Chia-I Wuab0c3192017-08-01 11:29:00 -07003020void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003021 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003022 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
3023 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003024 }
3025 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003026}
3027
Dan Stoza6b9454d2014-11-07 16:00:59 -08003028bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003029{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003030 ALOGV("handlePageFlip");
3031
Brian Andersond6927fb2016-07-23 23:37:30 -07003032 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003033
Mathias Agopian4fec8732012-06-29 14:12:52 -07003034 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003035 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003036 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003037
3038 // Store the set of layers that need updates. This set must not change as
3039 // buffers are being latched, as this could result in a deadlock.
3040 // Example: Two producers share the same command stream and:
3041 // 1.) Layer 0 is latched
3042 // 2.) Layer 0 gets a new frame
3043 // 2.) Layer 1 gets a new frame
3044 // 3.) Layer 1 is latched.
3045 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3046 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003047 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003048 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003049 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07003050 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003051 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003052 } else {
3053 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003054 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003055 } else {
3056 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003057 }
Robert Carr2047fae2016-11-28 14:09:09 -08003058 });
3059
Dan Stoza9e56aa02015-11-02 13:00:03 -08003060 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07003061 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07003062 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003063 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07003064 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06003065 newDataLatched = true;
3066 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003067 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003068
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003069 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003070
3071 // If we will need to wake up at some time in the future to deal with a
3072 // queued frame that shouldn't be displayed during this vsync period, wake
3073 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003074 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003075 signalLayerUpdate();
3076 }
3077
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003078 // enter boot animation on first buffer latch
3079 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3080 ALOGI("Enter boot animation");
3081 mBootStage = BootStage::BOOTANIMATION;
3082 }
3083
Dan Stoza6b9454d2014-11-07 16:00:59 -08003084 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003085 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003086}
3087
Mathias Agopianad456f92011-01-13 17:53:01 -08003088void SurfaceFlinger::invalidateHwcGeometry()
3089{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003090 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003091}
3092
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003093void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
3094 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003095 // We only need to actually compose the display if:
3096 // 1) It is being handled by hardware composer, which may need this to
3097 // keep its virtual display state machine in sync, or
3098 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07003099 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08003100 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003101 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003102 return;
3103 }
3104
Dan Stoza9e56aa02015-11-02 13:00:03 -08003105 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003106 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003107
3108 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003109 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003110}
3111
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003112bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003113 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003114
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003115 const Region bounds(display->bounds());
3116 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003117 const auto displayId = display->getId();
3118 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003119 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003120
Chia-I Wu8e50e692018-05-04 10:12:37 -07003121 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003122 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003123
Dan Stoza9e56aa02015-11-02 13:00:03 -08003124 if (hasClientComposition) {
3125 ALOGV("hasClientComposition");
3126
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003127 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003128 if (display->hasWideColorGamut()) {
3129 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003130 }
3131 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003132 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003133 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003134
Dominik Laskowski7e045462018-05-30 13:02:02 -07003135 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003136 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3137 HWC2::Capability::SkipClientColorTransform);
3138
Chia-I Wud49d6692018-06-27 07:17:41 +08003139 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003140 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3141 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003142 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003143 }
3144
Chia-I Wud49d6692018-06-27 07:17:41 +08003145 // The current enhanced saturation matrix is designed to enhance Display P3,
3146 // thus we only apply this matrix when the render intent is not colorimetric
3147 // and the output color space is Display P3.
3148 needsEnhancedColorMatrix =
3149 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3150 outputDataspace == Dataspace::DISPLAY_P3);
3151 if (needsEnhancedColorMatrix) {
3152 colorMatrix *= mEnhancedSaturationMatrix;
3153 }
3154
3155 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003156
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003157 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003158 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003159 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003160 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003161
3162 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003163 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3164 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3165 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003166 }
3167 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003168 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003169
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003170 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003171 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003172 // when using overlays, we assume a fully transparent framebuffer
3173 // NOTE: we could reduce how much we need to clear, for instance
3174 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003175 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003176 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003177 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003178 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003179 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003180 // we're left with the letterbox region
3181 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003182 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003183
3184 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003185 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003186
Mathias Agopianb9494d52012-04-18 02:28:45 -07003187 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003188 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003189 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003190 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003191 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003192 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003193
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003194 const Rect& bounds = display->getBounds();
3195 const Rect& scissor = display->getScissor();
3196 if (scissor != bounds) {
3197 // scissor doesn't match the screen's dimensions, so we
3198 // need to clear everything outside of it and enable
3199 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003200
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003201 // enable scissor for this frame
Alec Mouri05483a02018-09-10 21:03:42 +00003202 getBE().mRenderEngine->setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003203 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003204 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003205
Mathias Agopian85d751c2012-08-29 16:59:24 -07003206 /*
3207 * and then, render the layers targeted at the framebuffer
3208 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003209
Dan Stoza9e56aa02015-11-02 13:00:03 -08003210 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003211 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003212 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003213 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003214 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003215 displayTransform.transform(layer->visibleRegion)));
3216 ALOGV("Layer: %s", layer->getName().string());
3217 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003218 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003219 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003220 case HWC2::Composition::Cursor:
3221 case HWC2::Composition::Device:
3222 case HWC2::Composition::Sideband:
3223 case HWC2::Composition::SolidColor: {
David Sodmanc1498e62018-09-12 14:36:26 -07003224 const Layer::State& state(layer->getDrawingState());
3225 if (layer->getClearClientTarget(displayId) && !firstLayer &&
3226 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3227 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003228 // never clear the very first layer since we're
3229 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003230 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003231 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003232 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003233 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003234 case HWC2::Composition::Client: {
David Sodmanc1498e62018-09-12 14:36:26 -07003235 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003236 break;
3237 }
3238 default:
3239 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003240 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003241 } else {
3242 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003243 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003244 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003245 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003246
Chia-I Wud49d6692018-06-27 07:17:41 +08003247 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003248 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003249 }
3250
Mathias Agopianf45c5102012-10-24 16:29:17 -07003251 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003252 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003253 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003254}
3255
Chia-I Wu28e3a252018-09-07 12:05:02 -07003256void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003257 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003258 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003259}
3260
Dan Stoza7d89d062015-04-30 13:29:25 -07003261status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003262 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003263 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003264 const sp<Layer>& lbc,
3265 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003266{
Dan Stoza7d89d062015-04-30 13:29:25 -07003267 // add this layer to the current state list
3268 {
3269 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003270 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003271 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3272 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003273 return NO_MEMORY;
3274 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003275 if (parent == nullptr) {
3276 mCurrentState.layersSortedByZ.add(lbc);
3277 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003278 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003279 ALOGE("addClientLayer called with a removed parent");
3280 return NAME_NOT_FOUND;
3281 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003282 parent->addChild(lbc);
3283 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003284
Yiwei Zhang243b3782018-05-15 17:40:04 -07003285 if (gbc != nullptr) {
3286 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3287 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3288 mMaxGraphicBufferProducerListSize,
3289 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3290 mGraphicBufferProducerList.size(),
3291 mMaxGraphicBufferProducerListSize, mNumLayers);
3292 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003293 mLayersAdded = true;
3294 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003295 }
3296
Mathias Agopian96f08192010-06-02 23:28:45 -07003297 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003298 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003299
Dan Stoza7d89d062015-04-30 13:29:25 -07003300 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003301}
3302
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003303status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003304 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003305 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3306}
Robert Carr7f9b8992017-03-10 11:08:39 -08003307
chaviwca27f252018-02-06 16:46:39 -08003308status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3309 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003310 if (layer->isPendingRemoval()) {
3311 return NO_ERROR;
3312 }
3313
Robert Carr1f0a16a2016-10-24 16:27:39 -07003314 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003315 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003316 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003317 if (topLevelOnly) {
3318 return NO_ERROR;
3319 }
3320
Chia-I Wu98f1c102017-05-30 14:54:08 -07003321 sp<Layer> ancestor = p;
3322 while (ancestor->getParent() != nullptr) {
3323 ancestor = ancestor->getParent();
3324 }
3325 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3326 ALOGE("removeLayer called with a layer whose parent has been removed");
3327 return NAME_NOT_FOUND;
3328 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003329
3330 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003331 } else {
3332 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003333 }
3334
Robert Carr136e2f62017-02-08 17:54:29 -08003335 // As a matter of normal operation, the LayerCleaner will produce a second
3336 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3337 // so we will succeed in promoting it, but it's already been removed
3338 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3339 // otherwise something has gone wrong and we are leaking the layer.
3340 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003341 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3342 layer->getName().string(),
3343 (p != nullptr) ? p->getName().string() : "no-parent");
3344 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003345 } else if (index < 0) {
3346 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003347 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003348
Chia-I Wuc6657022017-08-15 11:18:17 -07003349 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003350 mLayersPendingRemoval.add(layer);
3351 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003352 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003353 setTransactionFlags(eTransactionNeeded);
3354 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003355}
3356
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003357uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003358 return android_atomic_release_load(&mTransactionFlags);
3359}
3360
Mathias Agopian3f844832013-08-07 21:24:32 -07003361uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003362 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3363}
3364
Mathias Agopian3f844832013-08-07 21:24:32 -07003365uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003366 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3367}
3368
3369uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3370 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003371 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003372 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003373 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003374 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003375 }
3376 return old;
3377}
3378
chaviwca27f252018-02-06 16:46:39 -08003379bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3380 for (const ComposerState& state : states) {
3381 // Here we need to check that the interface we're given is indeed
3382 // one of our own. A malicious client could give us a nullptr
3383 // IInterface, or one of its own or even one of our own but a
3384 // different type. All these situations would cause us to crash.
3385 if (state.client == nullptr) {
3386 return true;
3387 }
3388
3389 sp<IBinder> binder = IInterface::asBinder(state.client);
3390 if (binder == nullptr) {
3391 return true;
3392 }
3393
3394 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3395 return true;
3396 }
3397 }
3398 return false;
3399}
3400
Mathias Agopian8b33f032012-07-24 20:43:54 -07003401void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003402 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003403 const Vector<DisplayState>& displays,
3404 uint32_t flags)
3405{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003406 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003407 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003408 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003409
chaviwca27f252018-02-06 16:46:39 -08003410 if (containsAnyInvalidClientState(states)) {
3411 return;
3412 }
3413
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003414 if (flags & eAnimation) {
3415 // For window updates that are part of an animation we must wait for
3416 // previous animation "frames" to be handled.
3417 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003418 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003419 if (CC_UNLIKELY(err != NO_ERROR)) {
3420 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003421 // caller after a few seconds.
3422 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3423 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003424 mAnimTransactionPending = false;
3425 break;
3426 }
3427 }
3428 }
3429
chaviwca27f252018-02-06 16:46:39 -08003430 for (const DisplayState& display : displays) {
3431 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003432 }
3433
chaviwca27f252018-02-06 16:46:39 -08003434 for (const ComposerState& state : states) {
3435 transactionFlags |= setClientStateLocked(state);
3436 }
3437
3438 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3439 // as destroyed should only occur after setting all other states. This is to allow for a
3440 // child re-parent to happen before marking its original parent as destroyed (which would
3441 // then mark the child as destroyed).
3442 for (const ComposerState& state : states) {
3443 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003444 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003445
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003446 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3447 // anyway. This can be used as a flush mechanism for previous async transactions.
3448 // Empty animation transaction can be used to simulate back-pressure, so also force a
3449 // transaction for empty animation transactions.
3450 if (transactionFlags == 0 &&
3451 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003452 transactionFlags = eTransactionNeeded;
3453 }
3454
Mathias Agopian386aa982011-11-07 21:58:03 -08003455 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003456 if (mInterceptor->isEnabled()) {
3457 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003458 }
Irvel468051e2016-06-13 16:44:44 -07003459
Mathias Agopian386aa982011-11-07 21:58:03 -08003460 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003461 const auto start = (flags & eEarlyWakeup)
3462 ? VSyncModulator::TransactionStart::EARLY
3463 : VSyncModulator::TransactionStart::NORMAL;
3464 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003465
3466 // if this is a synchronous transaction, wait for it to take effect
3467 // before returning.
3468 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003469 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003470 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003471 if (flags & eAnimation) {
3472 mAnimTransactionPending = true;
3473 }
3474 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003475 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3476 if (CC_UNLIKELY(err != NO_ERROR)) {
3477 // just in case something goes wrong in SF, return to the
3478 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003479 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3480 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003481 break;
3482 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003483 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003484 }
3485}
3486
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003487uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3488 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3489 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003490
Mathias Agopiane57f2922012-08-09 16:29:12 -07003491 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003492 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3493
3494 const uint32_t what = s.what;
3495 if (what & DisplayState::eSurfaceChanged) {
3496 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3497 state.surface = s.surface;
3498 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003499 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003500 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003501 if (what & DisplayState::eLayerStackChanged) {
3502 if (state.layerStack != s.layerStack) {
3503 state.layerStack = s.layerStack;
3504 flags |= eDisplayTransactionNeeded;
3505 }
3506 }
3507 if (what & DisplayState::eDisplayProjectionChanged) {
3508 if (state.orientation != s.orientation) {
3509 state.orientation = s.orientation;
3510 flags |= eDisplayTransactionNeeded;
3511 }
3512 if (state.frame != s.frame) {
3513 state.frame = s.frame;
3514 flags |= eDisplayTransactionNeeded;
3515 }
3516 if (state.viewport != s.viewport) {
3517 state.viewport = s.viewport;
3518 flags |= eDisplayTransactionNeeded;
3519 }
3520 }
3521 if (what & DisplayState::eDisplaySizeChanged) {
3522 if (state.width != s.width) {
3523 state.width = s.width;
3524 flags |= eDisplayTransactionNeeded;
3525 }
3526 if (state.height != s.height) {
3527 state.height = s.height;
3528 flags |= eDisplayTransactionNeeded;
3529 }
3530 }
3531
Mathias Agopiane57f2922012-08-09 16:29:12 -07003532 return flags;
3533}
3534
Robert Carrd4ae7f32018-06-07 16:10:57 -07003535bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3536 IPCThreadState* ipc = IPCThreadState::self();
3537 const int pid = ipc->getCallingPid();
3538 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003539 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003540 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003541 return false;
3542 }
3543 return true;
3544}
3545
chaviwca27f252018-02-06 16:46:39 -08003546uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3547 const layer_state_t& s = composerState.state;
3548 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3549
Mathias Agopian13127d82013-03-05 17:47:11 -08003550 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003551 if (layer == nullptr) {
3552 return 0;
3553 }
3554
3555 if (layer->isPendingRemoval()) {
3556 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3557 return 0;
3558 }
3559
3560 uint32_t flags = 0;
3561
3562 const uint32_t what = s.what;
3563 bool geometryAppliesWithResize =
3564 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003565
3566 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3567 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003568 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003569 layer->pushPendingState();
3570 }
3571
chaviw8b3871a2017-11-01 17:41:01 -07003572 if (what & layer_state_t::ePositionChanged) {
3573 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3574 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003575 }
chaviw8b3871a2017-11-01 17:41:01 -07003576 }
3577 if (what & layer_state_t::eLayerChanged) {
3578 // NOTE: index needs to be calculated before we update the state
3579 const auto& p = layer->getParent();
3580 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003581 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003582 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003583 mCurrentState.layersSortedByZ.removeAt(idx);
3584 mCurrentState.layersSortedByZ.add(layer);
3585 // we need traversal (state changed)
3586 // AND transaction (list changed)
3587 flags |= eTransactionNeeded|eTraversalNeeded;
3588 }
chaviw8b3871a2017-11-01 17:41:01 -07003589 } else {
3590 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003591 flags |= eTransactionNeeded|eTraversalNeeded;
3592 }
3593 }
chaviw8b3871a2017-11-01 17:41:01 -07003594 }
3595 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003596 // NOTE: index needs to be calculated before we update the state
3597 const auto& p = layer->getParent();
3598 if (p == nullptr) {
3599 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3600 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3601 mCurrentState.layersSortedByZ.removeAt(idx);
3602 mCurrentState.layersSortedByZ.add(layer);
3603 // we need traversal (state changed)
3604 // AND transaction (list changed)
3605 flags |= eTransactionNeeded|eTraversalNeeded;
3606 }
3607 } else {
3608 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3609 flags |= eTransactionNeeded|eTraversalNeeded;
3610 }
chaviw8b3871a2017-11-01 17:41:01 -07003611 }
3612 }
3613 if (what & layer_state_t::eSizeChanged) {
3614 if (layer->setSize(s.w, s.h)) {
3615 flags |= eTraversalNeeded;
3616 }
3617 }
3618 if (what & layer_state_t::eAlphaChanged) {
3619 if (layer->setAlpha(s.alpha))
3620 flags |= eTraversalNeeded;
3621 }
3622 if (what & layer_state_t::eColorChanged) {
3623 if (layer->setColor(s.color))
3624 flags |= eTraversalNeeded;
3625 }
3626 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003627 // TODO: b/109894387
3628 //
3629 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3630 // rotation. To see the problem observe that if we have a square parent, and a child
3631 // of the same size, then we rotate the child 45 degrees around it's center, the child
3632 // must now be cropped to a non rectangular 8 sided region.
3633 //
3634 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3635 // private API, and the WindowManager only uses rotation in one case, which is on a top
3636 // level layer in which cropping is not an issue.
3637 //
3638 // However given that abuse of rotation matrices could lead to surfaces extending outside
3639 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3640 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3641 // transformations.
3642 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003643 flags |= eTraversalNeeded;
3644 }
3645 if (what & layer_state_t::eTransparentRegionChanged) {
3646 if (layer->setTransparentRegionHint(s.transparentRegion))
3647 flags |= eTraversalNeeded;
3648 }
3649 if (what & layer_state_t::eFlagsChanged) {
3650 if (layer->setFlags(s.flags, s.mask))
3651 flags |= eTraversalNeeded;
3652 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003653 if (what & layer_state_t::eCropChanged_legacy) {
3654 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003655 flags |= eTraversalNeeded;
3656 }
chaviw8b3871a2017-11-01 17:41:01 -07003657 if (what & layer_state_t::eLayerStackChanged) {
3658 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3659 // We only allow setting layer stacks for top level layers,
3660 // everything else inherits layer stack from its parent.
3661 if (layer->hasParent()) {
3662 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3663 layer->getName().string());
3664 } else if (idx < 0) {
3665 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3666 "that also does not appear in the top level layer list. Something"
3667 " has gone wrong.", layer->getName().string());
3668 } else if (layer->setLayerStack(s.layerStack)) {
3669 mCurrentState.layersSortedByZ.removeAt(idx);
3670 mCurrentState.layersSortedByZ.add(layer);
3671 // we need traversal (state changed)
3672 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003673 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003674 }
3675 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003676 if (what & layer_state_t::eDeferTransaction_legacy) {
3677 if (s.barrierHandle_legacy != nullptr) {
3678 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3679 } else if (s.barrierGbp_legacy != nullptr) {
3680 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003681 if (authenticateSurfaceTextureLocked(gbp)) {
3682 const auto& otherLayer =
3683 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003684 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003685 } else {
3686 ALOGE("Attempt to defer transaction to to an"
3687 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003688 }
3689 }
chaviw8b3871a2017-11-01 17:41:01 -07003690 // We don't trigger a traversal here because if no other state is
3691 // changed, we don't want this to cause any more work
3692 }
3693 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003694 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003695 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003696 if (!hadParent) {
3697 mCurrentState.layersSortedByZ.remove(layer);
3698 }
chaviw8b3871a2017-11-01 17:41:01 -07003699 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003700 }
chaviw8b3871a2017-11-01 17:41:01 -07003701 }
3702 if (what & layer_state_t::eReparentChildren) {
3703 if (layer->reparentChildren(s.reparentHandle)) {
3704 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003705 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003706 }
chaviw8b3871a2017-11-01 17:41:01 -07003707 if (what & layer_state_t::eDetachChildren) {
3708 layer->detachChildren();
3709 }
3710 if (what & layer_state_t::eOverrideScalingModeChanged) {
3711 layer->setOverrideScalingMode(s.overrideScalingMode);
3712 // We don't trigger a traversal here because if no other state is
3713 // changed, we don't want this to cause any more work
3714 }
Marissa Wall61c58622018-07-18 10:12:20 -07003715 if (what & layer_state_t::eTransformChanged) {
3716 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3717 }
3718 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3719 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3720 flags |= eTraversalNeeded;
3721 }
3722 if (what & layer_state_t::eCropChanged) {
3723 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3724 }
3725 if (what & layer_state_t::eBufferChanged) {
3726 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3727 }
3728 if (what & layer_state_t::eAcquireFenceChanged) {
3729 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3730 }
3731 if (what & layer_state_t::eDataspaceChanged) {
3732 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3733 }
3734 if (what & layer_state_t::eHdrMetadataChanged) {
3735 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3736 }
3737 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3738 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3739 }
3740 if (what & layer_state_t::eApiChanged) {
3741 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3742 }
3743 if (what & layer_state_t::eSidebandStreamChanged) {
3744 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3745 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003746 return flags;
3747}
3748
chaviwca27f252018-02-06 16:46:39 -08003749void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3750 const layer_state_t& state = composerState.state;
3751 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3752
3753 sp<Layer> layer(client->getLayerUser(state.surface));
3754 if (layer == nullptr) {
3755 return;
3756 }
3757
3758 if (layer->isPendingRemoval()) {
3759 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3760 return;
3761 }
3762
3763 if (state.what & layer_state_t::eDestroySurface) {
3764 removeLayerLocked(mStateLock, layer);
3765 }
3766}
3767
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003768status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003769 const String8& name,
3770 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003771 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003772 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003773 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003774{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003775 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003776 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003777 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003778 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003779 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003780
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003781 status_t result = NO_ERROR;
3782
3783 sp<Layer> layer;
3784
Cody Northropbc755282017-03-31 12:00:08 -06003785 String8 uniqueName = getUniqueLayerName(name);
3786
Mathias Agopian3165cc22012-08-08 19:42:09 -07003787 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003788 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003789 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3790 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003791
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003792 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003793 case ISurfaceComposerClient::eFXSurfaceBufferState:
3794 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3795 break;
chaviw13fdc492017-06-27 12:40:18 -07003796 case ISurfaceComposerClient::eFXSurfaceColor:
3797 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003798 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003799 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003800 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003801 case ISurfaceComposerClient::eFXSurfaceContainer:
3802 result = createContainerLayer(client,
3803 uniqueName, w, h, flags,
3804 handle, &layer);
3805 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003806 default:
3807 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003808 break;
3809 }
3810
Dan Stoza7d89d062015-04-30 13:29:25 -07003811 if (result != NO_ERROR) {
3812 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003813 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003814
Chia-I Wuab0c3192017-08-01 11:29:00 -07003815 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3816 // TODO b/64227542
3817 if (windowType == 441731) {
3818 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3819 layer->setPrimaryDisplayOnly();
3820 }
3821
Albert Chaulk479c60c2017-01-27 14:21:34 -05003822 layer->setInfo(windowType, ownerUid);
3823
Robert Carr1f0a16a2016-10-24 16:27:39 -07003824 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003825 if (result != NO_ERROR) {
3826 return result;
3827 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003828 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003829
3830 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003831 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003832}
3833
Cody Northropbc755282017-03-31 12:00:08 -06003834String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3835{
3836 bool matchFound = true;
3837 uint32_t dupeCounter = 0;
3838
3839 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3840 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3841
Dan Stoza436ccf32018-06-21 12:10:12 -07003842 // Grab the state lock since we're accessing mCurrentState
3843 Mutex::Autolock lock(mStateLock);
3844
Cody Northropbc755282017-03-31 12:00:08 -06003845 // Loop over layers until we're sure there is no matching name
3846 while (matchFound) {
3847 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003848 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003849 if (layer->getName() == uniqueName) {
3850 matchFound = true;
3851 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3852 }
3853 });
3854 }
3855
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003856 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3857 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003858
3859 return uniqueName;
3860}
3861
Marissa Wallfd668622018-05-10 10:21:13 -07003862status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3863 uint32_t w, uint32_t h, uint32_t flags,
3864 PixelFormat& format, sp<IBinder>* handle,
3865 sp<IGraphicBufferProducer>* gbp,
3866 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003867 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003868 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003869 case PIXEL_FORMAT_TRANSPARENT:
3870 case PIXEL_FORMAT_TRANSLUCENT:
3871 format = PIXEL_FORMAT_RGBA_8888;
3872 break;
3873 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003874 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003875 break;
3876 }
3877
Marissa Wallfd668622018-05-10 10:21:13 -07003878 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3879 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003880 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003881 *handle = layer->getHandle();
3882 *gbp = layer->getProducer();
3883 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003884 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003885
Marissa Wallfd668622018-05-10 10:21:13 -07003886 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003887 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003888}
3889
Marissa Wall61c58622018-07-18 10:12:20 -07003890status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3891 uint32_t w, uint32_t h, uint32_t flags,
3892 sp<IBinder>* handle, sp<Layer>* outLayer) {
3893 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3894 *handle = layer->getHandle();
3895 *outLayer = layer;
3896
3897 return NO_ERROR;
3898}
3899
chaviw13fdc492017-06-27 12:40:18 -07003900status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003901 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003902 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003903{
chaviw13fdc492017-06-27 12:40:18 -07003904 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003905 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003906 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003907}
3908
Robert Carr6b3f6c52018-08-13 13:05:17 -07003909status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3910 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3911 sp<IBinder>* handle, sp<Layer>* outLayer)
3912{
3913 *outLayer = new ContainerLayer(this, client, name, w, h, flags);
3914 *handle = (*outLayer)->getHandle();
3915 return NO_ERROR;
3916}
3917
3918
Mathias Agopianac9fa422013-02-11 16:40:36 -08003919status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003920{
Robert Carr9524cb32017-02-13 11:32:32 -08003921 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003922 status_t err = NO_ERROR;
3923 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003924 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003925 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003926 err = removeLayer(l);
3927 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3928 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003929 }
3930 return err;
3931}
3932
Mathias Agopian13127d82013-03-05 17:47:11 -08003933status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003934{
Mathias Agopian67106042013-03-14 19:18:13 -07003935 // called by ~LayerCleaner() when all references to the IBinder (handle)
3936 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003937 sp<Layer> l = layer.promote();
3938 if (l == nullptr) {
3939 // The layer has already been removed, carry on
3940 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003941 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003942 // If we have a parent, then we can continue to live as long as it does.
3943 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003944}
3945
Mathias Agopianb60314a2012-04-10 22:09:54 -07003946// ---------------------------------------------------------------------------
3947
Andy McFadden13a082e2012-08-24 10:16:42 -07003948void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003949 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3950 if (!displayToken) return;
3951
Jesse Hall01e29052013-02-19 16:13:35 -08003952 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003953 Vector<ComposerState> state;
3954 Vector<DisplayState> displays;
3955 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003956 d.what = DisplayState::eDisplayProjectionChanged |
3957 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003958 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003959 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003960 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003961 d.frame.makeInvalid();
3962 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003963 d.width = 0;
3964 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003965 displays.add(d);
3966 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003967
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003968 const auto display = getDisplayDevice(displayToken);
3969 if (!display) return;
3970
3971 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3972
3973 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003974 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003975 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003976
Brian Andersond0010582017-03-07 13:20:31 -08003977 // Use phase of 0 since phase is not known.
3978 // Use latency of 0, which will snap to the ideal latency.
3979 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003980}
3981
3982void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003983 // Async since we may be called from the main thread.
3984 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003985}
3986
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003987void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3988 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003989 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003990 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003991
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003992 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003993 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003994 return;
3995 }
3996
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003997 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003998 ALOGW("Trying to set power mode for virtual display");
3999 return;
4000 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004001
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004002 display->setPowerMode(mode);
4003
Lloyd Pique4dccc412018-01-22 17:21:36 -08004004 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07004005 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004006 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07004007 if (idx < 0) {
4008 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
4009 return;
4010 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07004011 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07004012 }
4013
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004014 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004015 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004016 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004017 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004018 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004019 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004020 if (mUseScheduler) {
4021 mScheduler->onScreenAcquired(mAppConnectionHandle);
4022 } else {
4023 mEventThread->onScreenAcquired();
4024 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07004025 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004026 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004027
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004028 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004029 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004030 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004031
4032 struct sched_param param = {0};
4033 param.sched_priority = 1;
4034 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4035 ALOGW("Couldn't set SCHED_FIFO on display on");
4036 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004037 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004038 // Turn off the display
4039 struct sched_param param = {0};
4040 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4041 ALOGW("Couldn't set SCHED_OTHER on display off");
4042 }
4043
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004044 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07004045 disableHardwareVsync(true); // also cancels any in-progress resync
4046
Mathias Agopiancde87a32012-09-13 14:09:01 -07004047 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004048 if (mUseScheduler) {
4049 mScheduler->onScreenReleased(mAppConnectionHandle);
4050 } else {
4051 mEventThread->onScreenReleased();
4052 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004053 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004054
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004055 getHwComposer().setPowerMode(type, mode);
4056 mVisibleRegionsDirty = true;
4057 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004058 } else if (mode == HWC_POWER_MODE_DOZE ||
4059 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004060 // Update display while dozing
4061 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004062 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004063 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004064 if (mUseScheduler) {
4065 mScheduler->onScreenAcquired(mAppConnectionHandle);
4066 } else {
4067 mEventThread->onScreenAcquired();
4068 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004069 resyncToHardwareVsync(true);
4070 }
4071 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4072 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004073 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004074 disableHardwareVsync(true); // also cancels any in-progress resync
4075 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004076 if (mUseScheduler) {
4077 mScheduler->onScreenReleased(mAppConnectionHandle);
4078 } else {
4079 mEventThread->onScreenReleased();
4080 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004081 }
4082 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004083 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004084 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004085 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004086 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004087
4088 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004089}
4090
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004091void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004092 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004093 const auto display = getDisplayDevice(displayToken);
4094 if (!display) {
4095 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4096 displayToken.get());
4097 } else if (display->isVirtual()) {
4098 ALOGW("Attempt to set power mode %d for virtual display", mode);
4099 } else {
4100 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004101 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004102 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004103}
4104
4105// ---------------------------------------------------------------------------
4106
Lloyd Pique755e3192018-01-31 16:46:15 -08004107status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4108 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004109 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004110
Mathias Agopianbd115332013-04-18 16:41:04 -07004111 IPCThreadState* ipc = IPCThreadState::self();
4112 const int pid = ipc->getCallingPid();
4113 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004114
Mathias Agopianbd115332013-04-18 16:41:04 -07004115 if ((uid != AID_SHELL) &&
4116 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004117 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07004118 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004119 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004120 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004121 // (this would indicate SF is stuck, but we want to be able to
4122 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004123 status_t err = mStateLock.timedLock(s2ns(1));
4124 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004125 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004126 result.appendFormat(
4127 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4128 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004129 }
4130
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004131 bool dumpAll = true;
4132 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004133 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004134
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004135 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004136 if ((index < numArgs) &&
4137 (args[index] == String16("--list"))) {
4138 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004139 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004140 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004141 }
4142
4143 if ((index < numArgs) &&
4144 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004145 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004146 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004147 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004148 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004149
4150 if ((index < numArgs) &&
4151 (args[index] == String16("--latency-clear"))) {
4152 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004153 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004154 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004155 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004156
4157 if ((index < numArgs) &&
4158 (args[index] == String16("--dispsync"))) {
4159 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004160 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004161 dumpAll = false;
4162 }
Dan Stozab90cf072015-03-05 11:05:59 -08004163
4164 if ((index < numArgs) &&
4165 (args[index] == String16("--static-screen"))) {
4166 index++;
4167 dumpStaticScreenStats(result);
4168 dumpAll = false;
4169 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004170
4171 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004172 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004173 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004174 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004175 dumpAll = false;
4176 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004177
4178 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4179 index++;
4180 dumpWideColorInfo(result);
4181 dumpAll = false;
4182 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004183
4184 if ((index < numArgs) &&
4185 (args[index] == String16("--enable-layer-stats"))) {
4186 index++;
4187 mLayerStats.enable();
4188 dumpAll = false;
4189 }
4190
4191 if ((index < numArgs) &&
4192 (args[index] == String16("--disable-layer-stats"))) {
4193 index++;
4194 mLayerStats.disable();
4195 dumpAll = false;
4196 }
4197
4198 if ((index < numArgs) &&
4199 (args[index] == String16("--clear-layer-stats"))) {
4200 index++;
4201 mLayerStats.clear();
4202 dumpAll = false;
4203 }
4204
4205 if ((index < numArgs) &&
4206 (args[index] == String16("--dump-layer-stats"))) {
4207 index++;
4208 mLayerStats.dump(result);
4209 dumpAll = false;
4210 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004211
4212 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004213 (args[index] == String16("--frame-composition"))) {
4214 index++;
4215 dumpFrameCompositionInfo(result);
4216 dumpAll = false;
4217 }
4218
4219 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004220 (args[index] == String16("--display-identification"))) {
4221 index++;
4222 dumpDisplayIdentificationData(result);
4223 dumpAll = false;
4224 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004225
4226 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4227 index++;
4228 mTimeStats.parseArgs(asProto, args, index, result);
4229 dumpAll = false;
4230 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004231 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004232
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004233 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004234 if (asProto) {
4235 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4236 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4237 } else {
4238 dumpAllLocked(args, index, result);
4239 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004240 }
4241
Mathias Agopian9795c422009-08-26 16:36:26 -07004242 if (locked) {
4243 mStateLock.unlock();
4244 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004245 }
4246 write(fd, result.string(), result.size());
4247 return NO_ERROR;
4248}
4249
Dan Stozac7014012014-02-14 15:03:43 -08004250void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4251 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004252{
Robert Carr2047fae2016-11-28 14:09:09 -08004253 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004254 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004255 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004256}
4257
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004258void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004259 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004260{
4261 String8 name;
4262 if (index < args.size()) {
4263 name = String8(args[index]);
4264 index++;
4265 }
4266
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004267 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4268 getHwComposer().isConnected(displayId)) {
4269 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4270 const nsecs_t period = activeConfig->getVsyncPeriod();
4271 result.appendFormat("%" PRId64 "\n", period);
4272 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004273
4274 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004275 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004276 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004277 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004278 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004279 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004280 }
Robert Carr2047fae2016-11-28 14:09:09 -08004281 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004282 }
4283}
4284
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004285void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004286 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004287{
4288 String8 name;
4289 if (index < args.size()) {
4290 name = String8(args[index]);
4291 index++;
4292 }
4293
Robert Carr2047fae2016-11-28 14:09:09 -08004294 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004295 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004296 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004297 }
Robert Carr2047fae2016-11-28 14:09:09 -08004298 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004299
Svetoslavd85084b2014-03-20 10:28:31 -07004300 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004301}
4302
Jamie Gennis6547ff42013-07-16 20:12:42 -07004303// This should only be called from the main thread. Otherwise it would need
4304// the lock and should use mCurrentState rather than mDrawingState.
4305void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004306 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004307 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004308 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004309
4310 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4311}
4312
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004313void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004314{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004315 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004316
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004317 if (isLayerTripleBufferingDisabled())
4318 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004319
4320 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004321 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004322 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004323 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004324 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4325 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004326 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004327}
4328
Dan Stozab90cf072015-03-05 11:05:59 -08004329void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4330{
4331 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004332 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4333 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004334 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004335 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004336 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4337 b + 1, bucketTimeSec, percent);
4338 }
David Sodman4a36e932017-11-07 14:29:47 -08004339 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004340 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004341 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004342 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004343 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004344}
4345
Dan Stozae77c7662016-05-13 11:37:28 -07004346void SurfaceFlinger::recordBufferingStats(const char* layerName,
4347 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004348 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4349 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004350 for (const auto& segment : history) {
4351 if (!segment.usedThirdBuffer) {
4352 stats.twoBufferTime += segment.totalTime;
4353 }
4354 if (segment.occupancyAverage < 1.0f) {
4355 stats.doubleBufferedTime += segment.totalTime;
4356 } else if (segment.occupancyAverage < 2.0f) {
4357 stats.tripleBufferedTime += segment.totalTime;
4358 }
4359 ++stats.numSegments;
4360 stats.totalTime += segment.totalTime;
4361 }
4362}
4363
Brian Andersond6927fb2016-07-23 23:37:30 -07004364void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4365 result.appendFormat("Layer frame timestamps:\n");
4366
4367 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4368 const size_t count = currentLayers.size();
4369 for (size_t i=0 ; i<count ; i++) {
4370 currentLayers[i]->dumpFrameEvents(result);
4371 }
4372}
4373
Dan Stozae77c7662016-05-13 11:37:28 -07004374void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4375 result.append("Buffering stats:\n");
4376 result.append(" [Layer name] <Active time> <Two buffer> "
4377 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004378 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004379 typedef std::tuple<std::string, float, float, float> BufferTuple;
4380 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004381 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004382 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004383 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004384 if (stats.numSegments == 0) {
4385 continue;
4386 }
4387 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4388 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4389 stats.totalTime;
4390 float doubleBufferRatio = static_cast<float>(
4391 stats.doubleBufferedTime) / stats.totalTime;
4392 float tripleBufferRatio = static_cast<float>(
4393 stats.tripleBufferedTime) / stats.totalTime;
4394 sorted.insert({activeTime, {name, twoBufferRatio,
4395 doubleBufferRatio, tripleBufferRatio}});
4396 }
4397 for (const auto& sortedPair : sorted) {
4398 float activeTime = sortedPair.first;
4399 const BufferTuple& values = sortedPair.second;
4400 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4401 std::get<0>(values).c_str(), activeTime,
4402 std::get<1>(values), std::get<2>(values),
4403 std::get<3>(values));
4404 }
4405 result.append("\n");
4406}
4407
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004408void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004409 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004410 const int32_t displayId = display->getId();
4411 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4412 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004413 continue;
4414 }
4415
Dominik Laskowski7e045462018-05-30 13:02:02 -07004416 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004417 uint8_t port;
4418 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004419 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004420 result.append("no identification data\n");
4421 continue;
4422 }
4423
4424 if (!isEdid(data)) {
4425 result.append("unknown identification data: ");
4426 for (uint8_t byte : data) {
4427 result.appendFormat("%x ", byte);
4428 }
4429 result.append("\n");
4430 continue;
4431 }
4432
4433 const auto edid = parseEdid(data);
4434 if (!edid) {
4435 result.append("invalid EDID: ");
4436 for (uint8_t byte : data) {
4437 result.appendFormat("%x ", byte);
4438 }
4439 result.append("\n");
4440 continue;
4441 }
4442
4443 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4444 result.append(edid->displayName.data(), edid->displayName.length());
4445 result.append("\"\n");
4446 }
4447 result.append("\n");
4448}
4449
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004450void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004451 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4452 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004453 result.appendFormat("DisplayColorSetting: %s\n",
4454 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004455
4456 // TODO: print out if wide-color mode is active or not
4457
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004458 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004459 const int32_t displayId = display->getId();
4460 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004461 continue;
4462 }
4463
Dominik Laskowski7e045462018-05-30 13:02:02 -07004464 result.appendFormat("Display %d color modes:\n", displayId);
4465 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004466 for (auto&& mode : modes) {
4467 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4468 }
4469
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004470 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004471 result.appendFormat(" Current color mode: %s (%d)\n",
4472 decodeColorMode(currentMode).c_str(), currentMode);
4473 }
4474 result.append("\n");
4475}
4476
David Sodman7e4ae112018-02-09 15:02:28 -08004477void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4478 std::string stringResult;
4479
4480 for (const auto& [token, display] : mDisplays) {
4481 const auto displayId = display->getId();
4482 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
4483 continue;
4484 }
4485
4486 const auto& compositionInfoIt = getBE().mEndOfFrameCompositionInfo.find(displayId);
4487 if (compositionInfoIt == getBE().mEndOfFrameCompositionInfo.end()) {
4488 break;
4489 }
4490 const auto& compositionInfoList = compositionInfoIt->second;
4491 stringResult += base::StringPrintf("Display: %d\n", displayId);
4492 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4493 for (const auto& compositionInfo : compositionInfoList) {
4494 compositionInfo.dump(stringResult, nullptr);
4495 stringResult += base::StringPrintf("\n");
4496 }
4497 }
4498
4499 result.append(stringResult.c_str());
4500}
4501
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004502LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004503 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004504 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4505 const State& state = useDrawing ? mDrawingState : mCurrentState;
4506 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004507 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004508 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004509 });
4510
4511 return layersProto;
4512}
4513
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004514LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004515 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004516
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004517 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004518 resolution->set_w(display.getWidth());
4519 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004520
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004521 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4522 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4523 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004524
Dominik Laskowski7e045462018-05-30 13:02:02 -07004525 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004526 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004527 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004528 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004529 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004530 }
4531 });
4532
4533 return layersProto;
4534}
4535
Mathias Agopian74d211a2013-04-22 16:55:35 +02004536void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4537 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004538{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004539 bool colorize = false;
4540 if (index < args.size()
4541 && (args[index] == String16("--color"))) {
4542 colorize = true;
4543 index++;
4544 }
4545
4546 Colorizer colorizer(colorize);
4547
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004548 // figure out if we're stuck somewhere
4549 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004550 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004551 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4552
4553 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004554 * Dump library configuration.
4555 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004556
4557 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004558 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004559 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004560 appendSfConfigString(result);
4561 appendUiConfigString(result);
4562 appendGuiConfigString(result);
4563 result.append("\n");
4564
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004565 result.append("\nDisplay identification data:\n");
4566 dumpDisplayIdentificationData(result);
4567
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004568 result.append("\nWide-Color information:\n");
4569 dumpWideColorInfo(result);
4570
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004571 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004572 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004573 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004574 result.append(SyncFeatures::getInstance().toString());
4575 result.append("\n");
4576
Andy McFadden41d67d72014-04-25 16:58:34 -07004577 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004578 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004579 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004580
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004581 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4582 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004583 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4584 getHwComposer().isConnected(displayId)) {
4585 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004586 result.appendFormat("Display %d: "
4587 "app phase %" PRId64 " ns, "
4588 "sf phase %" PRId64 " ns, "
4589 "early app phase %" PRId64 " ns, "
4590 "early sf phase %" PRId64 " ns, "
4591 "early app gl phase %" PRId64 " ns, "
4592 "early sf gl phase %" PRId64 " ns, "
4593 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4594 displayId,
4595 vsyncPhaseOffsetNs,
4596 sfVsyncPhaseOffsetNs,
4597 appEarlyOffset,
4598 sfEarlyOffset,
4599 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004600 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004601 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004602 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004603 result.append("\n");
4604
Dan Stozab90cf072015-03-05 11:05:59 -08004605 // Dump static screen stats
4606 result.append("\n");
4607 dumpStaticScreenStats(result);
4608 result.append("\n");
4609
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004610 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4611
Dan Stozae77c7662016-05-13 11:37:28 -07004612 dumpBufferingStats(result);
4613
Andy McFadden4803b742012-09-24 19:07:20 -07004614 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004615 * Dump the visible layer list
4616 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004617 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004618 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004619 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4620 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004621 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004622
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004623 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004624 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004625 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004626 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004627
David Sodman7e4ae112018-02-09 15:02:28 -08004628 result.append("\nFrame-Composition information:\n");
4629 dumpFrameCompositionInfo(result);
4630 result.append("\n");
4631
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004632 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004633 * Dump Display state
4634 */
4635
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004636 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004637 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004638 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004639 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004640 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004641 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004642 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004643
4644 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004645 * Dump SurfaceFlinger global state
4646 */
4647
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004648 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004649 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004650 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004651
Mathias Agopian888c8222012-08-04 21:10:38 -07004652 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004653 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004654
David Sodmanbc815282017-11-05 18:57:52 -08004655 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004656
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004657 if (display) {
4658 display->undefinedRegion.dump(result, "undefinedRegion");
4659 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4660 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004661 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004662 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004663 " gpu_to_cpu_unsupported : %d\n",
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004664 mTransactionFlags, !mGpuToCpuSupported);
4665
4666 if (display) {
4667 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4668 result.appendFormat(" refresh-rate : %f fps\n"
4669 " x-dpi : %f\n"
4670 " y-dpi : %f\n",
4671 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4672 activeConfig->getDpiY());
4673 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004674
Mathias Agopian74d211a2013-04-22 16:55:35 +02004675 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004676 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004677
Ana Krulec98b5b242018-08-10 15:03:23 -07004678 result.appendFormat(" use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004679 /*
4680 * VSYNC state
4681 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004682 if (mUseScheduler) {
4683 mScheduler->dump(mAppConnectionHandle, result);
4684 } else {
4685 mEventThread->dump(result);
4686 }
Dan Stozae22aec72016-08-01 13:20:59 -07004687 result.append("\n");
4688
4689 /*
4690 * HWC layer minidump
4691 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004692 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004693 const int32_t displayId = display->getId();
4694 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004695 continue;
4696 }
4697
Dominik Laskowski7e045462018-05-30 13:02:02 -07004698 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004699 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004700 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004701 result.append("\n");
4702 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004703
4704 /*
4705 * Dump HWComposer state
4706 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004707 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004708 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004709 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004710 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004711 result.appendFormat(" h/w composer %s\n",
4712 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004713 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004714
4715 /*
4716 * Dump gralloc state
4717 */
4718 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4719 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004720
4721 /*
4722 * Dump VrFlinger state if in use.
4723 */
4724 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4725 result.append("VrFlinger state:\n");
4726 result.append(mVrFlinger->Dump().c_str());
4727 result.append("\n");
4728 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004729}
4730
Dominik Laskowski7e045462018-05-30 13:02:02 -07004731const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004732 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004733 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004734 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004735 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004736 }
4737 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004738
4739 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4740 static const Vector<sp<Layer>> empty;
4741 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004742}
4743
Keun young Park63f165f2012-08-31 10:53:36 -07004744bool SurfaceFlinger::startDdmConnection()
4745{
4746 void* libddmconnection_dso =
4747 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4748 if (!libddmconnection_dso) {
4749 return false;
4750 }
4751 void (*DdmConnection_start)(const char* name);
4752 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004753 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004754 if (!DdmConnection_start) {
4755 dlclose(libddmconnection_dso);
4756 return false;
4757 }
4758 (*DdmConnection_start)(getServiceName());
4759 return true;
4760}
4761
Chia-I Wu28f320b2018-05-03 11:02:56 -07004762void SurfaceFlinger::updateColorMatrixLocked() {
4763 mat4 colorMatrix;
4764 if (mGlobalSaturationFactor != 1.0f) {
4765 // Rec.709 luma coefficients
4766 float3 luminance{0.213f, 0.715f, 0.072f};
4767 luminance *= 1.0f - mGlobalSaturationFactor;
4768 mat4 saturationMatrix = mat4(
4769 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4770 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4771 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4772 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4773 );
4774 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4775 } else {
4776 colorMatrix = mClientColorMatrix * mDaltonizer();
4777 }
4778
4779 if (mCurrentState.colorMatrix != colorMatrix) {
4780 mCurrentState.colorMatrix = colorMatrix;
4781 mCurrentState.colorMatrixChanged = true;
4782 setTransactionFlags(eTransactionNeeded);
4783 }
4784}
4785
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004786status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004787#pragma clang diagnostic push
4788#pragma clang diagnostic error "-Wswitch-enum"
4789 switch (static_cast<ISurfaceComposerTag>(code)) {
4790 // These methods should at minimum make sure that the client requested
4791 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004792 case BOOT_FINISHED:
4793 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004794 case CREATE_CONNECTION:
4795 case CREATE_DISPLAY:
4796 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004797 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004798 case GET_ACTIVE_COLOR_MODE:
4799 case GET_ANIMATION_FRAME_STATS:
4800 case GET_HDR_CAPABILITIES:
4801 case SET_ACTIVE_CONFIG:
4802 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004803 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004804 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004805 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4806 IPCThreadState* ipc = IPCThreadState::self();
4807 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4808 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004809 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004810 }
Robert Carr1db73f62016-12-21 12:58:51 -08004811 return OK;
4812 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004813 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004814 IPCThreadState* ipc = IPCThreadState::self();
4815 const int pid = ipc->getCallingPid();
4816 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004817 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4818 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004819 return PERMISSION_DENIED;
4820 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004821 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004822 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004823 // Used by apps to hook Choreographer to SurfaceFlinger.
4824 case CREATE_DISPLAY_EVENT_CONNECTION:
4825 // The following calls are currently used by clients that do not
4826 // request necessary permissions. However, they do not expose any secret
4827 // information, so it is OK to pass them.
4828 case AUTHENTICATE_SURFACE:
4829 case GET_ACTIVE_CONFIG:
4830 case GET_BUILT_IN_DISPLAY:
4831 case GET_DISPLAY_COLOR_MODES:
4832 case GET_DISPLAY_CONFIGS:
4833 case GET_DISPLAY_STATS:
4834 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4835 // Calling setTransactionState is safe, because you need to have been
4836 // granted a reference to Client* and Handle* to do anything with it.
4837 case SET_TRANSACTION_STATE:
4838 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004839 case CREATE_SCOPED_CONNECTION:
4840 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004841 return OK;
4842 }
4843 case CAPTURE_LAYERS:
4844 case CAPTURE_SCREEN: {
4845 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004846 IPCThreadState* ipc = IPCThreadState::self();
4847 const int pid = ipc->getCallingPid();
4848 const int uid = ipc->getCallingUid();
4849 if ((uid != AID_GRAPHICS) &&
4850 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4851 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4852 return PERMISSION_DENIED;
4853 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004854 return OK;
4855 }
4856 // The following codes are deprecated and should never be allowed to access SF.
4857 case CONNECT_DISPLAY_UNUSED:
4858 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4859 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4860 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004861 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004862 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004863
4864 // These codes are used for the IBinder protocol to either interrogate the recipient
4865 // side of the transaction for its canonical interface descriptor or to dump its state.
4866 // We let them pass by default.
4867 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4868 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4869 code == IBinder::SYSPROPS_TRANSACTION) {
4870 return OK;
4871 }
4872 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4873 // in onTransact verifies that the user is root, and has access to use SF.
4874 if (code >= 1000 && code <= 1029) {
4875 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4876 return OK;
4877 }
4878 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4879 return PERMISSION_DENIED;
4880#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004881}
4882
Ana Krulec13be8ad2018-08-21 02:43:56 +00004883status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4884 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004885 status_t credentialCheck = CheckTransactCodeCredentials(code);
4886 if (credentialCheck != OK) {
4887 return credentialCheck;
4888 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004889
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004890 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4891 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004892 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004893 IPCThreadState* ipc = IPCThreadState::self();
4894 const int uid = ipc->getCallingUid();
4895 if (CC_UNLIKELY(uid != AID_SYSTEM
4896 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004897 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004898 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004899 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004900 return PERMISSION_DENIED;
4901 }
4902 int n;
4903 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004904 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004905 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004906 return NO_ERROR;
4907 case 1002: // SHOW_UPDATES
4908 n = data.readInt32();
4909 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004910 invalidateHwcGeometry();
4911 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004912 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004913 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004914 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004915 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004916 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004917 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004918 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004919 setTransactionFlags(
4920 eTransactionNeeded|
4921 eDisplayTransactionNeeded|
4922 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004923 return NO_ERROR;
4924 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004925 case 1006:{ // send empty update
4926 signalRefresh();
4927 return NO_ERROR;
4928 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004929 case 1008: // toggle use of hw composer
4930 n = data.readInt32();
4931 mDebugDisableHWC = n ? 1 : 0;
4932 invalidateHwcGeometry();
4933 repaintEverything();
4934 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004935 case 1009: // toggle use of transform hint
4936 n = data.readInt32();
4937 mDebugDisableTransformHint = n ? 1 : 0;
4938 invalidateHwcGeometry();
4939 repaintEverything();
4940 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004941 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004942 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004943 reply->writeInt32(0);
4944 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004945 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004946 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004947 return NO_ERROR;
4948 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004949 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004950 if (!display) {
4951 return NAME_NOT_FOUND;
4952 }
4953
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004954 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004955 return NO_ERROR;
4956 }
4957 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004958 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004959 // daltonize
4960 n = data.readInt32();
4961 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004962 case 1:
4963 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4964 break;
4965 case 2:
4966 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4967 break;
4968 case 3:
4969 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4970 break;
4971 default:
4972 mDaltonizer.setType(ColorBlindnessType::None);
4973 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004974 }
4975 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004976 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004977 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004978 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004979 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004980
4981 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004982 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004983 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004984 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004985 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004986 // apply a color matrix
4987 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004988 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004989 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004990 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004991 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004992 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004993 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004994 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004995 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004996 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004997 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004998
4999 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5000 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005001 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005002 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5003 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5004 }
5005
Chia-I Wu28f320b2018-05-03 11:02:56 -07005006 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005007 return NO_ERROR;
5008 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005009 // This is an experimental interface
5010 // Needs to be shifted to proper binder interface when we productize
5011 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005012 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07005013 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005014 return NO_ERROR;
5015 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005016 case 1017: {
5017 n = data.readInt32();
5018 mForceFullDamage = static_cast<bool>(n);
5019 return NO_ERROR;
5020 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005021 case 1018: { // Modify Choreographer's phase offset
5022 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005023 if (mUseScheduler) {
5024 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5025 } else {
5026 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5027 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005028 return NO_ERROR;
5029 }
5030 case 1019: { // Modify SurfaceFlinger's phase offset
5031 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005032 if (mUseScheduler) {
5033 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5034 } else {
5035 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5036 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005037 return NO_ERROR;
5038 }
Irvel468051e2016-06-13 16:44:44 -07005039 case 1020: { // Layer updates interceptor
5040 n = data.readInt32();
5041 if (n) {
5042 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005043 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005044 }
5045 else{
5046 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005047 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005048 }
5049 return NO_ERROR;
5050 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005051 case 1021: { // Disable HWC virtual displays
5052 n = data.readInt32();
5053 mUseHwcVirtualDisplays = !n;
5054 return NO_ERROR;
5055 }
Romain Guy0147a172017-06-01 13:53:56 -07005056 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005057 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005058 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005059
Chia-I Wu28f320b2018-05-03 11:02:56 -07005060 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005061 return NO_ERROR;
5062 }
Romain Guy54f154a2017-10-24 21:40:32 +01005063 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005064 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005065 invalidateHwcGeometry();
5066 repaintEverything();
5067 return NO_ERROR;
5068 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005069 // TODO(b/111505327): Find out whether the usage of 1024 can switch to 1030,
5070 // deprecate 1024 if they can.
5071 case 1024: { // Does device have wide color gamut display?
Romain Guy54f154a2017-10-24 21:40:32 +01005072 reply->writeBool(hasWideColorDisplay);
5073 return NO_ERROR;
5074 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005075 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005076 n = data.readInt32();
5077 if (n) {
5078 ALOGV("LayerTracing enabled");
5079 mTracing.enable();
5080 doTracing("tracing.enable");
5081 reply->writeInt32(NO_ERROR);
5082 } else {
5083 ALOGV("LayerTracing disabled");
5084 status_t err = mTracing.disable();
5085 reply->writeInt32(err);
5086 }
5087 return NO_ERROR;
5088 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005089 case 1026: { // Get layer tracing status
5090 reply->writeBool(mTracing.isEnabled());
5091 return NO_ERROR;
5092 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005093 // Is a DisplayColorSetting supported?
5094 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005095 const auto display = getDefaultDisplayDevice();
5096 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005097 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005098 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005099
5100 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5101 switch (setting) {
5102 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005103 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005104 break;
5105 case DisplayColorSetting::UNMANAGED:
5106 reply->writeBool(true);
5107 break;
5108 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005109 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005110 break;
5111 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005112 reply->writeBool(
5113 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005114 break;
5115 }
5116 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005117 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005118 // Is VrFlinger active?
5119 case 1028: {
5120 Mutex::Autolock _l(mStateLock);
5121 reply->writeBool(getBE().mHwc->isUsingVrComposer());
5122 return NO_ERROR;
5123 }
David Sodman6d46c1e2018-07-13 12:59:48 -07005124 case 1029: {
5125 // Code 1029 is an experimental feature that allows applications to
5126 // simulate a high frequency panel by setting a multiplier and divisor
5127 // on the VSYNC-sf clock. If either the multiplier or divisor are
David Sodman44b5de02018-08-21 16:28:53 -07005128 // 0, then the code simply return the current multiplier and divisor.
5129 HWC2::Device::FrequencyScaler frequencyScaler;
5130 frequencyScaler.multiplier = data.readInt32();
5131 frequencyScaler.divisor = data.readInt32();
David Sodman6d46c1e2018-07-13 12:59:48 -07005132
David Sodman44b5de02018-08-21 16:28:53 -07005133 if ((frequencyScaler.multiplier == 0) || (frequencyScaler.divisor == 0)) {
5134 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5135 reply->writeInt32(frequencyScaler.multiplier);
5136 reply->writeInt32(frequencyScaler.divisor);
5137 return NO_ERROR;
David Sodman6d46c1e2018-07-13 12:59:48 -07005138 }
5139
David Sodman44b5de02018-08-21 16:28:53 -07005140 if ((frequencyScaler.multiplier == 1) && (frequencyScaler.divisor == 1)) {
David Sodman6d46c1e2018-07-13 12:59:48 -07005141 enableHardwareVsync();
5142 } else {
5143 disableHardwareVsync(true);
5144 }
David Sodman44b5de02018-08-21 16:28:53 -07005145 mPrimaryDispSync->scalePeriod(frequencyScaler);
5146 getBE().mHwc->setDisplayFrequencyScaleParameters(frequencyScaler);
David Sodman6d46c1e2018-07-13 12:59:48 -07005147
David Sodman44b5de02018-08-21 16:28:53 -07005148 ATRACE_INT("PeriodMultiplier", frequencyScaler.multiplier);
5149 ATRACE_INT("PeriodDivisor", frequencyScaler.divisor);
5150
5151 const hwc2_display_t hwcDisplayId = getBE().mHwc->getActiveConfig(
5152 DisplayDevice::DISPLAY_PRIMARY)->getDisplayId();
5153
5154 onHotplugReceived(getBE().mComposerSequenceId,
5155 hwcDisplayId, HWC2::Connection::Disconnected);
5156 onHotplugReceived(getBE().mComposerSequenceId,
5157 hwcDisplayId, HWC2::Connection::Connected);
5158 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5159 reply->writeInt32(frequencyScaler.multiplier);
5160 reply->writeInt32(frequencyScaler.divisor);
5161
David Sodman6d46c1e2018-07-13 12:59:48 -07005162 return NO_ERROR;
5163 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005164 // Is device color managed?
5165 case 1030: {
5166 reply->writeBool(useColorManagement);
5167 return NO_ERROR;
5168 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005169 }
5170 }
5171 return err;
5172}
5173
Steven Thomas6d8110b2017-08-31 18:24:21 -07005174void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07005175 android_atomic_or(1, &mRepaintEverything);
5176 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005177}
5178
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005179// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5180class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005181public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005182 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5183 ~WindowDisconnector() {
5184 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005185 }
5186
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005187private:
5188 ANativeWindow* mWindow;
5189 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005190};
5191
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005192status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
5193 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
5194 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
5195 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005196 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005197 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005198
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005199 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005200
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005201 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5202
Chia-I Wu20261cb2018-08-23 12:55:44 -07005203 sp<DisplayDevice> display;
5204 {
5205 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005206
Chia-I Wu20261cb2018-08-23 12:55:44 -07005207 display = getDisplayDeviceLocked(displayToken);
5208 if (!display) return BAD_VALUE;
5209
Chia-I Wu8730ba82018-08-29 09:25:59 -07005210 // ignore sourceCrop (i.e., use the projected logical display
5211 // viewport) until the framework is fixed
5212 sourceCrop.clear();
Chia-I Wucb023152018-08-28 12:57:23 -07005213
5214 // set the requested width/height to the logical display viewport size
5215 // by default
5216 if (reqWidth == 0 || reqHeight == 0) {
5217 reqWidth = uint32_t(display->getViewport().width());
5218 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005219 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005220 }
5221
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005222 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005223
5224 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005225 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005226 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005227}
5228
5229status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08005230 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005231 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005232 ATRACE_CALL();
5233
5234 class LayerRenderArea : public RenderArea {
5235 public:
Robert Carr578038f2018-03-09 12:25:24 -08005236 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
5237 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
Chia-I Wu9d1abea2018-08-23 13:44:43 -07005238 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08005239 mLayer(layer),
5240 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005241 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005242 mFlinger(flinger),
5243 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005244 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005245 Rect getBounds() const override {
5246 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005247 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005248 }
Marissa Wall61c58622018-07-18 10:12:20 -07005249 int getHeight() const override {
5250 return mLayer->getActiveHeight(mLayer->getDrawingState());
5251 }
5252 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005253 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005254 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005255 Rect getSourceCrop() const override {
5256 if (mCrop.isEmpty()) {
5257 return getBounds();
5258 } else {
5259 return mCrop;
5260 }
5261 }
Robert Carr578038f2018-03-09 12:25:24 -08005262 class ReparentForDrawing {
5263 public:
5264 const sp<Layer>& oldParent;
5265 const sp<Layer>& newParent;
5266
5267 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5268 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005269 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005270 }
Robert Carr15eae092018-03-23 13:43:53 -07005271 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005272 };
5273
5274 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005275 const Rect sourceCrop = getSourceCrop();
5276 // no need to check rotation because there is none
5277 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5278 sourceCrop.height() != getReqHeight();
5279
Robert Carr578038f2018-03-09 12:25:24 -08005280 if (!mChildrenOnly) {
5281 mTransform = mLayer->getTransform().inverse();
5282 drawLayers();
5283 } else {
5284 Rect bounds = getBounds();
5285 screenshotParentLayer =
5286 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
5287 bounds.getWidth(), bounds.getHeight(), 0);
5288
5289 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5290 drawLayers();
5291 }
5292 }
chaviwa76b2712017-09-20 12:02:26 -07005293
chaviwa76b2712017-09-20 12:02:26 -07005294 private:
chaviw7206d492017-11-10 16:16:12 -08005295 const sp<Layer> mLayer;
5296 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005297
5298 // In the "childrenOnly" case we reparent the children to a screenshot
5299 // layer which has no properties set and which does not draw.
5300 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005301 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005302 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005303
5304 SurfaceFlinger* mFlinger;
5305 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005306 };
5307
5308 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5309 auto parent = layerHandle->owner.promote();
5310
chaviw7206d492017-11-10 16:16:12 -08005311 if (parent == nullptr || parent->isPendingRemoval()) {
5312 ALOGE("captureLayers called with a removed parent");
5313 return NAME_NOT_FOUND;
5314 }
5315
Robert Carr578038f2018-03-09 12:25:24 -08005316 const int uid = IPCThreadState::self()->getCallingUid();
5317 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5318 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5319 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5320 return PERMISSION_DENIED;
5321 }
5322
chaviw7206d492017-11-10 16:16:12 -08005323 Rect crop(sourceCrop);
5324 if (sourceCrop.width() <= 0) {
5325 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005326 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005327 }
5328
5329 if (sourceCrop.height() <= 0) {
5330 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005331 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005332 }
5333
5334 int32_t reqWidth = crop.width() * frameScale;
5335 int32_t reqHeight = crop.height() * frameScale;
5336
Chia-I Wu20261cb2018-08-23 12:55:44 -07005337 // really small crop or frameScale
5338 if (reqWidth <= 0) {
5339 reqWidth = 1;
5340 }
5341 if (reqHeight <= 0) {
5342 reqHeight = 1;
5343 }
5344
Robert Carr578038f2018-03-09 12:25:24 -08005345 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005346
Robert Carr578038f2018-03-09 12:25:24 -08005347 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005348 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5349 if (!layer->isVisible()) {
5350 return;
Robert Carr578038f2018-03-09 12:25:24 -08005351 } else if (childrenOnly && layer == parent.get()) {
5352 return;
chaviwa76b2712017-09-20 12:02:26 -07005353 }
5354 visitor(layer);
5355 });
5356 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005357 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005358}
5359
5360status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5361 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005362 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005363 bool useIdentityTransform) {
5364 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005365
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005366 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5367 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5368 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5369 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005370
5371 // This mutex protects syncFd and captureResult for communication of the return values from the
5372 // main thread back to this Binder thread
5373 std::mutex captureMutex;
5374 std::condition_variable captureCondition;
5375 std::unique_lock<std::mutex> captureLock(captureMutex);
5376 int syncFd = -1;
5377 std::optional<status_t> captureResult;
5378
Robert Carr03480e22018-01-04 16:02:06 -08005379 const int uid = IPCThreadState::self()->getCallingUid();
5380 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5381
Dominik Laskowski8c001672018-05-30 16:52:06 -07005382 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005383 // If there is a refresh pending, bug out early and tell the binder thread to try again
5384 // after the refresh.
5385 if (mRefreshPending) {
5386 ATRACE_NAME("Skipping screenshot for now");
5387 std::unique_lock<std::mutex> captureLock(captureMutex);
5388 captureResult = std::make_optional<status_t>(EAGAIN);
5389 captureCondition.notify_one();
5390 return;
5391 }
5392
5393 status_t result = NO_ERROR;
5394 int fd = -1;
5395 {
5396 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005397 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005398 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5399 useIdentityTransform, forSystem, &fd);
5400 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005401 }
5402
5403 {
5404 std::unique_lock<std::mutex> captureLock(captureMutex);
5405 syncFd = fd;
5406 captureResult = std::make_optional<status_t>(result);
5407 captureCondition.notify_one();
5408 }
5409 });
5410
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005411 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005412 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005413 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005414 while (*captureResult == EAGAIN) {
5415 captureResult.reset();
5416 result = postMessageAsync(message);
5417 if (result != NO_ERROR) {
5418 return result;
5419 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005420 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005421 }
5422 result = *captureResult;
5423 }
5424
5425 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005426 sync_wait(syncFd, -1);
5427 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005428 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005429
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005430 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005431}
5432
chaviwa76b2712017-09-20 12:02:26 -07005433void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005434 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005435 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005436 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005437
Lloyd Pique144e1162017-12-20 16:44:52 -08005438 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005439
chaviwa76b2712017-09-20 12:02:26 -07005440 const auto reqWidth = renderArea.getReqWidth();
5441 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005442 const auto sourceCrop = renderArea.getSourceCrop();
5443 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005444
Chia-I Wu36574d92018-05-16 10:54:36 -07005445 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5446 engine.setOutputDataSpace(Dataspace::SRGB);
5447 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005448
Mathias Agopian180f10d2013-04-10 22:55:41 -07005449 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005450 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005451
5452 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005453 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005454 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005455
chaviw50da5042018-04-09 13:49:37 -07005456 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005457 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005458 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005459
chaviwa76b2712017-09-20 12:02:26 -07005460 traverseLayers([&](Layer* layer) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08005461 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005462 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005463}
5464
chaviwa76b2712017-09-20 12:02:26 -07005465status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5466 TraverseLayersFunction traverseLayers,
5467 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005468 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005469 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005470 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005471 ATRACE_CALL();
5472
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005473 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005474
5475 traverseLayers([&](Layer* layer) {
5476 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5477 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005478
Robert Carr03480e22018-01-04 16:02:06 -08005479 // We allow the system server to take screenshots of secure layers for
5480 // use in situations like the Screen-rotation animation and place
5481 // the impetus on WindowManager to not persist them.
5482 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005483 ALOGW("FB is protected: PERMISSION_DENIED");
5484 return PERMISSION_DENIED;
5485 }
5486
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005487 // this binds the given EGLImage as a framebuffer for the
5488 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005489 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005490 if (bufferBond.getStatus() != NO_ERROR) {
5491 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005492 return INVALID_OPERATION;
5493 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005494
Dan Stozaabcda352017-06-01 14:37:39 -07005495 // this will in fact render into our dequeued buffer
5496 // via an FBO, which means we didn't have to create
5497 // an EGLSurface and therefore we're not
5498 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005499 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005500
Alec Mouri492bc572018-09-11 21:40:04 +00005501 base::unique_fd syncFd = getRenderEngine().flush();
5502 if (syncFd < 0) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005503 getRenderEngine().finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005504 }
Alec Mouri492bc572018-09-11 21:40:04 +00005505 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005506
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005507 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005508}
5509
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005510// ---------------------------------------------------------------------------
5511
Dan Stoza412903f2017-04-27 13:42:17 -07005512void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5513 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005514}
5515
Dan Stoza412903f2017-04-27 13:42:17 -07005516void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5517 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005518}
5519
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005520void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5521 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005522 const LayerVector::Visitor& visitor) {
5523 // We loop through the first level of layers without traversing,
5524 // as we need to interpret min/max layer Z in the top level Z space.
5525 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005526 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005527 continue;
5528 }
5529 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005530 // relative layers are traversed in Layer::traverseInZOrder
5531 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005532 continue;
5533 }
5534 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005535 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005536 return;
5537 }
chaviwa76b2712017-09-20 12:02:26 -07005538 if (!layer->isVisible()) {
5539 return;
5540 }
5541 visitor(layer);
5542 });
5543 }
5544}
5545
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005546}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005547
Lloyd Pique074e8122018-07-26 12:57:23 -07005548
Mathias Agopian3f844832013-08-07 21:24:32 -07005549#if defined(__gl_h_)
5550#error "don't include gl/gl.h in this file"
5551#endif
5552
5553#if defined(__gl2_h_)
5554#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005555#endif