blob: dbf2f30df608064d41938ad809ddc20e7caec080 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Chia-I Wud49d6692018-06-27 07:17:41 +080040#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060041#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070043#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080048#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070050
51#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Robert Carr578038f2018-03-09 12:25:24 -080065#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070066#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070067#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020070#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080072#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080073#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Steven Thomasb02664d2017-07-26 18:48:28 -070079#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070080#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070084#include "Effects/Daltonizer.h"
Mathias Agopian875d8e12013-06-07 15:35:48 -070085#include "RenderEngine/RenderEngine.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070086#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070087#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070088#include "Scheduler/EventControlThread.h"
89#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070090#include "Scheduler/InjectVSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070091
Mathias Agopianff2ed702013-09-01 21:36:12 -070092#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070093
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
Mathias Agopianfee2b462013-07-03 12:34:01 -0700106/*
107 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
108 * black pixels.
109 */
110#define DEBUG_SCREENSHOTS false
111
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800112namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700113
Jaesoo Lee43518572017-01-23 19:03:16 +0900114using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900115using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700116using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700117using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700118using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700119using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900120
Steven Thomasb02664d2017-07-26 18:48:28 -0700121namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700122
123#pragma clang diagnostic push
124#pragma clang diagnostic error "-Wswitch-enum"
125
126bool isWideColorMode(const ColorMode colorMode) {
127 switch (colorMode) {
128 case ColorMode::DISPLAY_P3:
129 case ColorMode::ADOBE_RGB:
130 case ColorMode::DCI_P3:
131 case ColorMode::BT2020:
132 case ColorMode::BT2100_PQ:
133 case ColorMode::BT2100_HLG:
134 return true;
135 case ColorMode::NATIVE:
136 case ColorMode::STANDARD_BT601_625:
137 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
138 case ColorMode::STANDARD_BT601_525:
139 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
140 case ColorMode::STANDARD_BT709:
141 case ColorMode::SRGB:
142 return false;
143 }
144 return false;
145}
146
147#pragma clang diagnostic pop
148
Steven Thomasb02664d2017-07-26 18:48:28 -0700149class ConditionalLock {
150public:
151 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
152 if (lock) {
153 mMutex.lock();
154 }
155 }
156 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
157private:
158 Mutex& mMutex;
159 bool mLocked;
160};
Peiyong Linfca547f2018-07-09 13:03:33 -0700161
Steven Thomasb02664d2017-07-26 18:48:28 -0700162} // namespace anonymous
163
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800164// ---------------------------------------------------------------------------
165
Mathias Agopian99b49842011-06-27 16:05:52 -0700166const String16 sHardwareTest("android.permission.HARDWARE_TEST");
167const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
168const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
169const String16 sDump("android.permission.DUMP");
170
171// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800172int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
173int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700174int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700175bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800176uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800177bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800178bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800179int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800180// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600181bool SurfaceFlinger::hasWideColorDisplay;
Peiyong Lin13effd12018-07-24 17:01:47 -0700182bool SurfaceFlinger::useColorManagement;
Mathias Agopian99b49842011-06-27 16:05:52 -0700183
Kalle Raitaa099a242017-01-11 11:17:29 -0800184
185std::string getHwcServiceName() {
186 char value[PROPERTY_VALUE_MAX] = {};
187 property_get("debug.sf.hwc_service_name", value, "default");
188 ALOGI("Using HWComposer service: '%s'", value);
189 return std::string(value);
190}
191
192bool useTrebleTestingOverride() {
193 char value[PROPERTY_VALUE_MAX] = {};
194 property_get("debug.sf.treble_testing_override", value, "false");
195 ALOGI("Treble testing override: '%s'", value);
196 return std::string(value) == "true";
197}
198
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800199std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
200 switch(displayColorSetting) {
201 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700202 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800203 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700204 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800205 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700206 return std::string("Enhanced");
207 default:
208 return std::string("Unknown ") +
209 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800210 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800211}
212
Lloyd Pique99d3da52018-01-22 17:48:03 -0800213NativeWindowSurface::~NativeWindowSurface() = default;
214
215namespace impl {
216
217class NativeWindowSurface final : public android::NativeWindowSurface {
218public:
219 static std::unique_ptr<android::NativeWindowSurface> create(
220 const sp<IGraphicBufferProducer>& producer) {
221 return std::make_unique<NativeWindowSurface>(producer);
222 }
223
224 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
225 : surface(new Surface(producer, false)) {}
226
227 ~NativeWindowSurface() override = default;
228
229private:
230 sp<ANativeWindow> getNativeWindow() const override { return surface; }
231
232 void preallocateBuffers() override { surface->allocateBuffers(); }
233
234 sp<Surface> surface;
235};
236
237} // namespace impl
238
David Sodmanbc815282017-11-05 18:57:52 -0800239SurfaceFlingerBE::SurfaceFlingerBE()
240 : mHwcServiceName(getHwcServiceName()),
241 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800242 mFrameBuckets(),
243 mTotalTime(0),
244 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800245 mComposerSequenceId(0) {
246}
247
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800248SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800249 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800250 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700251 mTransactionPending(false),
252 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700253 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700254 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700255 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800256 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700257 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800258 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800259 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800260 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800261 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800262 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700263 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700264 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700265 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700266 mDebugInTransaction(0),
267 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700268 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700269 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700270 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800271 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800272 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800273 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700274 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800275 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800276 mCreateBufferQueue(&BufferQueue::createBufferQueue),
277 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800278
279SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800280 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800281
282 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
283 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
284
285 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
286 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
287
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800288 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
289 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800290
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700291 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
292 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
293
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700294 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
295 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
296
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800297 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
298 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
299
Steven Thomas050b2c82017-03-06 11:45:16 -0800300 // Vr flinger is only enabled on Daydream ready devices.
301 useVrFlinger = getBool< ISurfaceFlingerConfigs,
302 &ISurfaceFlingerConfigs::useVrFlinger>(false);
303
Fabien Sanglard1971b632017-03-10 14:50:03 -0800304 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
305 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
306
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600307 hasWideColorDisplay =
308 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700309 useColorManagement =
310 getBool<V1_2::ISurfaceFlingerConfigs, &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600311
Iris Chang7501ed62018-04-30 14:45:42 +0800312 V1_1::DisplayOrientation primaryDisplayOrientation =
313 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
314 V1_1::DisplayOrientation::ORIENTATION_0);
315
316 switch (primaryDisplayOrientation) {
317 case V1_1::DisplayOrientation::ORIENTATION_90:
318 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
319 break;
320 case V1_1::DisplayOrientation::ORIENTATION_180:
321 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
322 break;
323 case V1_1::DisplayOrientation::ORIENTATION_270:
324 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
325 break;
326 default:
327 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
328 break;
329 }
330 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
331
Lloyd Pique41be5d22018-06-21 13:11:48 -0700332 // Note: We create a local temporary with the real DispSync implementation
333 // type temporarily so we can initialize it with the configured values,
334 // before storing it for more generic use using the interface type.
335 auto primaryDispSync = std::make_unique<impl::DispSync>("PrimaryDispSync");
336 primaryDispSync->init(SurfaceFlinger::hasSyncFramework,
337 SurfaceFlinger::dispSyncPresentTimeOffset);
338 mPrimaryDispSync = std::move(primaryDispSync);
Saurabh Shahf4174532017-07-13 10:45:07 -0700339
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800340 // debugging stuff...
341 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700342
Mathias Agopianb4b17302013-03-20 18:36:41 -0700343 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700344 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700345
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800346 property_get("debug.sf.showupdates", value, "0");
347 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700348
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700349 property_get("debug.sf.ddms", value, "0");
350 mDebugDDMS = atoi(value);
351 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700352 if (!startDdmConnection()) {
353 // start failed, and DDMS debugging not enabled
354 mDebugDDMS = 0;
355 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700356 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700357 ALOGI_IF(mDebugRegion, "showupdates enabled");
358 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700359
360 property_get("debug.sf.disable_backpressure", value, "0");
361 mPropagateBackpressure = !atoi(value);
362 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700363
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800364 property_get("debug.sf.enable_hwc_vds", value, "0");
365 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800366 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800367
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800368 property_get("ro.sf.disable_triple_buffer", value, "1");
369 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800370 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700371
Yiwei Zhang243b3782018-05-15 17:40:04 -0700372 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700373 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
374 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
375
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200376 property_get("debug.sf.early_phase_offset_ns", value, "-1");
377 const int earlySfOffsetNs = atoi(value);
378
379 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
380 const int earlyGlSfOffsetNs = atoi(value);
381
382 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
383 const int earlyAppOffsetNs = atoi(value);
384
385 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
386 const int earlyGlAppOffsetNs = atoi(value);
387
388 const VSyncModulator::Offsets earlyOffsets =
389 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
390 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
391 const VSyncModulator::Offsets earlyGlOffsets =
392 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
393 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
394 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
395 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700396
Romain Guy11d63f42017-07-20 12:47:14 -0700397 // We should be reading 'persist.sys.sf.color_saturation' here
398 // but since /data may be encrypted, we need to wait until after vold
399 // comes online to attempt to read the property. The property is
400 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800401
402 if (useTrebleTestingOverride()) {
403 // Without the override SurfaceFlinger cannot connect to HIDL
404 // services that are not listed in the manifests. Considered
405 // deriving the setting from the set service name, but it
406 // would be brittle if the name that's not 'default' is used
407 // for production purposes later on.
408 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
409 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800410}
411
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800412void SurfaceFlinger::onFirstRef()
413{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800414 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800415}
416
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800417SurfaceFlinger::~SurfaceFlinger()
418{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800419}
420
Dan Stozac7014012014-02-14 15:03:43 -0800421void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800422{
423 // the window manager died on us. prepare its eulogy.
424
Andy McFadden13a082e2012-08-24 10:16:42 -0700425 // restore initial conditions (default device unblank, etc)
426 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800427
428 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700429 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800430}
431
Robert Carr1db73f62016-12-21 12:58:51 -0800432static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700433 status_t err = client->initCheck();
434 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800435 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800436 }
Robert Carr1db73f62016-12-21 12:58:51 -0800437 return nullptr;
438}
439
440sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
441 return initClient(new Client(this));
442}
443
444sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
445 const sp<IGraphicBufferProducer>& gbp) {
446 if (authenticateSurfaceTexture(gbp) == false) {
447 return nullptr;
448 }
449 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
450 if (layer == nullptr) {
451 return nullptr;
452 }
453
454 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800455}
456
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700457sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
458 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700459{
460 class DisplayToken : public BBinder {
461 sp<SurfaceFlinger> flinger;
462 virtual ~DisplayToken() {
463 // no more references, this display must be terminated
464 Mutex::Autolock _l(flinger->mStateLock);
465 flinger->mCurrentState.displays.removeItem(this);
466 flinger->setTransactionFlags(eDisplayTransactionNeeded);
467 }
468 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700469 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700470 : flinger(flinger) {
471 }
472 };
473
474 sp<BBinder> token = new DisplayToken(this);
475
476 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700477 DisplayDeviceState info;
478 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700479 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700480 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700481 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800482 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700483 return token;
484}
485
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700486void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700487 Mutex::Autolock _l(mStateLock);
488
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700489 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700490 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700491 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700492 return;
493 }
494
495 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700496 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700497 ALOGE("destroyDisplay called for non-virtual display");
498 return;
499 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700500 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700501 mCurrentState.displays.removeItemsAt(idx);
502 setTransactionFlags(eDisplayTransactionNeeded);
503}
504
Mathias Agopiane57f2922012-08-09 16:29:12 -0700505sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700506 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700507 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800508 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700509 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700510 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700511}
512
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800513void SurfaceFlinger::bootFinished()
514{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700515 if (mStartPropertySetThread->join() != NO_ERROR) {
516 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800517 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800518 const nsecs_t now = systemTime();
519 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000520 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700521
522 // wait patiently for the window manager death
523 const String16 name("window");
524 sp<IBinder> window(defaultServiceManager()->getService(name));
525 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700526 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700527 }
528
Steven Thomas050b2c82017-03-06 11:45:16 -0800529 if (mVrFlinger) {
530 mVrFlinger->OnBootFinished();
531 }
532
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700533 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700534 // formerly we would just kill the process, but we now ask it to exit so it
535 // can choose where to stop the animation.
536 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700537
538 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
539 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
540 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700541
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800542 postMessageAsync(new LambdaMessage([this] {
543 readPersistentProperties();
544 mBootStage = BootStage::FINISHED;
545 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800546}
547
Dan Stoza436ccf32018-06-21 12:10:12 -0700548uint32_t SurfaceFlinger::getNewTexture() {
549 {
550 std::lock_guard lock(mTexturePoolMutex);
551 if (!mTexturePool.empty()) {
552 uint32_t name = mTexturePool.back();
553 mTexturePool.pop_back();
554 ATRACE_INT("TexturePoolSize", mTexturePool.size());
555 return name;
556 }
557
558 // The pool was too small, so increase it for the future
559 ++mTexturePoolSize;
560 }
561
562 // The pool was empty, so we need to get a new texture name directly using a
563 // blocking call to the main thread
564 uint32_t name = 0;
565 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
566 return name;
567}
568
Mathias Agopian3f844832013-08-07 21:24:32 -0700569void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700570 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700571}
572
Wei Wangf9b05ee2017-07-19 20:59:39 -0700573// Do not call property_set on main thread which will be blocked by init
574// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700575void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700576 ALOGI( "SurfaceFlinger's main thread ready to run. "
577 "Initializing graphics H/W...");
578
Thierry Strudel2924d012017-08-14 15:19:37 -0700579 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900580
Steven Thomasb02664d2017-07-26 18:48:28 -0700581 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800582
Steven Thomasb02664d2017-07-26 18:48:28 -0700583 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800584 mEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700585 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
586 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800587 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700588 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800589 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800590 "appEventThread");
591 mSfEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700592 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800593 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800594
Lloyd Pique24b0a482018-03-09 18:52:26 -0800595 mSFEventThread =
596 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700597 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800598 [this](nsecs_t timestamp) {
599 mInterceptor->saveVSyncEvent(timestamp);
600 },
601 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800602 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200603 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800604
Steven Thomasb02664d2017-07-26 18:48:28 -0700605 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700606 int32_t renderEngineFeature = 0;
607 renderEngineFeature |= (useColorManagement ? RE::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Lloyd Pique144e1162017-12-20 16:44:52 -0800608 getBE().mRenderEngine =
Peiyong Lin13effd12018-07-24 17:01:47 -0700609 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888, renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800610 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700611
612 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
613 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800614 getBE().mHwc.reset(
615 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700616 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800617 // Process any initial hotplug and resulting display changes.
618 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700619 const auto display = getDefaultDisplayDeviceLocked();
620 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
621 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
622 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800623
Lloyd Piquefcd86612017-12-14 17:15:36 -0800624 // make the default display GLContext current so that we can create textures
625 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700626 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800627
Steven Thomas050b2c82017-03-06 11:45:16 -0800628 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700629 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700630 // This callback is called from the vr flinger dispatch thread. We
631 // need to call signalTransaction(), which requires holding
632 // mStateLock when we're not on the main thread. Acquiring
633 // mStateLock from the vr flinger dispatch thread might trigger a
634 // deadlock in surface flinger (see b/66916578), so post a message
635 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700636 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700637 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
638 mVrFlingerRequestsDisplay = requestDisplay;
639 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700640 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800641 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700642 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
643 getHwComposer()
644 .getHwcDisplayId(display->getId())
645 .value_or(0),
646 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800647 if (!mVrFlinger) {
648 ALOGE("Failed to start vrflinger");
649 }
650 }
651
Lloyd Pique379adc12018-01-22 17:31:47 -0800652 mEventControlThread = std::make_unique<impl::EventControlThread>(
653 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700654
Mathias Agopian92a979a2012-08-02 18:32:23 -0700655 // initialize our drawing state
656 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700657
Andy McFadden13a082e2012-08-24 10:16:42 -0700658 // set initial conditions (e.g. unblank default device)
659 initializeDisplays();
660
David Sodmanbc815282017-11-05 18:57:52 -0800661 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700662
Wei Wangf9b05ee2017-07-19 20:59:39 -0700663 // Inform native graphics APIs whether the present timestamp is supported:
664 if (getHwComposer().hasCapability(
665 HWC2::Capability::PresentFenceIsNotReliable)) {
666 mStartPropertySetThread = new StartPropertySetThread(false);
667 } else {
668 mStartPropertySetThread = new StartPropertySetThread(true);
669 }
670
671 if (mStartPropertySetThread->Start() != NO_ERROR) {
672 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800673 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800674
Chia-I Wud49d6692018-06-27 07:17:41 +0800675 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
676 // is used to saturate legacy sRGB content. However, to make sure the same color under
677 // Display P3 will be saturated to the same color, we intentionally break the API spec
678 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
679 // such saturation matrix on Display P3 is understood fully, the API should always return
680 // identify matrix.
681 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
682 Dataspace::SRGB_LINEAR);
683
684 // we will apply this on Display P3.
685 if (mEnhancedSaturationMatrix != mat4()) {
686 ColorSpace srgb(ColorSpace::sRGB());
687 ColorSpace displayP3(ColorSpace::DisplayP3());
688 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
689 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
690 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
691 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800692
Dan Stoza9e56aa02015-11-02 13:00:03 -0800693 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700694}
695
Romain Guy11d63f42017-07-20 12:47:14 -0700696void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700697 Mutex::Autolock _l(mStateLock);
698
Romain Guy11d63f42017-07-20 12:47:14 -0700699 char value[PROPERTY_VALUE_MAX];
700
701 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800702 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700703 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800704 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100705
706 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700707 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700708}
709
Mathias Agopiana67e4182012-06-19 17:26:12 -0700710void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800711 // Start boot animation service by setting a property mailbox
712 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700713 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800714 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700715 if (mStartPropertySetThread->join() != NO_ERROR) {
716 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800717 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700718}
719
Mathias Agopian875d8e12013-06-07 15:35:48 -0700720size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800721 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700722}
723
Mathias Agopian875d8e12013-06-07 15:35:48 -0700724size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800725 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700726}
727
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800728// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800729
Jamie Gennis582270d2011-08-17 18:19:00 -0700730bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800731 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800732 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800733 return authenticateSurfaceTextureLocked(bufferProducer);
734}
735
736bool SurfaceFlinger::authenticateSurfaceTextureLocked(
737 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800738 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800739 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800740}
741
Brian Anderson6b376712017-04-04 10:51:39 -0700742status_t SurfaceFlinger::getSupportedFrameTimestamps(
743 std::vector<FrameEvent>* outSupported) const {
744 *outSupported = {
745 FrameEvent::REQUESTED_PRESENT,
746 FrameEvent::ACQUIRE,
747 FrameEvent::LATCH,
748 FrameEvent::FIRST_REFRESH_START,
749 FrameEvent::LAST_REFRESH_START,
750 FrameEvent::GPU_COMPOSITION_DONE,
751 FrameEvent::DEQUEUE_READY,
752 FrameEvent::RELEASE,
753 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700754 ConditionalLock _l(mStateLock,
755 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700756 if (!getHwComposer().hasCapability(
757 HWC2::Capability::PresentFenceIsNotReliable)) {
758 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
759 }
760 return NO_ERROR;
761}
762
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700763status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
764 Vector<DisplayInfo>* configs) {
765 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700766 return BAD_VALUE;
767 }
768
Jesse Hall692c7232012-11-08 15:41:56 -0800769 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700770 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
771 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700772 type = i;
773 break;
774 }
775 }
776
777 if (type < 0) {
778 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700779 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700780
Mathias Agopian8b736f12012-08-13 17:54:26 -0700781 // TODO: Not sure if display density should handled by SF any longer
782 class Density {
783 static int getDensityFromProperty(char const* propName) {
784 char property[PROPERTY_VALUE_MAX];
785 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800786 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700787 density = atoi(property);
788 }
789 return density;
790 }
791 public:
792 static int getEmuDensity() {
793 return getDensityFromProperty("qemu.sf.lcd_density"); }
794 static int getBuildDensity() {
795 return getDensityFromProperty("ro.sf.lcd_density"); }
796 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700797
Dan Stoza7f7da322014-05-02 15:26:25 -0700798 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700799
Steven Thomas6d8110b2017-08-31 18:24:21 -0700800 ConditionalLock _l(mStateLock,
801 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800802 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700803 DisplayInfo info = DisplayInfo();
804
Dan Stoza9e56aa02015-11-02 13:00:03 -0800805 float xdpi = hwConfig->getDpiX();
806 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700807
808 if (type == DisplayDevice::DISPLAY_PRIMARY) {
809 // The density of the device is provided by a build property
810 float density = Density::getBuildDensity() / 160.0f;
811 if (density == 0) {
812 // the build doesn't provide a density -- this is wrong!
813 // use xdpi instead
814 ALOGE("ro.sf.lcd_density must be defined as a build property");
815 density = xdpi / 160.0f;
816 }
817 if (Density::getEmuDensity()) {
818 // if "qemu.sf.lcd_density" is specified, it overrides everything
819 xdpi = ydpi = density = Density::getEmuDensity();
820 density /= 160.0f;
821 }
822 info.density = density;
823
824 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700825 const auto display = getDefaultDisplayDeviceLocked();
826 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700827 } else {
828 // TODO: where should this value come from?
829 static const int TV_DENSITY = 213;
830 info.density = TV_DENSITY / 160.0f;
831 info.orientation = 0;
832 }
833
Dan Stoza9e56aa02015-11-02 13:00:03 -0800834 info.w = hwConfig->getWidth();
835 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700836 info.xdpi = xdpi;
837 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800838 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900839 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800840
Andy McFadden91b2ca82014-06-13 14:04:23 -0700841 // This is how far in advance a buffer must be queued for
842 // presentation at a given time. If you want a buffer to appear
843 // on the screen at time N, you must submit the buffer before
844 // (N - presentationDeadline).
845 //
846 // Normally it's one full refresh period (to give SF a chance to
847 // latch the buffer), but this can be reduced by configuring a
848 // DispSync offset. Any additional delays introduced by the hardware
849 // composer or panel must be accounted for here.
850 //
851 // We add an additional 1ms to allow for processing time and
852 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800853 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800854 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700855
856 // All non-virtual displays are currently considered secure.
857 info.secure = true;
858
Iris Chang7501ed62018-04-30 14:45:42 +0800859 if (type == DisplayDevice::DISPLAY_PRIMARY &&
860 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
861 std::swap(info.w, info.h);
862 }
863
Michael Wright28f24d02016-07-12 13:30:53 -0700864 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700865 }
866
Dan Stoza7f7da322014-05-02 15:26:25 -0700867 return NO_ERROR;
868}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700869
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700870status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
871 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700872 return BAD_VALUE;
873 }
874
875 // FIXME for now we always return stats for the primary display
876 memset(stats, 0, sizeof(*stats));
Lloyd Pique41be5d22018-06-21 13:11:48 -0700877 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
878 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700879 return NO_ERROR;
880}
881
Yiwei Zhangcd3f9e92018-08-21 15:15:42 -0700882status_t SurfaceFlinger::getDisplayViewport(const sp<IBinder>& display, Rect* outViewport) {
883 if (outViewport == nullptr || display.get() == nullptr) {
884 return BAD_VALUE;
885 }
886
887 sp<const DisplayDevice> device(getDisplayDevice(display));
888 if (device == nullptr) {
889 return BAD_VALUE;
890 }
891
892 *outViewport = device->getViewport();
893
894 return NO_ERROR;
895}
896
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700897int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
898 const auto display = getDisplayDevice(displayToken);
899 if (!display) {
900 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800901 return BAD_VALUE;
902 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700903
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700904 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700905}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700906
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700907void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
908 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700909 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700910 return;
911 }
912
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700913 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700914 ALOGW("Trying to set config for virtual display");
915 return;
916 }
917
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700918 display->setActiveConfig(mode);
919 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700920}
921
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700922status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700923 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700924 Vector<DisplayInfo> configs;
925 getDisplayConfigs(displayToken, &configs);
926 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
927 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
928 configs.size());
929 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700930 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700931 const auto display = getDisplayDevice(displayToken);
932 if (!display) {
933 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
934 displayToken.get());
935 } else if (display->isVirtual()) {
936 ALOGW("Attempt to set active config %d for virtual display", mode);
937 } else {
938 setActiveConfigInternal(display, mode);
939 }
940 }));
941
Mathias Agopian888c8222012-08-04 21:10:38 -0700942 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700943}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700944status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
945 Vector<ColorMode>* outColorModes) {
946 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700947 return BAD_VALUE;
948 }
949
Michael Wright28f24d02016-07-12 13:30:53 -0700950 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700951 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
952 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700953 type = i;
954 break;
955 }
956 }
957
958 if (type < 0) {
959 return type;
960 }
961
Peiyong Lina52f0292018-03-14 17:26:31 -0700962 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700963 {
964 ConditionalLock _l(mStateLock,
965 std::this_thread::get_id() != mMainThreadId);
966 modes = getHwComposer().getColorModes(type);
967 }
Michael Wright28f24d02016-07-12 13:30:53 -0700968 outColorModes->clear();
969 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
970
971 return NO_ERROR;
972}
973
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700974ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
975 if (const auto display = getDisplayDevice(displayToken)) {
976 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700977 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700978 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700979}
980
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700981void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
982 Dataspace dataSpace, RenderIntent renderIntent) {
983 ColorMode currentMode = display->getActiveColorMode();
984 Dataspace currentDataSpace = display->getCompositionDataSpace();
985 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -0700986
Peiyong Lin38e9a562018-04-10 16:24:20 -0700987 if (mode == currentMode && dataSpace == currentDataSpace &&
988 renderIntent == currentRenderIntent) {
989 return;
990 }
991
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700992 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -0700993 ALOGW("Trying to set config for virtual display");
994 return;
995 }
996
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700997 display->setActiveColorMode(mode);
998 display->setCompositionDataSpace(dataSpace);
999 display->setActiveRenderIntent(renderIntent);
1000 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001001
1002 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001003 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1004 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001005}
1006
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001007status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001008 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001009 Vector<ColorMode> modes;
1010 getDisplayColorModes(displayToken, &modes);
1011 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1012 if (mode < ColorMode::NATIVE || !exists) {
1013 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1014 decodeColorMode(mode).c_str(), mode, displayToken.get());
1015 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001016 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001017 const auto display = getDisplayDevice(displayToken);
1018 if (!display) {
1019 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1020 decodeColorMode(mode).c_str(), mode, displayToken.get());
1021 } else if (display->isVirtual()) {
1022 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1023 decodeColorMode(mode).c_str(), mode);
1024 } else {
1025 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1026 RenderIntent::COLORIMETRIC);
1027 }
1028 }));
1029
Michael Wright28f24d02016-07-12 13:30:53 -07001030 return NO_ERROR;
1031}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001032
Svetoslavd85084b2014-03-20 10:28:31 -07001033status_t SurfaceFlinger::clearAnimationFrameStats() {
1034 Mutex::Autolock _l(mStateLock);
1035 mAnimFrameTracker.clearStats();
1036 return NO_ERROR;
1037}
1038
1039status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1040 Mutex::Autolock _l(mStateLock);
1041 mAnimFrameTracker.getStats(outStats);
1042 return NO_ERROR;
1043}
1044
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001045status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1046 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001047 Mutex::Autolock _l(mStateLock);
1048
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001049 const auto display = getDisplayDeviceLocked(displayToken);
1050 if (!display) {
1051 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001052 return BAD_VALUE;
1053 }
1054
Peiyong Linfb069302018-04-25 14:34:31 -07001055 // At this point the DisplayDeivce should already be set up,
1056 // meaning the luminance information is already queried from
1057 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001058 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001059 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1060 capabilities.getDesiredMaxLuminance(),
1061 capabilities.getDesiredMaxAverageLuminance(),
1062 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001063
1064 return NO_ERROR;
1065}
1066
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001067status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001068 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001069 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001070
Chia-I Wu90f669f2017-10-05 14:24:41 -07001071 if (mInjectVSyncs == enable) {
1072 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001073 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001074
1075 if (enable) {
1076 ALOGV("VSync Injections enabled");
1077 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001078 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001079 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001080 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001081 impl::EventThread::InterceptVSyncsCallback(),
1082 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001083 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001084 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001085 } else {
1086 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001087 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001088 }
1089
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001090 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001091 }));
1092
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001093 return NO_ERROR;
1094}
1095
1096status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001097 Mutex::Autolock _l(mStateLock);
1098
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001099 if (!mInjectVSyncs) {
1100 ALOGE("VSync Injections not enabled");
1101 return BAD_VALUE;
1102 }
1103 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1104 ALOGV("Injecting VSync inside SurfaceFlinger");
1105 mVSyncInjector->onInjectSyncEvent(when);
1106 }
1107 return NO_ERROR;
1108}
1109
Lloyd Pique755e3192018-01-31 16:46:15 -08001110status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1111 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001112 // Try to acquire a lock for 1s, fail gracefully
1113 const status_t err = mStateLock.timedLock(s2ns(1));
1114 const bool locked = (err == NO_ERROR);
1115 if (!locked) {
1116 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1117 return TIMED_OUT;
1118 }
1119
1120 outLayers->clear();
1121 mCurrentState.traverseInZOrder([&](Layer* layer) {
1122 outLayers->push_back(layer->getLayerDebugInfo());
1123 });
1124
1125 mStateLock.unlock();
1126 return NO_ERROR;
1127}
1128
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001129// ----------------------------------------------------------------------------
1130
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001131sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1132 ISurfaceComposer::VsyncSource vsyncSource) {
1133 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1134 return mSFEventThread->createEventConnection();
1135 } else {
1136 return mEventThread->createEventConnection();
1137 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001138}
1139
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001140// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001141
1142void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001143 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001144}
1145
1146void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001147 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001148}
1149
1150void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001151 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001152}
1153
1154void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001155 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001156 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001157}
1158
1159status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001160 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001161 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001162}
1163
1164status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001165 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001166 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001167 if (res == NO_ERROR) {
1168 msg->wait();
1169 }
1170 return res;
1171}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001172
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001173void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001174 do {
1175 waitForEvent();
1176 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001177}
1178
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001179void SurfaceFlinger::enableHardwareVsync() {
1180 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001181 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001182 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001183 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001184 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001185 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001186}
1187
Jesse Hall948fe0c2013-10-14 12:56:09 -07001188void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001189 Mutex::Autolock _l(mHWVsyncLock);
1190
Jesse Hall948fe0c2013-10-14 12:56:09 -07001191 if (makeAvailable) {
1192 mHWVsyncAvailable = true;
1193 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001194 // Hardware vsync is not currently available, so abort the resync
1195 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001196 return;
1197 }
1198
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001199 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1200 if (!getHwComposer().isConnected(displayId)) {
1201 return;
1202 }
1203
1204 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001205 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001206
Lloyd Pique41be5d22018-06-21 13:11:48 -07001207 mPrimaryDispSync->reset();
1208 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001209
1210 if (!mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001211 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001212 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001213 mPrimaryHWVsyncEnabled = true;
1214 }
1215}
1216
Jesse Hall948fe0c2013-10-14 12:56:09 -07001217void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001218 Mutex::Autolock _l(mHWVsyncLock);
1219 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001220 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001221 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001222 mPrimaryHWVsyncEnabled = false;
1223 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001224 if (makeUnavailable) {
1225 mHWVsyncAvailable = false;
1226 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001227}
1228
Tim Murray4a4e4a22016-04-19 16:29:23 +00001229void SurfaceFlinger::resyncWithRateLimit() {
1230 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001231
1232 // No explicit locking is needed here since EventThread holds a lock while calling this method
1233 static nsecs_t sLastResyncAttempted = 0;
1234 const nsecs_t now = systemTime();
1235 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001236 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001237 }
Dan Stoza57164302017-05-08 14:03:54 -07001238 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001239}
1240
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001241void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1242 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001243 ATRACE_NAME("SF onVsync");
1244
Steven Thomas3cfac282017-02-06 12:29:30 -08001245 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001246 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001247 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001248 return;
1249 }
1250
1251 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001252 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001253 return;
1254 }
1255
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001256 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1257 // For now, we don't do anything with external display vsyncs.
1258 return;
1259 }
1260
Jamie Gennisd1700752013-10-14 12:22:52 -07001261 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001262
Jamie Gennisd1700752013-10-14 12:22:52 -07001263 { // Scope for the lock
1264 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001265 if (mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001266 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001267 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001268 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001269
1270 if (needsHwVsync) {
1271 enableHardwareVsync();
1272 } else {
1273 disableHardwareVsync(false);
1274 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001275}
1276
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001277void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001278 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1279 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001280}
1281
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001282void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001283 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001284 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001285 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001286
Lloyd Piqueba04e622017-12-14 17:11:26 -08001287 // Ignore events that do not have the right sequenceId.
1288 if (sequenceId != getBE().mComposerSequenceId) {
1289 return;
1290 }
1291
Steven Thomasb02664d2017-07-26 18:48:28 -07001292 // Only lock if we're not on the main thread. This function is normally
1293 // called on a hwbinder thread, but for the primary display it's called on
1294 // the main thread with the state lock already held, so don't attempt to
1295 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001296 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001297
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001298 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001299
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001300 if (std::this_thread::get_id() == mMainThreadId) {
1301 // Process all pending hot plug events immediately if we are on the main thread.
1302 processDisplayHotplugEventsLocked();
1303 }
1304
Lloyd Piqueba04e622017-12-14 17:11:26 -08001305 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001306}
1307
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001308void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001309 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001310 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001311 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001312 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001313 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001314}
1315
Dan Stoza9e56aa02015-11-02 13:00:03 -08001316void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001317 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001318 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001319 getHwComposer().setVsyncEnabled(disp,
1320 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001321}
1322
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001323// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001324void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001325 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001326 // Clear the drawing state so that the logic inside of
1327 // handleTransactionLocked will fire. It will determine the delta between
1328 // mCurrentState and mDrawingState and re-apply all changes when we make the
1329 // transition.
1330 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001331 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001332 mDisplays.clear();
1333}
1334
Steven Thomas050b2c82017-03-06 11:45:16 -08001335void SurfaceFlinger::updateVrFlinger() {
1336 if (!mVrFlinger)
1337 return;
1338 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001339 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001340 return;
1341 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001342
David Sodman105b7dc2017-11-04 20:28:14 -07001343 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001344 ALOGE("Vr flinger is only supported for remote hardware composer"
1345 " service connections. Ignoring request to transition to vr"
1346 " flinger.");
1347 mVrFlingerRequestsDisplay = false;
1348 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001349 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001350
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001351 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001352
Steven Thomas0123ac62018-07-12 11:32:34 -07001353 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001354 LOG_ALWAYS_FATAL_IF(!display);
1355 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001356 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1357 // called below. Clear the reference now so we don't accidentally use it
1358 // later.
1359 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001360
Steven Thomasb02664d2017-07-26 18:48:28 -07001361 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001362 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001363 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001364
Steven Thomasb02664d2017-07-26 18:48:28 -07001365 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001366 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001367 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1368 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001369 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001370
David Sodman105b7dc2017-11-04 20:28:14 -07001371 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1372 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001373
1374 if (vrFlingerRequestsDisplay) {
1375 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001376 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001377
1378 mVisibleRegionsDirty = true;
1379 invalidateHwcGeometry();
1380
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001381 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001382 display = getDefaultDisplayDeviceLocked();
1383 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001384 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001385
Steven Thomasb02664d2017-07-26 18:48:28 -07001386 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001387 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001388 const nsecs_t period = activeConfig->getVsyncPeriod();
1389 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001390
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001391 // The present fences returned from vr_hwc are not an accurate
1392 // representation of vsync times.
Lloyd Pique41be5d22018-06-21 13:11:48 -07001393 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1394 !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001395
Steven Thomasb02664d2017-07-26 18:48:28 -07001396 // Use phase of 0 since phase is not known.
1397 // Use latency of 0, which will snap to the ideal latency.
1398 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001399
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001400 resyncToHardwareVsync(false);
1401
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001402 android_atomic_or(1, &mRepaintEverything);
1403 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001404}
1405
Mathias Agopian4fec8732012-06-29 14:12:52 -07001406void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001407 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001408 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001409 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001410 bool frameMissed = !mHadClientComposition &&
1411 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001412 (mPreviousPresentFence->getSignalTime() ==
1413 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001414 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001415 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001416 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001417 mTimeStats.incrementMissedFrames();
1418 if (mPropagateBackpressure) {
1419 signalLayerUpdate();
1420 break;
1421 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001422 }
Dan Stoza50182882016-07-08 12:02:20 -07001423
Steven Thomas050b2c82017-03-06 11:45:16 -08001424 // Now that we're going to make it to the handleMessageTransaction()
1425 // call below it's safe to call updateVrFlinger(), which will
1426 // potentially trigger a display handoff.
1427 updateVrFlinger();
1428
Dan Stoza6b9454d2014-11-07 16:00:59 -08001429 bool refreshNeeded = handleMessageTransaction();
1430 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001431 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001432 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001433 // Signal a refresh if a transaction modified the window state,
1434 // a new buffer was latched, or if HWC has requested a full
1435 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001436 signalRefresh();
1437 }
1438 break;
1439 }
1440 case MessageQueue::REFRESH: {
1441 handleMessageRefresh();
1442 break;
1443 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001444 }
1445}
1446
Dan Stoza6b9454d2014-11-07 16:00:59 -08001447bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001448 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001449 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001450 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001451 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001452 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001453 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001454}
1455
Mathias Agopian4fec8732012-06-29 14:12:52 -07001456void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001457 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001458
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001459 mRefreshPending = false;
1460
David Sodmanfa9b2af2017-12-24 13:28:59 -08001461 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
David Sodman2b406362017-12-15 13:33:47 -08001462 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001463 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001464 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001465 for (const auto& [token, display] : mDisplays) {
1466 beginFrame(display);
1467 prepareFrame(display);
1468 doDebugFlashRegions(display, repaintEverything);
1469 doComposition(display, repaintEverything);
1470 }
1471
Adrian Roos1e1a1282017-11-01 19:05:31 +01001472 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001473 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001474
1475 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001476 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001477
Dan Stozabfbffeb2016-07-21 14:49:33 -07001478 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001479 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001480 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001481 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001482 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001483
Jorim Jaggi90535212018-05-23 23:44:06 +02001484 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001485
David Sodman7e4ae112018-02-09 15:02:28 -08001486 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001487 for (const auto& [token, display] : mDisplays) {
1488 const auto displayId = display->getId();
David Sodman7e4ae112018-02-09 15:02:28 -08001489 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[displayId]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001490 compositionInfo.hwc.hwcLayer = nullptr;
1491 }
David Sodmanba340492018-08-05 21:51:33 -07001492 }
David Sodman7e4ae112018-02-09 15:02:28 -08001493
1494 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001495}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001496
David Sodmanfa9b2af2017-12-24 13:28:59 -08001497
1498bool SurfaceFlinger::handleMessageInvalidate() {
1499 ATRACE_CALL();
1500 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001501}
1502
David Sodman79bba0e2018-08-05 18:07:49 -07001503void SurfaceFlinger::calculateWorkingSet() {
1504 ATRACE_CALL();
1505 ALOGV(__FUNCTION__);
1506
David Sodman79bba0e2018-08-05 18:07:49 -07001507 // build the h/w work list
1508 if (CC_UNLIKELY(mGeometryInvalid)) {
1509 mGeometryInvalid = false;
1510 for (const auto& [token, display] : mDisplays) {
1511 const auto displayId = display->getId();
1512 if (displayId >= 0) {
1513 const Vector<sp<Layer>>& currentLayers(
1514 display->getVisibleLayersSortedByZ());
1515 for (size_t i = 0; i < currentLayers.size(); i++) {
1516 const auto& layer = currentLayers[i];
1517
1518 if (!layer->hasHwcLayer(displayId)) {
1519 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1520 layer->forceClientComposition(displayId);
1521 continue;
1522 }
1523 }
1524
1525 layer->setGeometry(display, i);
1526 if (mDebugDisableHWC || mDebugRegion) {
1527 layer->forceClientComposition(displayId);
1528 }
1529 }
1530 }
1531 }
1532 }
1533
1534 // Set the per-frame data
1535 for (const auto& [token, display] : mDisplays) {
1536 const auto displayId = display->getId();
1537 if (displayId < 0) {
1538 continue;
1539 }
1540
1541 if (mDrawingState.colorMatrixChanged) {
1542 display->setColorTransform(mDrawingState.colorMatrix);
1543 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1544 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1545 "display %d: %d", displayId, result);
1546 }
1547 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1548 if (layer->isHdrY410()) {
1549 layer->forceClientComposition(displayId);
1550 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1551 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1552 !display->hasHDR10Support()) {
1553 layer->forceClientComposition(displayId);
1554 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1555 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1556 !display->hasHLGSupport()) {
1557 layer->forceClientComposition(displayId);
1558 }
1559
1560 if (layer->getForceClientComposition(displayId)) {
1561 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1562 layer->setCompositionType(displayId, HWC2::Composition::Client);
1563 continue;
1564 }
1565
1566 layer->setPerFrameData(display);
1567 }
1568
Peiyong Lin13effd12018-07-24 17:01:47 -07001569 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001570 ColorMode colorMode;
1571 Dataspace dataSpace;
1572 RenderIntent renderIntent;
1573 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1574 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1575 }
1576 }
1577
1578 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001579
1580 for (const auto& [token, display] : mDisplays) {
David Sodman15fb96e2018-01-07 10:23:24 -08001581 const auto displayId = display->getId();
1582 getBE().mCompositionInfo[displayId].clear();
David Sodmanba340492018-08-05 21:51:33 -07001583 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1584 auto displayId = display->getId();
1585 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1586 if (!layer->setHwcLayer(displayId)) {
1587 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1588 }
David Sodman15fb96e2018-01-07 10:23:24 -08001589 layer->getBE().compositionInfo.hwc.displayId = displayId;
1590 getBE().mCompositionInfo[displayId].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001591 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1592 }
1593 }
David Sodman79bba0e2018-08-05 18:07:49 -07001594}
1595
David Sodmanfa9b2af2017-12-24 13:28:59 -08001596void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001597{
1598 // is debugging enabled
1599 if (CC_LIKELY(!mDebugRegion))
1600 return;
1601
David Sodmanfa9b2af2017-12-24 13:28:59 -08001602 if (display->isPoweredOn()) {
1603 // transform the dirty region into this screen's coordinate space
1604 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1605 if (!dirtyRegion.isEmpty()) {
1606 // redraw the whole screen
1607 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001608
David Sodmanfa9b2af2017-12-24 13:28:59 -08001609 // and draw the dirty region
1610 const int32_t height = display->getHeight();
1611 auto& engine(getRenderEngine());
1612 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001613
David Sodmanfa9b2af2017-12-24 13:28:59 -08001614 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001615 }
1616 }
1617
David Sodmanfa9b2af2017-12-24 13:28:59 -08001618 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001619
1620 if (mDebugRegion > 1) {
1621 usleep(mDebugRegion * 1000);
1622 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001623
David Sodmanfa9b2af2017-12-24 13:28:59 -08001624 if (display->isPoweredOn()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001625 status_t result = display->prepareFrame(*getBE().mHwc);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001626 ALOGE_IF(result != NO_ERROR,
1627 "prepareFrame for display %d failed:"
1628 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001629 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001630 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001631}
1632
Adrian Roos1e1a1282017-11-01 19:05:31 +01001633void SurfaceFlinger::doTracing(const char* where) {
1634 ATRACE_CALL();
1635 ATRACE_NAME(where);
1636 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001637 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001638 }
1639}
1640
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001641void SurfaceFlinger::logLayerStats() {
1642 ATRACE_CALL();
1643 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001644 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001645 if (display->isPrimary()) {
1646 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001647 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001648 }
1649 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001650
1651 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001652 }
1653}
1654
David Sodman2b406362017-12-15 13:33:47 -08001655void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001656{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001657 ATRACE_CALL();
1658 ALOGV("preComposition");
1659
David Sodman2b406362017-12-15 13:33:47 -08001660 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1661
Mathias Agopiancd60f992012-08-16 16:28:27 -07001662 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001663 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001664 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001665 needExtraInvalidate = true;
1666 }
Robert Carr2047fae2016-11-28 14:09:09 -08001667 });
1668
Mathias Agopiancd60f992012-08-16 16:28:27 -07001669 if (needExtraInvalidate) {
1670 signalLayerUpdate();
1671 }
1672}
1673
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001674void SurfaceFlinger::updateCompositorTiming(
1675 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1676 std::shared_ptr<FenceTime>& presentFenceTime) {
1677 // Update queue of past composite+present times and determine the
1678 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001679 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001680 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001681 while (!getBE().mCompositePresentTimes.empty()) {
1682 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001683 // Cached values should have been updated before calling this method,
1684 // which helps avoid duplicate syscalls.
1685 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1686 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1687 break;
1688 }
1689 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001690 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001691 }
1692
1693 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001694 while (getBE().mCompositePresentTimes.size() > 16) {
1695 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001696 }
1697
Brian Andersond0010582017-03-07 13:20:31 -08001698 setCompositorTimingSnapped(
1699 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1700}
1701
1702void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1703 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001704 // Integer division and modulo round toward 0 not -inf, so we need to
1705 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001706 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001707 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1708 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1709
Brian Andersond0010582017-03-07 13:20:31 -08001710 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1711 if (idealLatency <= 0) {
1712 idealLatency = vsyncInterval;
1713 }
1714
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001715 // Snap the latency to a value that removes scheduling jitter from the
1716 // composition and present times, which often have >1ms of jitter.
1717 // Reducing jitter is important if an app attempts to extrapolate
1718 // something (such as user input) to an accurate diasplay time.
1719 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1720 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001721 nsecs_t bias = vsyncInterval / 2;
1722 int64_t extraVsyncs =
1723 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1724 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1725 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001726
David Sodman99974d22017-11-28 12:04:33 -08001727 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1728 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1729 getBE().mCompositorTiming.interval = vsyncInterval;
1730 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001731}
1732
David Sodman2b406362017-12-15 13:33:47 -08001733void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001734{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001735 ATRACE_CALL();
1736 ALOGV("postComposition");
1737
Brian Anderson3546a3f2016-07-14 11:51:14 -07001738 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001739 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001740 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001741 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001742 }
1743
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001744 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001745 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001746
David Sodman73beded2017-11-15 11:56:06 -08001747 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001748 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001749 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001750 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001751 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001752 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001753 } else {
1754 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1755 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001756
David Sodman73beded2017-11-15 11:56:06 -08001757 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001758 mPreviousPresentFence =
1759 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1760 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001761 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001762
Lloyd Pique41be5d22018-06-21 13:11:48 -07001763 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1764 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001765
David Sodman2b406362017-12-15 13:33:47 -08001766 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001767 // when we started doing work for this frame, but that should be okay
1768 // since updateCompositorTiming has snapping logic.
1769 updateCompositorTiming(
David Sodman2b406362017-12-15 13:33:47 -08001770 vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001771 CompositorTiming compositorTiming;
1772 {
David Sodman99974d22017-11-28 12:04:33 -08001773 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1774 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001775 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001776
Robert Carr2047fae2016-11-28 14:09:09 -08001777 mDrawingState.traverseInZOrder([&](Layer* layer) {
1778 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001779 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001780 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001781 recordBufferingStats(layer->getName().string(),
1782 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001783 }
Robert Carr2047fae2016-11-28 14:09:09 -08001784 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001785
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001786 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001787 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001788 enableHardwareVsync();
1789 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001790 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001791 }
1792 }
1793
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001794 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001795 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001796 enableHardwareVsync();
1797 }
1798 }
1799
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001800 if (mAnimCompositionPending) {
1801 mAnimCompositionPending = false;
1802
Brian Anderson4e606e32017-03-16 15:34:57 -07001803 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001804 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001805 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001806 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001807 // The HWC doesn't support present fences, so use the refresh
1808 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001809 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001810 mAnimFrameTracker.setActualPresentTime(presentTime);
1811 }
1812 mAnimFrameTracker.advanceFrame();
1813 }
Dan Stozab90cf072015-03-05 11:05:59 -08001814
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001815 mTimeStats.incrementTotalFrames();
1816 if (mHadClientComposition) {
1817 mTimeStats.incrementClientCompositionFrames();
1818 }
1819
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001820 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001821 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001822 return;
1823 }
1824
1825 nsecs_t currentTime = systemTime();
1826 if (mHasPoweredOff) {
1827 mHasPoweredOff = false;
1828 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001829 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001830 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001831 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1832 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001833 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001834 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001835 }
David Sodman4a36e932017-11-07 14:29:47 -08001836 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001837 }
David Sodman4a36e932017-11-07 14:29:47 -08001838 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001839
1840 {
1841 std::lock_guard lock(mTexturePoolMutex);
1842 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1843 if (refillCount > 0) {
1844 const size_t offset = mTexturePool.size();
1845 mTexturePool.resize(mTexturePoolSize);
1846 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1847 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1848 }
1849 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001850}
1851
1852void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001853 ATRACE_CALL();
1854 ALOGV("rebuildLayerStacks");
1855
Mathias Agopiancd60f992012-08-16 16:28:27 -07001856 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001857 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001858 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001859 mVisibleRegionsDirty = false;
1860 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001861
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001862 for (const auto& pair : mDisplays) {
1863 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001864 Region opaqueRegion;
1865 Region dirtyRegion;
1866 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001867 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001868 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001869 const Rect bounds = display->getBounds();
1870 if (display->isPoweredOn()) {
1871 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001872
Jeff Sharkey76488112017-02-27 14:15:18 -07001873 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001874 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001875 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001876 Region drawRegion(tr.transform(
1877 layer->visibleNonTransparentRegion));
1878 drawRegion.andSelf(bounds);
1879 if (!drawRegion.isEmpty()) {
1880 layersSortedByZ.add(layer);
1881 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001882 // Clear out the HWC layer if this layer was
1883 // previously visible, but no longer is
1884 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001885 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001886 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001887 // WM changes display->layerStack upon sleep/awake.
1888 // Here we make sure we delete the HWC layers even if
1889 // WM changed their layer stack.
1890 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001891 }
1892
1893 // If a layer is not going to get a release fence because
1894 // it is invisible, but it is also going to release its
1895 // old buffer, add it to the list of layers needing
1896 // fences.
1897 if (hwcLayerDestroyed) {
1898 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1899 mLayersWithQueuedFrames.cend(), layer);
1900 if (found != mLayersWithQueuedFrames.cend()) {
1901 layersNeedingFences.add(layer);
1902 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001903 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001904 });
1905 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001906 display->setVisibleLayersSortedByZ(layersSortedByZ);
1907 display->setLayersNeedingFences(layersNeedingFences);
1908 display->undefinedRegion.set(bounds);
1909 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1910 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001911 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001912 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001913}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001914
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001915// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001916// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001917// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001918// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001919// The returned HDR data space is one of
1920// - Dataspace::UNKNOWN
1921// - Dataspace::BT2020_HLG
1922// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001923Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1924 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001925 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001926 *outHdrDataSpace = Dataspace::UNKNOWN;
1927
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001928 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001929 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001930 case Dataspace::V0_SCRGB:
1931 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001932 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001933 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001934 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001935 case Dataspace::BT2020_PQ:
1936 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001937 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001938 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001939 case Dataspace::BT2020_HLG:
1940 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001941 // When there's mixed PQ content and HLG content, we set the HDR
1942 // data space to be BT2020_PQ and convert HLG to PQ.
1943 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1944 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001945 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001946 break;
1947 default:
1948 break;
1949 }
Romain Guy54f154a2017-10-24 21:40:32 +01001950 }
1951
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001952 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001953}
1954
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001955// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001956void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1957 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001958 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1959 *outMode = ColorMode::NATIVE;
1960 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001961 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001962 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001963 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001964
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001965 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001966 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001967
Peiyong Lindfde5112018-06-05 10:58:41 -07001968 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001969 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001970 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001971 if (isHdr) {
1972 bestDataSpace = hdrDataSpace;
1973 }
1974
Chia-I Wu0d711262018-05-21 15:19:35 -07001975 RenderIntent intent;
1976 switch (mDisplayColorSetting) {
1977 case DisplayColorSetting::MANAGED:
1978 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001979 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001980 break;
1981 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001982 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001983 break;
1984 default: // vendor display color setting
1985 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1986 break;
1987 }
Chia-I Wube02ec02018-05-18 10:59:36 -07001988
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001989 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001990}
1991
David Sodmanfa9b2af2017-12-24 13:28:59 -08001992void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08001993{
David Sodmanfa9b2af2017-12-24 13:28:59 -08001994 bool dirty = !display->getDirtyRegion(false).isEmpty();
1995 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
1996 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08001997
David Sodmanfa9b2af2017-12-24 13:28:59 -08001998 // If nothing has changed (!dirty), don't recompose.
1999 // If something changed, but we don't currently have any visible layers,
2000 // and didn't when we last did a composition, then skip it this time.
2001 // The second rule does two things:
2002 // - When all layers are removed from a display, we'll emit one black
2003 // frame, then nothing more until we get new layers.
2004 // - When a display is created with a private layer stack, we won't
2005 // emit any black frames until a layer is added to the layer stack.
2006 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002007
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002008 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2009 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002010 mustRecompose ? "doing" : "skipping",
2011 dirty ? "+" : "-",
2012 empty ? "+" : "-",
2013 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002014
David Sodmanfa9b2af2017-12-24 13:28:59 -08002015 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002016
David Sodmanfa9b2af2017-12-24 13:28:59 -08002017 if (mustRecompose) {
2018 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002019 }
2020}
2021
David Sodmanfa9b2af2017-12-24 13:28:59 -08002022void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002023{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002024 if (!display->isPoweredOn()) {
2025 return;
David Sodman2b406362017-12-15 13:33:47 -08002026 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002027
2028 status_t result = display->prepareFrame(*getBE().mHwc);
2029 ALOGE_IF(result != NO_ERROR,
2030 "prepareFrame for display %d failed:"
2031 " %d (%s)",
2032 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002033}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002034
David Sodmanfa9b2af2017-12-24 13:28:59 -08002035void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002036 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002037 ALOGV("doComposition");
2038
David Sodmanfa9b2af2017-12-24 13:28:59 -08002039 if (display->isPoweredOn()) {
2040 // transform the dirty region into this screen's coordinate space
2041 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002042
David Sodmanfa9b2af2017-12-24 13:28:59 -08002043 // repaint the framebuffer (if needed)
2044 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002045
David Sodmanfa9b2af2017-12-24 13:28:59 -08002046 display->dirtyRegion.clear();
2047 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002048 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002049 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002050}
2051
David Sodmanfa9b2af2017-12-24 13:28:59 -08002052void SurfaceFlinger::postFrame()
2053{
2054 // |mStateLock| not needed as we are on the main thread
2055 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2056 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2057 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2058 logFrameStats();
2059 }
2060 }
2061}
2062
2063void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002064{
Mathias Agopian841cde52012-03-01 15:44:37 -08002065 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002066 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002067
David Sodmanfa9b2af2017-12-24 13:28:59 -08002068 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002069
David Sodmanfa9b2af2017-12-24 13:28:59 -08002070 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002071 const auto displayId = display->getId();
2072 if (displayId >= 0) {
2073 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002074 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002075 display->onSwapBuffersCompleted();
2076 display->makeCurrent();
2077 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002078 sp<Fence> releaseFence = Fence::NO_FENCE;
2079
Chia-I Wu7b549592017-11-15 09:14:57 -08002080 // The layer buffer from the previous frame (if any) is released
2081 // by HWC only when the release fence from this frame (if any) is
2082 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002083 auto hwcLayer = layer->getHwcLayer(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002084 if (displayId >= 0) {
2085 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
2086 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002087
2088 // If the layer was client composited in the previous frame, we
2089 // need to merge with the previous client target acquire fence.
2090 // Since we do not track that, always merge with the current
2091 // client target acquire fence when it is available, even though
2092 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002093 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002094 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002095 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002096 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002097
David Sodmanb8af7922017-12-21 15:17:55 -08002098 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002099 }
Chia-I Wu83806892017-11-16 10:50:20 -08002100
2101 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002102 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002103 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002104 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002105 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002106 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002107 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002108 }
2109 }
2110
Dominik Laskowski7e045462018-05-30 13:02:02 -07002111 if (displayId >= 0) {
2112 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002113 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002114 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002115}
2116
Mathias Agopian87baae12012-07-31 12:38:26 -07002117void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002118{
Mathias Agopian841cde52012-03-01 15:44:37 -08002119 ATRACE_CALL();
2120
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002121 // here we keep a copy of the drawing state (that is the state that's
2122 // going to be overwritten by handleTransactionLocked()) outside of
2123 // mStateLock so that the side-effects of the State assignment
2124 // don't happen with mStateLock held (which can cause deadlocks).
2125 State drawingState(mDrawingState);
2126
Mathias Agopianca4d3602011-05-19 15:38:14 -07002127 Mutex::Autolock _l(mStateLock);
2128 const nsecs_t now = systemTime();
2129 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002130
Mathias Agopianca4d3602011-05-19 15:38:14 -07002131 // Here we're guaranteed that some transaction flags are set
2132 // so we can call handleTransactionLocked() unconditionally.
2133 // We call getTransactionFlags(), which will also clear the flags,
2134 // with mStateLock held to guarantee that mCurrentState won't change
2135 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002136
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002137 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002138 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002139 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002140
Mathias Agopianca4d3602011-05-19 15:38:14 -07002141 mLastTransactionTime = systemTime() - now;
2142 mDebugInTransaction = 0;
2143 invalidateHwcGeometry();
2144 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002145}
2146
Dominik Laskowski7e045462018-05-30 13:02:02 -07002147DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002148 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002149 // Figure out whether the event is for the primary display or an
2150 // external display by matching the Hwc display id against one for a
2151 // connected display. If we did not find a match, we then check what
2152 // displays are not already connected to determine the type. If we don't
2153 // have a connected primary display, we assume the new display is meant to
2154 // be the primary display, and then if we don't have an external display,
2155 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002156 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2157 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002158 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002159 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002160 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002161 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002162 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002163 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002164 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002165 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002166 return DisplayDevice::DISPLAY_EXTERNAL;
2167 }
2168
2169 return DisplayDevice::DISPLAY_ID_INVALID;
2170}
2171
Lloyd Piqueba04e622017-12-14 17:11:26 -08002172void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2173 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002174 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002175 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002176 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002177 continue;
2178 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002179
2180 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2181 ALOGE("External displays are not supported by the vr hardware composer.");
2182 continue;
2183 }
2184
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002185 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002186 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002187 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002188 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002189 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002190
2191 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002192 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002193 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002194 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002195 DisplayDeviceState info;
2196 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002197 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2198 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002199 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002200 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002201 mInterceptor->saveDisplayCreation(info);
2202 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002203 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002204 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002205
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002206 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002207 if (idx >= 0) {
2208 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002209 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002210 mCurrentState.displays.removeItemsAt(idx);
2211 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002212 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002213 }
2214
2215 processDisplayChangesLocked();
2216 }
2217
2218 mPendingHotplugEvents.clear();
2219}
2220
Lloyd Pique99d3da52018-01-22 17:48:03 -08002221sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002222 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002223 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002224 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002225 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002226 HdrCapabilities hdrCapabilities;
2227 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002228
Peiyong Lin13effd12018-07-24 17:01:47 -07002229 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002230 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002231 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002232 if (isWideColorMode(colorMode)) {
2233 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002234 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002235
Dominik Laskowski7e045462018-05-30 13:02:02 -07002236 std::vector<RenderIntent> renderIntents =
2237 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002238 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002239 }
tangrobin6753a022018-08-10 10:58:54 +08002240 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002241
tangrobin6753a022018-08-10 10:58:54 +08002242 if (displayId >= 0) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002243 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2244 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2245 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002246
2247 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2248 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2249
2250 /*
2251 * Create our display's surface
2252 */
2253 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2254 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002255 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002256 renderSurface->setNativeWindow(nativeWindow.get());
2257 const int displayWidth = renderSurface->queryWidth();
2258 const int displayHeight = renderSurface->queryHeight();
2259
2260 // Make sure that composition can never be stalled by a virtual display
2261 // consumer that isn't processing buffers fast enough. We have to do this
2262 // in two places:
2263 // * Here, in case the display is composed entirely by HWC.
2264 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2265 // window's swap interval in eglMakeCurrent, so they'll override the
2266 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002267 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002268 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2269 }
2270
2271 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002272 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002273
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002274 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002275 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2276 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2277 displayHeight, hasWideColorGamut, hdrCapabilities,
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002278 supportedPerFrameMetadata, hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002279
2280 if (maxFrameBufferAcquiredBuffers >= 3) {
2281 nativeWindowSurface->preallocateBuffers();
2282 }
2283
2284 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002285 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2286 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002287 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002288 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002289 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002290 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002291 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002292 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002293 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002294 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002295 display->setLayerStack(state.layerStack);
2296 display->setProjection(state.orientation, state.viewport, state.frame);
2297 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002298
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002299 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002300}
2301
Lloyd Pique347200f2017-12-14 17:00:15 -08002302void SurfaceFlinger::processDisplayChangesLocked() {
2303 // here we take advantage of Vector's copy-on-write semantics to
2304 // improve performance by skipping the transaction entirely when
2305 // know that the lists are identical
2306 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2307 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2308 if (!curr.isIdenticalTo(draw)) {
2309 mVisibleRegionsDirty = true;
2310 const size_t cc = curr.size();
2311 size_t dc = draw.size();
2312
2313 // find the displays that were removed
2314 // (ie: in drawing state but not in current state)
2315 // also handle displays that changed
2316 // (ie: displays that are in both lists)
2317 for (size_t i = 0; i < dc;) {
2318 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2319 if (j < 0) {
2320 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002321 // Call makeCurrent() on the primary display so we can
2322 // be sure that nothing associated with this display
2323 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002324 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2325 defaultDisplay->makeCurrent();
2326 }
2327 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2328 display->disconnect(getHwComposer());
2329 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002330 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2331 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2332 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2333 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2334 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002335 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002336 } else {
2337 // this display is in both lists. see if something changed.
2338 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002339 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002340 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2341 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2342 if (state_binder != draw_binder) {
2343 // changing the surface is like destroying and
2344 // recreating the DisplayDevice, so we just remove it
2345 // from the drawing state, so that it get re-added
2346 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002347 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2348 display->disconnect(getHwComposer());
2349 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002350 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002351 mDrawingState.displays.removeItemsAt(i);
2352 dc--;
2353 // at this point we must loop to the next item
2354 continue;
2355 }
2356
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002357 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002358 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002359 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002360 }
2361 if ((state.orientation != draw[i].orientation) ||
2362 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002363 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002364 }
2365 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002366 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002367 }
2368 }
2369 }
2370 ++i;
2371 }
2372
2373 // find displays that were added
2374 // (ie: in current state but not in drawing state)
2375 for (size_t i = 0; i < cc; i++) {
2376 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2377 const DisplayDeviceState& state(curr[i]);
2378
2379 sp<DisplaySurface> dispSurface;
2380 sp<IGraphicBufferProducer> producer;
2381 sp<IGraphicBufferProducer> bqProducer;
2382 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002383 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002384
Dominik Laskowski7e045462018-05-30 13:02:02 -07002385 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002386 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002387 // Virtual displays without a surface are dormant:
2388 // they have external state (layer stack, projection,
2389 // etc.) but no internal state (i.e. a DisplayDevice).
2390 if (state.surface != nullptr) {
2391 // Allow VR composer to use virtual displays.
2392 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2393 int width = 0;
2394 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2395 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2396 int height = 0;
2397 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2398 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2399 int intFormat = 0;
2400 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2401 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002402 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002403
Dominik Laskowski7e045462018-05-30 13:02:02 -07002404 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2405 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002406 }
2407
2408 // TODO: Plumb requested format back up to consumer
2409
2410 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002411 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002412 bqProducer, bqConsumer,
2413 state.displayName);
2414
2415 dispSurface = vds;
2416 producer = vds;
2417 }
2418 } else {
2419 ALOGE_IF(state.surface != nullptr,
2420 "adding a supported display, but rendering "
2421 "surface is provided (%p), ignoring it",
2422 state.surface.get());
2423
Dominik Laskowski7e045462018-05-30 13:02:02 -07002424 displayId = state.type;
2425 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002426 producer = bqProducer;
2427 }
2428
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002429 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002430 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002431 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002432 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002433 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002434 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002435 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2436 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2437 true);
2438 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2439 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2440 true);
2441 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002442 }
2443 }
2444 }
2445 }
2446 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002447
2448 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002449}
2450
Mathias Agopian87baae12012-07-31 12:38:26 -07002451void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002452{
Dan Stoza7dde5992015-05-22 09:51:44 -07002453 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002454 mCurrentState.traverseInZOrder([](Layer* layer) {
2455 layer->notifyAvailableFrames();
2456 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002457
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002458 /*
2459 * Traversal of the children
2460 * (perform the transaction for each of them if needed)
2461 */
2462
Mathias Agopian3559b072012-08-15 13:46:03 -07002463 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002464 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002465 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002466 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002467
2468 const uint32_t flags = layer->doTransaction(0);
2469 if (flags & Layer::eVisibleRegion)
2470 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002471 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002472 }
2473
2474 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002475 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002476 */
2477
Mathias Agopiane57f2922012-08-09 16:29:12 -07002478 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002479 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002480 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002481 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002482
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002483 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002484 // The transform hint might have changed for some layers
2485 // (either because a display has changed, or because a layer
2486 // as changed).
2487 //
2488 // Walk through all the layers in currentLayers,
2489 // and update their transform hint.
2490 //
2491 // If a layer is visible only on a single display, then that
2492 // display is used to calculate the hint, otherwise we use the
2493 // default display.
2494 //
2495 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2496 // the hint is set before we acquire a buffer from the surface texture.
2497 //
2498 // NOTE: layer transactions have taken place already, so we use their
2499 // drawing state. However, SurfaceFlinger's own transaction has not
2500 // happened yet, so we must use the current state layer list
2501 // (soon to become the drawing state list).
2502 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002503 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002504 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002505 bool first = true;
2506 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002507 // NOTE: we rely on the fact that layers are sorted by
2508 // layerStack first (so we don't have to traverse the list
2509 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002510 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002511 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002512 currentlayerStack = layerStack;
2513 // figure out if this layerstack is mirrored
2514 // (more than one display) if so, pick the default display,
2515 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002516 hintDisplay = nullptr;
2517 for (const auto& [token, display] : mDisplays) {
2518 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2519 if (hintDisplay) {
2520 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002521 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002522 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002523 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002524 }
2525 }
2526 }
2527 }
Chet Haase91d25932013-04-11 15:24:55 -07002528
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002529 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002530 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2531 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002532
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002533 // could be null when this layer is using a layerStack
2534 // that is not visible on any display. Also can occur at
2535 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002536 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002537 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002538
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002539 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002540 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002541 if (hintDisplay) {
2542 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002543 }
Robert Carr2047fae2016-11-28 14:09:09 -08002544
2545 first = false;
2546 });
Mathias Agopian84300952012-11-21 16:02:13 -08002547 }
2548
2549
Mathias Agopian3559b072012-08-15 13:46:03 -07002550 /*
2551 * Perform our own transaction if needed
2552 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002553
2554 if (mLayersAdded) {
2555 mLayersAdded = false;
2556 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002557 mVisibleRegionsDirty = true;
2558 }
2559
2560 // some layers might have been removed, so
2561 // we need to update the regions they're exposing.
2562 if (mLayersRemoved) {
2563 mLayersRemoved = false;
2564 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002565 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002566 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002567 // this layer is not visible anymore
2568 // TODO: we could traverse the tree from front to back and
2569 // compute the actual visible region
2570 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002571 Region visibleReg;
2572 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002573 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002574 }
Robert Carr2047fae2016-11-28 14:09:09 -08002575 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002576 }
2577
2578 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002579
2580 updateCursorAsync();
2581}
2582
2583void SurfaceFlinger::updateCursorAsync()
2584{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002585 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002586 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002587 continue;
2588 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002589
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002590 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2591 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002592 }
2593 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002594}
2595
2596void SurfaceFlinger::commitTransaction()
2597{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002598 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002599 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002600 for (const auto& l : mLayersPendingRemoval) {
2601 recordBufferingStats(l->getName().string(),
2602 l->getOccupancyHistory(true));
2603 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002604 }
2605 mLayersPendingRemoval.clear();
2606 }
2607
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002608 // If this transaction is part of a window animation then the next frame
2609 // we composite should be considered an animation as well.
2610 mAnimCompositionPending = mAnimTransactionPending;
2611
Mathias Agopian4fec8732012-06-29 14:12:52 -07002612 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002613 // clear the "changed" flags in current state
2614 mCurrentState.colorMatrixChanged = false;
2615
Robert Carr1f0a16a2016-10-24 16:27:39 -07002616 mDrawingState.traverseInZOrder([](Layer* layer) {
2617 layer->commitChildList();
2618 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002619 mTransactionPending = false;
2620 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002621 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002622}
2623
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002624void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2625 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002626 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002627 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002628
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002629 Region aboveOpaqueLayers;
2630 Region aboveCoveredLayers;
2631 Region dirty;
2632
Mathias Agopian87baae12012-07-31 12:38:26 -07002633 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002634
Robert Carr2047fae2016-11-28 14:09:09 -08002635 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002636 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002637 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002638
Jesse Hall01e29052013-02-19 16:13:35 -08002639 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002640 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002641 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002642 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002643
Mathias Agopianab028732010-03-16 16:41:46 -07002644 /*
2645 * opaqueRegion: area of a surface that is fully opaque.
2646 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002647 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002648
2649 /*
2650 * visibleRegion: area of a surface that is visible on screen
2651 * and not fully transparent. This is essentially the layer's
2652 * footprint minus the opaque regions above it.
2653 * Areas covered by a translucent surface are considered visible.
2654 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002655 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002656
2657 /*
2658 * coveredRegion: area of a surface that is covered by all
2659 * visible regions above it (which includes the translucent areas).
2660 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002661 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002662
Jesse Halla8026d22012-09-25 13:25:04 -07002663 /*
2664 * transparentRegion: area of a surface that is hinted to be completely
2665 * transparent. This is only used to tell when the layer has no visible
2666 * non-transparent regions and can be removed from the layer list. It
2667 * does not affect the visibleRegion of this layer or any layers
2668 * beneath it. The hint may not be correct if apps don't respect the
2669 * SurfaceView restrictions (which, sadly, some don't).
2670 */
2671 Region transparentRegion;
2672
Mathias Agopianab028732010-03-16 16:41:46 -07002673
2674 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002675 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002676 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002677 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002678 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002679 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002680 if (!visibleRegion.isEmpty()) {
2681 // Remove the transparent area from the visible region
2682 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002683 if (tr.preserveRects()) {
2684 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002685 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002686 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002687 // transformation too complex, can't do the
2688 // transparent region optimization.
2689 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002690 }
Mathias Agopianab028732010-03-16 16:41:46 -07002691 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002692
Mathias Agopianab028732010-03-16 16:41:46 -07002693 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002694 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002695 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002696 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002697 // the opaque region is the layer's footprint
2698 opaqueRegion = visibleRegion;
2699 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002700 }
2701 }
2702
Robert Carre5f4f692018-01-12 13:12:28 -08002703 if (visibleRegion.isEmpty()) {
2704 layer->clearVisibilityRegions();
2705 return;
2706 }
2707
Mathias Agopianab028732010-03-16 16:41:46 -07002708 // Clip the covered region to the visible region
2709 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2710
2711 // Update aboveCoveredLayers for next (lower) layer
2712 aboveCoveredLayers.orSelf(visibleRegion);
2713
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002714 // subtract the opaque region covered by the layers above us
2715 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002716
2717 // compute this layer's dirty region
2718 if (layer->contentDirty) {
2719 // we need to invalidate the whole region
2720 dirty = visibleRegion;
2721 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002722 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002723 layer->contentDirty = false;
2724 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002725 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002726 * the exposed region consists of two components:
2727 * 1) what's VISIBLE now and was COVERED before
2728 * 2) what's EXPOSED now less what was EXPOSED before
2729 *
2730 * note that (1) is conservative, we start with the whole
2731 * visible region but only keep what used to be covered by
2732 * something -- which mean it may have been exposed.
2733 *
2734 * (2) handles areas that were not covered by anything but got
2735 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002736 */
Mathias Agopianab028732010-03-16 16:41:46 -07002737 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002738 const Region oldVisibleRegion = layer->visibleRegion;
2739 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002740 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2741 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002742 }
2743 dirty.subtractSelf(aboveOpaqueLayers);
2744
2745 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002746 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002747
Mathias Agopianab028732010-03-16 16:41:46 -07002748 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002749 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002750
Jesse Halla8026d22012-09-25 13:25:04 -07002751 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002752 layer->setVisibleRegion(visibleRegion);
2753 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002754 layer->setVisibleNonTransparentRegion(
2755 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002756 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002757
Mathias Agopian87baae12012-07-31 12:38:26 -07002758 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002759}
2760
Chia-I Wuab0c3192017-08-01 11:29:00 -07002761void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002762 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002763 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2764 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002765 }
2766 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002767}
2768
Dan Stoza6b9454d2014-11-07 16:00:59 -08002769bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002770{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002771 ALOGV("handlePageFlip");
2772
Brian Andersond6927fb2016-07-23 23:37:30 -07002773 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002774
Mathias Agopian4fec8732012-06-29 14:12:52 -07002775 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002776 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002777 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002778
2779 // Store the set of layers that need updates. This set must not change as
2780 // buffers are being latched, as this could result in a deadlock.
2781 // Example: Two producers share the same command stream and:
2782 // 1.) Layer 0 is latched
2783 // 2.) Layer 0 gets a new frame
2784 // 2.) Layer 1 gets a new frame
2785 // 3.) Layer 1 is latched.
2786 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2787 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002788 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002789 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002790 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07002791 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002792 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002793 } else {
2794 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002795 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002796 } else {
2797 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002798 }
Robert Carr2047fae2016-11-28 14:09:09 -08002799 });
2800
Dan Stoza9e56aa02015-11-02 13:00:03 -08002801 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002802 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002803 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002804 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002805 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002806 newDataLatched = true;
2807 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002808 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002809
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002810 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002811
2812 // If we will need to wake up at some time in the future to deal with a
2813 // queued frame that shouldn't be displayed during this vsync period, wake
2814 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002815 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002816 signalLayerUpdate();
2817 }
2818
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002819 // enter boot animation on first buffer latch
2820 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2821 ALOGI("Enter boot animation");
2822 mBootStage = BootStage::BOOTANIMATION;
2823 }
2824
Dan Stoza6b9454d2014-11-07 16:00:59 -08002825 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002826 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002827}
2828
Mathias Agopianad456f92011-01-13 17:53:01 -08002829void SurfaceFlinger::invalidateHwcGeometry()
2830{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002831 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002832}
2833
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002834void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2835 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002836 // We only need to actually compose the display if:
2837 // 1) It is being handled by hardware composer, which may need this to
2838 // keep its virtual display state machine in sync, or
2839 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002840 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002841 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002842 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002843 return;
2844 }
2845
Dan Stoza9e56aa02015-11-02 13:00:03 -08002846 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002847 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002848
2849 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002850 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002851}
2852
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002853bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002854 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002855
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002856 const Region bounds(display->bounds());
2857 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002858 const auto displayId = display->getId();
2859 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002860 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002861
Chia-I Wu8e50e692018-05-04 10:12:37 -07002862 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002863 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002864
Dan Stoza9e56aa02015-11-02 13:00:03 -08002865 if (hasClientComposition) {
2866 ALOGV("hasClientComposition");
2867
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002868 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002869 if (display->hasWideColorGamut()) {
2870 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002871 }
2872 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002873 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002874 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002875
Dominik Laskowski7e045462018-05-30 13:02:02 -07002876 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002877 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2878 HWC2::Capability::SkipClientColorTransform);
2879
Chia-I Wud49d6692018-06-27 07:17:41 +08002880 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002881 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2882 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08002883 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002884 }
2885
Chia-I Wud49d6692018-06-27 07:17:41 +08002886 // The current enhanced saturation matrix is designed to enhance Display P3,
2887 // thus we only apply this matrix when the render intent is not colorimetric
2888 // and the output color space is Display P3.
2889 needsEnhancedColorMatrix =
2890 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2891 outputDataspace == Dataspace::DISPLAY_P3);
2892 if (needsEnhancedColorMatrix) {
2893 colorMatrix *= mEnhancedSaturationMatrix;
2894 }
2895
2896 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002897
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002898 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002899 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002900 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002901 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002902
2903 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002904 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
2905 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
2906 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07002907 }
2908 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002909 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002910
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002911 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002912 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002913 // when using overlays, we assume a fully transparent framebuffer
2914 // NOTE: we could reduce how much we need to clear, for instance
2915 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002916 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002917 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002918 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002919 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002920 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002921 // we're left with the letterbox region
2922 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002923 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07002924
2925 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002926 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07002927
Mathias Agopianb9494d52012-04-18 02:28:45 -07002928 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002929 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002930 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002931 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002932 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002933 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002934
Yiwei Zhange4e26c02018-08-22 13:59:12 -07002935 const Rect& bounds = display->getBounds();
2936 const Rect& scissor = display->getScissor();
2937 if (scissor != bounds) {
2938 // scissor doesn't match the screen's dimensions, so we
2939 // need to clear everything outside of it and enable
2940 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002941
Yiwei Zhange4e26c02018-08-22 13:59:12 -07002942 // enable scissor for this frame
2943 const uint32_t height = display->getHeight();
2944 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
2945 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002946 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002947 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002948
Mathias Agopian85d751c2012-08-29 16:59:24 -07002949 /*
2950 * and then, render the layers targeted at the framebuffer
2951 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002952
Dan Stoza9e56aa02015-11-02 13:00:03 -08002953 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07002954 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002955 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002956 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002957 const Region clip(bounds.intersect(
2958 displayTransform.transform(layer->visibleRegion)));
2959 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002960 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002961 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002962 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002963 case HWC2::Composition::Cursor:
2964 case HWC2::Composition::Device:
2965 case HWC2::Composition::Sideband:
2966 case HWC2::Composition::SolidColor: {
2967 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002968 if (layer->getClearClientTarget(displayId) && !firstLayer &&
Rajavenu Kyatham2eae6d32018-04-10 12:34:05 +05302969 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
2970 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002971 // never clear the very first layer since we're
2972 // guaranteed the FB is already cleared
2973 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002974 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002975 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002976 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002977 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002978 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002979 break;
2980 }
2981 default:
2982 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002983 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002984 } else {
2985 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002986 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002987 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002988 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002989
Chia-I Wud49d6692018-06-27 07:17:41 +08002990 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07002991 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002992 }
2993
Mathias Agopianf45c5102012-10-24 16:29:17 -07002994 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002995 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002996 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002997}
2998
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002999void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
3000 const Region& region) const {
3001 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003002 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003003 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003004}
3005
Dan Stoza7d89d062015-04-30 13:29:25 -07003006status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003007 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003008 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003009 const sp<Layer>& lbc,
3010 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003011{
Dan Stoza7d89d062015-04-30 13:29:25 -07003012 // add this layer to the current state list
3013 {
3014 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003015 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003016 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3017 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003018 return NO_MEMORY;
3019 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003020 if (parent == nullptr) {
3021 mCurrentState.layersSortedByZ.add(lbc);
3022 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003023 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003024 ALOGE("addClientLayer called with a removed parent");
3025 return NAME_NOT_FOUND;
3026 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003027 parent->addChild(lbc);
3028 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003029
Yiwei Zhang243b3782018-05-15 17:40:04 -07003030 if (gbc != nullptr) {
3031 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3032 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3033 mMaxGraphicBufferProducerListSize,
3034 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3035 mGraphicBufferProducerList.size(),
3036 mMaxGraphicBufferProducerListSize, mNumLayers);
3037 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003038 mLayersAdded = true;
3039 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003040 }
3041
Mathias Agopian96f08192010-06-02 23:28:45 -07003042 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003043 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003044
Dan Stoza7d89d062015-04-30 13:29:25 -07003045 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003046}
3047
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003048status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003049 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003050 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3051}
Robert Carr7f9b8992017-03-10 11:08:39 -08003052
chaviwca27f252018-02-06 16:46:39 -08003053status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3054 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003055 if (layer->isPendingRemoval()) {
3056 return NO_ERROR;
3057 }
3058
Robert Carr1f0a16a2016-10-24 16:27:39 -07003059 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003060 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003061 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003062 if (topLevelOnly) {
3063 return NO_ERROR;
3064 }
3065
Chia-I Wu98f1c102017-05-30 14:54:08 -07003066 sp<Layer> ancestor = p;
3067 while (ancestor->getParent() != nullptr) {
3068 ancestor = ancestor->getParent();
3069 }
3070 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3071 ALOGE("removeLayer called with a layer whose parent has been removed");
3072 return NAME_NOT_FOUND;
3073 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003074
3075 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003076 } else {
3077 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003078 }
3079
Robert Carr136e2f62017-02-08 17:54:29 -08003080 // As a matter of normal operation, the LayerCleaner will produce a second
3081 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3082 // so we will succeed in promoting it, but it's already been removed
3083 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3084 // otherwise something has gone wrong and we are leaking the layer.
3085 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003086 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3087 layer->getName().string(),
3088 (p != nullptr) ? p->getName().string() : "no-parent");
3089 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003090 } else if (index < 0) {
3091 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003092 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003093
Chia-I Wuc6657022017-08-15 11:18:17 -07003094 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003095 mLayersPendingRemoval.add(layer);
3096 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003097 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003098 setTransactionFlags(eTransactionNeeded);
3099 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003100}
3101
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003102uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003103 return android_atomic_release_load(&mTransactionFlags);
3104}
3105
Mathias Agopian3f844832013-08-07 21:24:32 -07003106uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003107 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3108}
3109
Mathias Agopian3f844832013-08-07 21:24:32 -07003110uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003111 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3112}
3113
3114uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3115 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003116 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003117 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003118 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003119 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003120 }
3121 return old;
3122}
3123
chaviwca27f252018-02-06 16:46:39 -08003124bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3125 for (const ComposerState& state : states) {
3126 // Here we need to check that the interface we're given is indeed
3127 // one of our own. A malicious client could give us a nullptr
3128 // IInterface, or one of its own or even one of our own but a
3129 // different type. All these situations would cause us to crash.
3130 if (state.client == nullptr) {
3131 return true;
3132 }
3133
3134 sp<IBinder> binder = IInterface::asBinder(state.client);
3135 if (binder == nullptr) {
3136 return true;
3137 }
3138
3139 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3140 return true;
3141 }
3142 }
3143 return false;
3144}
3145
Mathias Agopian8b33f032012-07-24 20:43:54 -07003146void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003147 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003148 const Vector<DisplayState>& displays,
3149 uint32_t flags)
3150{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003151 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003152 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003153 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003154
chaviwca27f252018-02-06 16:46:39 -08003155 if (containsAnyInvalidClientState(states)) {
3156 return;
3157 }
3158
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003159 if (flags & eAnimation) {
3160 // For window updates that are part of an animation we must wait for
3161 // previous animation "frames" to be handled.
3162 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003163 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003164 if (CC_UNLIKELY(err != NO_ERROR)) {
3165 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003166 // caller after a few seconds.
3167 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3168 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003169 mAnimTransactionPending = false;
3170 break;
3171 }
3172 }
3173 }
3174
chaviwca27f252018-02-06 16:46:39 -08003175 for (const DisplayState& display : displays) {
3176 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003177 }
3178
chaviwca27f252018-02-06 16:46:39 -08003179 for (const ComposerState& state : states) {
3180 transactionFlags |= setClientStateLocked(state);
3181 }
3182
3183 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3184 // as destroyed should only occur after setting all other states. This is to allow for a
3185 // child re-parent to happen before marking its original parent as destroyed (which would
3186 // then mark the child as destroyed).
3187 for (const ComposerState& state : states) {
3188 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003189 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003190
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003191 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3192 // anyway. This can be used as a flush mechanism for previous async transactions.
3193 // Empty animation transaction can be used to simulate back-pressure, so also force a
3194 // transaction for empty animation transactions.
3195 if (transactionFlags == 0 &&
3196 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003197 transactionFlags = eTransactionNeeded;
3198 }
3199
Mathias Agopian386aa982011-11-07 21:58:03 -08003200 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003201 if (mInterceptor->isEnabled()) {
3202 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003203 }
Irvel468051e2016-06-13 16:44:44 -07003204
Mathias Agopian386aa982011-11-07 21:58:03 -08003205 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003206 const auto start = (flags & eEarlyWakeup)
3207 ? VSyncModulator::TransactionStart::EARLY
3208 : VSyncModulator::TransactionStart::NORMAL;
3209 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003210
3211 // if this is a synchronous transaction, wait for it to take effect
3212 // before returning.
3213 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003214 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003215 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003216 if (flags & eAnimation) {
3217 mAnimTransactionPending = true;
3218 }
3219 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003220 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3221 if (CC_UNLIKELY(err != NO_ERROR)) {
3222 // just in case something goes wrong in SF, return to the
3223 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003224 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3225 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003226 break;
3227 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003228 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003229 }
3230}
3231
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003232uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3233 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3234 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003235
Mathias Agopiane57f2922012-08-09 16:29:12 -07003236 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003237 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3238
3239 const uint32_t what = s.what;
3240 if (what & DisplayState::eSurfaceChanged) {
3241 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3242 state.surface = s.surface;
3243 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003244 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003245 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003246 if (what & DisplayState::eLayerStackChanged) {
3247 if (state.layerStack != s.layerStack) {
3248 state.layerStack = s.layerStack;
3249 flags |= eDisplayTransactionNeeded;
3250 }
3251 }
3252 if (what & DisplayState::eDisplayProjectionChanged) {
3253 if (state.orientation != s.orientation) {
3254 state.orientation = s.orientation;
3255 flags |= eDisplayTransactionNeeded;
3256 }
3257 if (state.frame != s.frame) {
3258 state.frame = s.frame;
3259 flags |= eDisplayTransactionNeeded;
3260 }
3261 if (state.viewport != s.viewport) {
3262 state.viewport = s.viewport;
3263 flags |= eDisplayTransactionNeeded;
3264 }
3265 }
3266 if (what & DisplayState::eDisplaySizeChanged) {
3267 if (state.width != s.width) {
3268 state.width = s.width;
3269 flags |= eDisplayTransactionNeeded;
3270 }
3271 if (state.height != s.height) {
3272 state.height = s.height;
3273 flags |= eDisplayTransactionNeeded;
3274 }
3275 }
3276
Mathias Agopiane57f2922012-08-09 16:29:12 -07003277 return flags;
3278}
3279
Robert Carrd4ae7f32018-06-07 16:10:57 -07003280bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3281 IPCThreadState* ipc = IPCThreadState::self();
3282 const int pid = ipc->getCallingPid();
3283 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003284 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003285 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003286 return false;
3287 }
3288 return true;
3289}
3290
chaviwca27f252018-02-06 16:46:39 -08003291uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3292 const layer_state_t& s = composerState.state;
3293 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3294
Mathias Agopian13127d82013-03-05 17:47:11 -08003295 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003296 if (layer == nullptr) {
3297 return 0;
3298 }
3299
3300 if (layer->isPendingRemoval()) {
3301 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3302 return 0;
3303 }
3304
3305 uint32_t flags = 0;
3306
3307 const uint32_t what = s.what;
3308 bool geometryAppliesWithResize =
3309 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003310
3311 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3312 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003313 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003314 layer->pushPendingState();
3315 }
3316
chaviw8b3871a2017-11-01 17:41:01 -07003317 if (what & layer_state_t::ePositionChanged) {
3318 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3319 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003320 }
chaviw8b3871a2017-11-01 17:41:01 -07003321 }
3322 if (what & layer_state_t::eLayerChanged) {
3323 // NOTE: index needs to be calculated before we update the state
3324 const auto& p = layer->getParent();
3325 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003326 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003327 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003328 mCurrentState.layersSortedByZ.removeAt(idx);
3329 mCurrentState.layersSortedByZ.add(layer);
3330 // we need traversal (state changed)
3331 // AND transaction (list changed)
3332 flags |= eTransactionNeeded|eTraversalNeeded;
3333 }
chaviw8b3871a2017-11-01 17:41:01 -07003334 } else {
3335 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003336 flags |= eTransactionNeeded|eTraversalNeeded;
3337 }
3338 }
chaviw8b3871a2017-11-01 17:41:01 -07003339 }
3340 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003341 // NOTE: index needs to be calculated before we update the state
3342 const auto& p = layer->getParent();
3343 if (p == nullptr) {
3344 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3345 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3346 mCurrentState.layersSortedByZ.removeAt(idx);
3347 mCurrentState.layersSortedByZ.add(layer);
3348 // we need traversal (state changed)
3349 // AND transaction (list changed)
3350 flags |= eTransactionNeeded|eTraversalNeeded;
3351 }
3352 } else {
3353 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3354 flags |= eTransactionNeeded|eTraversalNeeded;
3355 }
chaviw8b3871a2017-11-01 17:41:01 -07003356 }
3357 }
3358 if (what & layer_state_t::eSizeChanged) {
3359 if (layer->setSize(s.w, s.h)) {
3360 flags |= eTraversalNeeded;
3361 }
3362 }
3363 if (what & layer_state_t::eAlphaChanged) {
3364 if (layer->setAlpha(s.alpha))
3365 flags |= eTraversalNeeded;
3366 }
3367 if (what & layer_state_t::eColorChanged) {
3368 if (layer->setColor(s.color))
3369 flags |= eTraversalNeeded;
3370 }
3371 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003372 // TODO: b/109894387
3373 //
3374 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3375 // rotation. To see the problem observe that if we have a square parent, and a child
3376 // of the same size, then we rotate the child 45 degrees around it's center, the child
3377 // must now be cropped to a non rectangular 8 sided region.
3378 //
3379 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3380 // private API, and the WindowManager only uses rotation in one case, which is on a top
3381 // level layer in which cropping is not an issue.
3382 //
3383 // However given that abuse of rotation matrices could lead to surfaces extending outside
3384 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3385 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3386 // transformations.
3387 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003388 flags |= eTraversalNeeded;
3389 }
3390 if (what & layer_state_t::eTransparentRegionChanged) {
3391 if (layer->setTransparentRegionHint(s.transparentRegion))
3392 flags |= eTraversalNeeded;
3393 }
3394 if (what & layer_state_t::eFlagsChanged) {
3395 if (layer->setFlags(s.flags, s.mask))
3396 flags |= eTraversalNeeded;
3397 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003398 if (what & layer_state_t::eCropChanged_legacy) {
3399 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003400 flags |= eTraversalNeeded;
3401 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003402 if (what & layer_state_t::eFinalCropChanged_legacy) {
3403 if (layer->setFinalCrop_legacy(s.finalCrop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003404 flags |= eTraversalNeeded;
3405 }
3406 if (what & layer_state_t::eLayerStackChanged) {
3407 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3408 // We only allow setting layer stacks for top level layers,
3409 // everything else inherits layer stack from its parent.
3410 if (layer->hasParent()) {
3411 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3412 layer->getName().string());
3413 } else if (idx < 0) {
3414 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3415 "that also does not appear in the top level layer list. Something"
3416 " has gone wrong.", layer->getName().string());
3417 } else if (layer->setLayerStack(s.layerStack)) {
3418 mCurrentState.layersSortedByZ.removeAt(idx);
3419 mCurrentState.layersSortedByZ.add(layer);
3420 // we need traversal (state changed)
3421 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003422 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003423 }
3424 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003425 if (what & layer_state_t::eDeferTransaction_legacy) {
3426 if (s.barrierHandle_legacy != nullptr) {
3427 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3428 } else if (s.barrierGbp_legacy != nullptr) {
3429 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003430 if (authenticateSurfaceTextureLocked(gbp)) {
3431 const auto& otherLayer =
3432 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003433 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003434 } else {
3435 ALOGE("Attempt to defer transaction to to an"
3436 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003437 }
3438 }
chaviw8b3871a2017-11-01 17:41:01 -07003439 // We don't trigger a traversal here because if no other state is
3440 // changed, we don't want this to cause any more work
3441 }
3442 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003443 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003444 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003445 if (!hadParent) {
3446 mCurrentState.layersSortedByZ.remove(layer);
3447 }
chaviw8b3871a2017-11-01 17:41:01 -07003448 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003449 }
chaviw8b3871a2017-11-01 17:41:01 -07003450 }
3451 if (what & layer_state_t::eReparentChildren) {
3452 if (layer->reparentChildren(s.reparentHandle)) {
3453 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003454 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003455 }
chaviw8b3871a2017-11-01 17:41:01 -07003456 if (what & layer_state_t::eDetachChildren) {
3457 layer->detachChildren();
3458 }
3459 if (what & layer_state_t::eOverrideScalingModeChanged) {
3460 layer->setOverrideScalingMode(s.overrideScalingMode);
3461 // We don't trigger a traversal here because if no other state is
3462 // changed, we don't want this to cause any more work
3463 }
Marissa Wall61c58622018-07-18 10:12:20 -07003464 if (what & layer_state_t::eTransformChanged) {
3465 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3466 }
3467 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3468 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3469 flags |= eTraversalNeeded;
3470 }
3471 if (what & layer_state_t::eCropChanged) {
3472 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3473 }
3474 if (what & layer_state_t::eBufferChanged) {
3475 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3476 }
3477 if (what & layer_state_t::eAcquireFenceChanged) {
3478 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3479 }
3480 if (what & layer_state_t::eDataspaceChanged) {
3481 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3482 }
3483 if (what & layer_state_t::eHdrMetadataChanged) {
3484 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3485 }
3486 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3487 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3488 }
3489 if (what & layer_state_t::eApiChanged) {
3490 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3491 }
3492 if (what & layer_state_t::eSidebandStreamChanged) {
3493 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3494 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003495 return flags;
3496}
3497
chaviwca27f252018-02-06 16:46:39 -08003498void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3499 const layer_state_t& state = composerState.state;
3500 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3501
3502 sp<Layer> layer(client->getLayerUser(state.surface));
3503 if (layer == nullptr) {
3504 return;
3505 }
3506
3507 if (layer->isPendingRemoval()) {
3508 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3509 return;
3510 }
3511
3512 if (state.what & layer_state_t::eDestroySurface) {
3513 removeLayerLocked(mStateLock, layer);
3514 }
3515}
3516
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003517status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003518 const String8& name,
3519 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003520 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003521 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003522 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003523{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003524 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003525 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003526 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003527 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003528 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003529
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003530 status_t result = NO_ERROR;
3531
3532 sp<Layer> layer;
3533
Cody Northropbc755282017-03-31 12:00:08 -06003534 String8 uniqueName = getUniqueLayerName(name);
3535
Mathias Agopian3165cc22012-08-08 19:42:09 -07003536 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003537 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003538 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3539 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003540
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003541 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003542 case ISurfaceComposerClient::eFXSurfaceBufferState:
3543 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3544 break;
chaviw13fdc492017-06-27 12:40:18 -07003545 case ISurfaceComposerClient::eFXSurfaceColor:
3546 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003547 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003548 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003549 break;
3550 default:
3551 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003552 break;
3553 }
3554
Dan Stoza7d89d062015-04-30 13:29:25 -07003555 if (result != NO_ERROR) {
3556 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003557 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003558
Chia-I Wuab0c3192017-08-01 11:29:00 -07003559 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3560 // TODO b/64227542
3561 if (windowType == 441731) {
3562 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3563 layer->setPrimaryDisplayOnly();
3564 }
3565
Albert Chaulk479c60c2017-01-27 14:21:34 -05003566 layer->setInfo(windowType, ownerUid);
3567
Robert Carr1f0a16a2016-10-24 16:27:39 -07003568 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003569 if (result != NO_ERROR) {
3570 return result;
3571 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003572 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003573
3574 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003575 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003576}
3577
Cody Northropbc755282017-03-31 12:00:08 -06003578String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3579{
3580 bool matchFound = true;
3581 uint32_t dupeCounter = 0;
3582
3583 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3584 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3585
Dan Stoza436ccf32018-06-21 12:10:12 -07003586 // Grab the state lock since we're accessing mCurrentState
3587 Mutex::Autolock lock(mStateLock);
3588
Cody Northropbc755282017-03-31 12:00:08 -06003589 // Loop over layers until we're sure there is no matching name
3590 while (matchFound) {
3591 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003592 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003593 if (layer->getName() == uniqueName) {
3594 matchFound = true;
3595 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3596 }
3597 });
3598 }
3599
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003600 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3601 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003602
3603 return uniqueName;
3604}
3605
Marissa Wallfd668622018-05-10 10:21:13 -07003606status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3607 uint32_t w, uint32_t h, uint32_t flags,
3608 PixelFormat& format, sp<IBinder>* handle,
3609 sp<IGraphicBufferProducer>* gbp,
3610 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003611 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003612 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003613 case PIXEL_FORMAT_TRANSPARENT:
3614 case PIXEL_FORMAT_TRANSLUCENT:
3615 format = PIXEL_FORMAT_RGBA_8888;
3616 break;
3617 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003618 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003619 break;
3620 }
3621
Marissa Wallfd668622018-05-10 10:21:13 -07003622 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3623 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003624 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003625 *handle = layer->getHandle();
3626 *gbp = layer->getProducer();
3627 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003628 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003629
Marissa Wallfd668622018-05-10 10:21:13 -07003630 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003631 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003632}
3633
Marissa Wall61c58622018-07-18 10:12:20 -07003634status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3635 uint32_t w, uint32_t h, uint32_t flags,
3636 sp<IBinder>* handle, sp<Layer>* outLayer) {
3637 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3638 *handle = layer->getHandle();
3639 *outLayer = layer;
3640
3641 return NO_ERROR;
3642}
3643
chaviw13fdc492017-06-27 12:40:18 -07003644status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003645 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003646 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003647{
chaviw13fdc492017-06-27 12:40:18 -07003648 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003649 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003650 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003651}
3652
Mathias Agopianac9fa422013-02-11 16:40:36 -08003653status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003654{
Robert Carr9524cb32017-02-13 11:32:32 -08003655 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003656 status_t err = NO_ERROR;
3657 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003658 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003659 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003660 err = removeLayer(l);
3661 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3662 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003663 }
3664 return err;
3665}
3666
Mathias Agopian13127d82013-03-05 17:47:11 -08003667status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003668{
Mathias Agopian67106042013-03-14 19:18:13 -07003669 // called by ~LayerCleaner() when all references to the IBinder (handle)
3670 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003671 sp<Layer> l = layer.promote();
3672 if (l == nullptr) {
3673 // The layer has already been removed, carry on
3674 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003675 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003676 // If we have a parent, then we can continue to live as long as it does.
3677 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003678}
3679
Mathias Agopianb60314a2012-04-10 22:09:54 -07003680// ---------------------------------------------------------------------------
3681
Andy McFadden13a082e2012-08-24 10:16:42 -07003682void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003683 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3684 if (!displayToken) return;
3685
Jesse Hall01e29052013-02-19 16:13:35 -08003686 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003687 Vector<ComposerState> state;
3688 Vector<DisplayState> displays;
3689 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003690 d.what = DisplayState::eDisplayProjectionChanged |
3691 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003692 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003693 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003694 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003695 d.frame.makeInvalid();
3696 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003697 d.width = 0;
3698 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003699 displays.add(d);
3700 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003701
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003702 const auto display = getDisplayDevice(displayToken);
3703 if (!display) return;
3704
3705 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3706
3707 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003708 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003709 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003710
Brian Andersond0010582017-03-07 13:20:31 -08003711 // Use phase of 0 since phase is not known.
3712 // Use latency of 0, which will snap to the ideal latency.
3713 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003714}
3715
3716void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003717 // Async since we may be called from the main thread.
3718 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003719}
3720
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003721void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3722 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003723 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003724 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003725
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003726 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003727 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003728 return;
3729 }
3730
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003731 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003732 ALOGW("Trying to set power mode for virtual display");
3733 return;
3734 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003735
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003736 display->setPowerMode(mode);
3737
Lloyd Pique4dccc412018-01-22 17:21:36 -08003738 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003739 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003740 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003741 if (idx < 0) {
3742 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3743 return;
3744 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003745 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003746 }
3747
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003748 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003749 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003750 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003751 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003752 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003753 // FIXME: eventthread only knows about the main display right now
3754 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003755 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003756 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003757
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003758 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003759 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003760 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003761
3762 struct sched_param param = {0};
3763 param.sched_priority = 1;
3764 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3765 ALOGW("Couldn't set SCHED_FIFO on display on");
3766 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003767 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003768 // Turn off the display
3769 struct sched_param param = {0};
3770 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3771 ALOGW("Couldn't set SCHED_OTHER on display off");
3772 }
3773
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003774 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003775 disableHardwareVsync(true); // also cancels any in-progress resync
3776
Mathias Agopiancde87a32012-09-13 14:09:01 -07003777 // FIXME: eventthread only knows about the main display right now
3778 mEventThread->onScreenReleased();
3779 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003780
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003781 getHwComposer().setPowerMode(type, mode);
3782 mVisibleRegionsDirty = true;
3783 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003784 } else if (mode == HWC_POWER_MODE_DOZE ||
3785 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003786 // Update display while dozing
3787 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003788 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003789 // FIXME: eventthread only knows about the main display right now
3790 mEventThread->onScreenAcquired();
3791 resyncToHardwareVsync(true);
3792 }
3793 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3794 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003795 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003796 disableHardwareVsync(true); // also cancels any in-progress resync
3797 // FIXME: eventthread only knows about the main display right now
3798 mEventThread->onScreenReleased();
3799 }
3800 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003801 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003802 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003803 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003804 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003805
3806 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003807}
3808
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003809void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003810 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003811 const auto display = getDisplayDevice(displayToken);
3812 if (!display) {
3813 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3814 displayToken.get());
3815 } else if (display->isVirtual()) {
3816 ALOGW("Attempt to set power mode %d for virtual display", mode);
3817 } else {
3818 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003819 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003820 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003821}
3822
3823// ---------------------------------------------------------------------------
3824
Lloyd Pique755e3192018-01-31 16:46:15 -08003825status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3826 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003827 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003828
Mathias Agopianbd115332013-04-18 16:41:04 -07003829 IPCThreadState* ipc = IPCThreadState::self();
3830 const int pid = ipc->getCallingPid();
3831 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003832
Mathias Agopianbd115332013-04-18 16:41:04 -07003833 if ((uid != AID_SHELL) &&
3834 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003835 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003836 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003837 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003838 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003839 // (this would indicate SF is stuck, but we want to be able to
3840 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003841 status_t err = mStateLock.timedLock(s2ns(1));
3842 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003843 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003844 result.appendFormat(
3845 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3846 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003847 }
3848
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003849 bool dumpAll = true;
3850 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003851 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003852
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003853 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003854 if ((index < numArgs) &&
3855 (args[index] == String16("--list"))) {
3856 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003857 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003858 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003859 }
3860
3861 if ((index < numArgs) &&
3862 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003863 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003864 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003865 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003866 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003867
3868 if ((index < numArgs) &&
3869 (args[index] == String16("--latency-clear"))) {
3870 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003871 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003872 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003873 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003874
3875 if ((index < numArgs) &&
3876 (args[index] == String16("--dispsync"))) {
3877 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07003878 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07003879 dumpAll = false;
3880 }
Dan Stozab90cf072015-03-05 11:05:59 -08003881
3882 if ((index < numArgs) &&
3883 (args[index] == String16("--static-screen"))) {
3884 index++;
3885 dumpStaticScreenStats(result);
3886 dumpAll = false;
3887 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003888
3889 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003890 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003891 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003892 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003893 dumpAll = false;
3894 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003895
3896 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3897 index++;
3898 dumpWideColorInfo(result);
3899 dumpAll = false;
3900 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003901
3902 if ((index < numArgs) &&
3903 (args[index] == String16("--enable-layer-stats"))) {
3904 index++;
3905 mLayerStats.enable();
3906 dumpAll = false;
3907 }
3908
3909 if ((index < numArgs) &&
3910 (args[index] == String16("--disable-layer-stats"))) {
3911 index++;
3912 mLayerStats.disable();
3913 dumpAll = false;
3914 }
3915
3916 if ((index < numArgs) &&
3917 (args[index] == String16("--clear-layer-stats"))) {
3918 index++;
3919 mLayerStats.clear();
3920 dumpAll = false;
3921 }
3922
3923 if ((index < numArgs) &&
3924 (args[index] == String16("--dump-layer-stats"))) {
3925 index++;
3926 mLayerStats.dump(result);
3927 dumpAll = false;
3928 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003929
3930 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08003931 (args[index] == String16("--frame-composition"))) {
3932 index++;
3933 dumpFrameCompositionInfo(result);
3934 dumpAll = false;
3935 }
3936
3937 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003938 (args[index] == String16("--display-identification"))) {
3939 index++;
3940 dumpDisplayIdentificationData(result);
3941 dumpAll = false;
3942 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003943
3944 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3945 index++;
3946 mTimeStats.parseArgs(asProto, args, index, result);
3947 dumpAll = false;
3948 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003949 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003950
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003951 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003952 if (asProto) {
3953 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3954 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3955 } else {
3956 dumpAllLocked(args, index, result);
3957 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003958 }
3959
Mathias Agopian9795c422009-08-26 16:36:26 -07003960 if (locked) {
3961 mStateLock.unlock();
3962 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003963 }
3964 write(fd, result.string(), result.size());
3965 return NO_ERROR;
3966}
3967
Dan Stozac7014012014-02-14 15:03:43 -08003968void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3969 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003970{
Robert Carr2047fae2016-11-28 14:09:09 -08003971 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003972 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003973 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003974}
3975
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003976void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003977 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003978{
3979 String8 name;
3980 if (index < args.size()) {
3981 name = String8(args[index]);
3982 index++;
3983 }
3984
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003985 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
3986 getHwComposer().isConnected(displayId)) {
3987 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
3988 const nsecs_t period = activeConfig->getVsyncPeriod();
3989 result.appendFormat("%" PRId64 "\n", period);
3990 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003991
3992 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003993 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003994 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003995 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003996 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003997 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003998 }
Robert Carr2047fae2016-11-28 14:09:09 -08003999 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004000 }
4001}
4002
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004003void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004004 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004005{
4006 String8 name;
4007 if (index < args.size()) {
4008 name = String8(args[index]);
4009 index++;
4010 }
4011
Robert Carr2047fae2016-11-28 14:09:09 -08004012 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004013 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004014 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004015 }
Robert Carr2047fae2016-11-28 14:09:09 -08004016 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004017
Svetoslavd85084b2014-03-20 10:28:31 -07004018 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004019}
4020
Jamie Gennis6547ff42013-07-16 20:12:42 -07004021// This should only be called from the main thread. Otherwise it would need
4022// the lock and should use mCurrentState rather than mDrawingState.
4023void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004024 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004025 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004026 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004027
4028 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4029}
4030
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004031void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004032{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004033 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004034
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004035 if (isLayerTripleBufferingDisabled())
4036 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004037
4038 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004039 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004040 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004041 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004042 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4043 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004044 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004045}
4046
Dan Stozab90cf072015-03-05 11:05:59 -08004047void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4048{
4049 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004050 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4051 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004052 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004053 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004054 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4055 b + 1, bucketTimeSec, percent);
4056 }
David Sodman4a36e932017-11-07 14:29:47 -08004057 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004058 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004059 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004060 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004061 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004062}
4063
Dan Stozae77c7662016-05-13 11:37:28 -07004064void SurfaceFlinger::recordBufferingStats(const char* layerName,
4065 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004066 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4067 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004068 for (const auto& segment : history) {
4069 if (!segment.usedThirdBuffer) {
4070 stats.twoBufferTime += segment.totalTime;
4071 }
4072 if (segment.occupancyAverage < 1.0f) {
4073 stats.doubleBufferedTime += segment.totalTime;
4074 } else if (segment.occupancyAverage < 2.0f) {
4075 stats.tripleBufferedTime += segment.totalTime;
4076 }
4077 ++stats.numSegments;
4078 stats.totalTime += segment.totalTime;
4079 }
4080}
4081
Brian Andersond6927fb2016-07-23 23:37:30 -07004082void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4083 result.appendFormat("Layer frame timestamps:\n");
4084
4085 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4086 const size_t count = currentLayers.size();
4087 for (size_t i=0 ; i<count ; i++) {
4088 currentLayers[i]->dumpFrameEvents(result);
4089 }
4090}
4091
Dan Stozae77c7662016-05-13 11:37:28 -07004092void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4093 result.append("Buffering stats:\n");
4094 result.append(" [Layer name] <Active time> <Two buffer> "
4095 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004096 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004097 typedef std::tuple<std::string, float, float, float> BufferTuple;
4098 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004099 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004100 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004101 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004102 if (stats.numSegments == 0) {
4103 continue;
4104 }
4105 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4106 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4107 stats.totalTime;
4108 float doubleBufferRatio = static_cast<float>(
4109 stats.doubleBufferedTime) / stats.totalTime;
4110 float tripleBufferRatio = static_cast<float>(
4111 stats.tripleBufferedTime) / stats.totalTime;
4112 sorted.insert({activeTime, {name, twoBufferRatio,
4113 doubleBufferRatio, tripleBufferRatio}});
4114 }
4115 for (const auto& sortedPair : sorted) {
4116 float activeTime = sortedPair.first;
4117 const BufferTuple& values = sortedPair.second;
4118 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4119 std::get<0>(values).c_str(), activeTime,
4120 std::get<1>(values), std::get<2>(values),
4121 std::get<3>(values));
4122 }
4123 result.append("\n");
4124}
4125
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004126void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004127 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004128 const int32_t displayId = display->getId();
4129 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4130 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004131 continue;
4132 }
4133
Dominik Laskowski7e045462018-05-30 13:02:02 -07004134 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004135 uint8_t port;
4136 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004137 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004138 result.append("no identification data\n");
4139 continue;
4140 }
4141
4142 if (!isEdid(data)) {
4143 result.append("unknown identification data: ");
4144 for (uint8_t byte : data) {
4145 result.appendFormat("%x ", byte);
4146 }
4147 result.append("\n");
4148 continue;
4149 }
4150
4151 const auto edid = parseEdid(data);
4152 if (!edid) {
4153 result.append("invalid EDID: ");
4154 for (uint8_t byte : data) {
4155 result.appendFormat("%x ", byte);
4156 }
4157 result.append("\n");
4158 continue;
4159 }
4160
4161 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4162 result.append(edid->displayName.data(), edid->displayName.length());
4163 result.append("\"\n");
4164 }
4165 result.append("\n");
4166}
4167
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004168void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004169 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4170 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004171 result.appendFormat("DisplayColorSetting: %s\n",
4172 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004173
4174 // TODO: print out if wide-color mode is active or not
4175
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004176 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004177 const int32_t displayId = display->getId();
4178 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004179 continue;
4180 }
4181
Dominik Laskowski7e045462018-05-30 13:02:02 -07004182 result.appendFormat("Display %d color modes:\n", displayId);
4183 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004184 for (auto&& mode : modes) {
4185 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4186 }
4187
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004188 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004189 result.appendFormat(" Current color mode: %s (%d)\n",
4190 decodeColorMode(currentMode).c_str(), currentMode);
4191 }
4192 result.append("\n");
4193}
4194
David Sodman7e4ae112018-02-09 15:02:28 -08004195void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4196 std::string stringResult;
4197
4198 for (const auto& [token, display] : mDisplays) {
4199 const auto displayId = display->getId();
4200 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
4201 continue;
4202 }
4203
4204 const auto& compositionInfoIt = getBE().mEndOfFrameCompositionInfo.find(displayId);
4205 if (compositionInfoIt == getBE().mEndOfFrameCompositionInfo.end()) {
4206 break;
4207 }
4208 const auto& compositionInfoList = compositionInfoIt->second;
4209 stringResult += base::StringPrintf("Display: %d\n", displayId);
4210 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4211 for (const auto& compositionInfo : compositionInfoList) {
4212 compositionInfo.dump(stringResult, nullptr);
4213 stringResult += base::StringPrintf("\n");
4214 }
4215 }
4216
4217 result.append(stringResult.c_str());
4218}
4219
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004220LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004221 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004222 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4223 const State& state = useDrawing ? mDrawingState : mCurrentState;
4224 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004225 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004226 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004227 });
4228
4229 return layersProto;
4230}
4231
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004232LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004233 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004234
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004235 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004236 resolution->set_w(display.getWidth());
4237 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004238
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004239 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4240 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4241 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004242
Dominik Laskowski7e045462018-05-30 13:02:02 -07004243 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004244 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004245 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004246 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004247 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004248 }
4249 });
4250
4251 return layersProto;
4252}
4253
Mathias Agopian74d211a2013-04-22 16:55:35 +02004254void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4255 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004256{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004257 bool colorize = false;
4258 if (index < args.size()
4259 && (args[index] == String16("--color"))) {
4260 colorize = true;
4261 index++;
4262 }
4263
4264 Colorizer colorizer(colorize);
4265
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004266 // figure out if we're stuck somewhere
4267 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004268 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004269 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4270
4271 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004272 * Dump library configuration.
4273 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004274
4275 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004276 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004277 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004278 appendSfConfigString(result);
4279 appendUiConfigString(result);
4280 appendGuiConfigString(result);
4281 result.append("\n");
4282
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004283 result.append("\nDisplay identification data:\n");
4284 dumpDisplayIdentificationData(result);
4285
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004286 result.append("\nWide-Color information:\n");
4287 dumpWideColorInfo(result);
4288
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004289 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004290 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004291 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004292 result.append(SyncFeatures::getInstance().toString());
4293 result.append("\n");
4294
Andy McFadden41d67d72014-04-25 16:58:34 -07004295 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004296 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004297 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004298
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004299 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4300 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004301 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4302 getHwComposer().isConnected(displayId)) {
4303 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004304 result.appendFormat("Display %d: "
4305 "app phase %" PRId64 " ns, "
4306 "sf phase %" PRId64 " ns, "
4307 "early app phase %" PRId64 " ns, "
4308 "early sf phase %" PRId64 " ns, "
4309 "early app gl phase %" PRId64 " ns, "
4310 "early sf gl phase %" PRId64 " ns, "
4311 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4312 displayId,
4313 vsyncPhaseOffsetNs,
4314 sfVsyncPhaseOffsetNs,
4315 appEarlyOffset,
4316 sfEarlyOffset,
4317 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004318 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004319 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004320 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004321 result.append("\n");
4322
Dan Stozab90cf072015-03-05 11:05:59 -08004323 // Dump static screen stats
4324 result.append("\n");
4325 dumpStaticScreenStats(result);
4326 result.append("\n");
4327
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004328 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4329
Dan Stozae77c7662016-05-13 11:37:28 -07004330 dumpBufferingStats(result);
4331
Andy McFadden4803b742012-09-24 19:07:20 -07004332 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004333 * Dump the visible layer list
4334 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004335 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004336 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004337 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4338 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004339 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004340
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004341 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004342 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004343 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004344 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004345
David Sodman7e4ae112018-02-09 15:02:28 -08004346 result.append("\nFrame-Composition information:\n");
4347 dumpFrameCompositionInfo(result);
4348 result.append("\n");
4349
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004350 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004351 * Dump Display state
4352 */
4353
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004354 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004355 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004356 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004357 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004358 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004359 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004360 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004361
4362 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004363 * Dump SurfaceFlinger global state
4364 */
4365
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004366 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004367 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004368 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004369
Mathias Agopian888c8222012-08-04 21:10:38 -07004370 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004371 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004372
David Sodmanbc815282017-11-05 18:57:52 -08004373 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004374
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004375 if (display) {
4376 display->undefinedRegion.dump(result, "undefinedRegion");
4377 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4378 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004379 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004380 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004381 " gpu_to_cpu_unsupported : %d\n",
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004382 mTransactionFlags, !mGpuToCpuSupported);
4383
4384 if (display) {
4385 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4386 result.appendFormat(" refresh-rate : %f fps\n"
4387 " x-dpi : %f\n"
4388 " y-dpi : %f\n",
4389 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4390 activeConfig->getDpiY());
4391 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004392
Mathias Agopian74d211a2013-04-22 16:55:35 +02004393 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004394 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004395
4396 /*
4397 * VSYNC state
4398 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004399 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004400 result.append("\n");
4401
4402 /*
4403 * HWC layer minidump
4404 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004405 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004406 const int32_t displayId = display->getId();
4407 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004408 continue;
4409 }
4410
Dominik Laskowski7e045462018-05-30 13:02:02 -07004411 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004412 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004413 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004414 result.append("\n");
4415 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004416
4417 /*
4418 * Dump HWComposer state
4419 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004420 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004421 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004422 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004423 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004424 result.appendFormat(" h/w composer %s\n",
4425 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004426 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004427
4428 /*
4429 * Dump gralloc state
4430 */
4431 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4432 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004433
4434 /*
4435 * Dump VrFlinger state if in use.
4436 */
4437 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4438 result.append("VrFlinger state:\n");
4439 result.append(mVrFlinger->Dump().c_str());
4440 result.append("\n");
4441 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004442}
4443
Dominik Laskowski7e045462018-05-30 13:02:02 -07004444const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004445 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004446 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004447 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004448 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004449 }
4450 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004451
4452 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4453 static const Vector<sp<Layer>> empty;
4454 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004455}
4456
Keun young Park63f165f2012-08-31 10:53:36 -07004457bool SurfaceFlinger::startDdmConnection()
4458{
4459 void* libddmconnection_dso =
4460 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4461 if (!libddmconnection_dso) {
4462 return false;
4463 }
4464 void (*DdmConnection_start)(const char* name);
4465 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004466 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004467 if (!DdmConnection_start) {
4468 dlclose(libddmconnection_dso);
4469 return false;
4470 }
4471 (*DdmConnection_start)(getServiceName());
4472 return true;
4473}
4474
Chia-I Wu28f320b2018-05-03 11:02:56 -07004475void SurfaceFlinger::updateColorMatrixLocked() {
4476 mat4 colorMatrix;
4477 if (mGlobalSaturationFactor != 1.0f) {
4478 // Rec.709 luma coefficients
4479 float3 luminance{0.213f, 0.715f, 0.072f};
4480 luminance *= 1.0f - mGlobalSaturationFactor;
4481 mat4 saturationMatrix = mat4(
4482 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4483 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4484 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4485 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4486 );
4487 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4488 } else {
4489 colorMatrix = mClientColorMatrix * mDaltonizer();
4490 }
4491
4492 if (mCurrentState.colorMatrix != colorMatrix) {
4493 mCurrentState.colorMatrix = colorMatrix;
4494 mCurrentState.colorMatrixChanged = true;
4495 setTransactionFlags(eTransactionNeeded);
4496 }
4497}
4498
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004499status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004500#pragma clang diagnostic push
4501#pragma clang diagnostic error "-Wswitch-enum"
4502 switch (static_cast<ISurfaceComposerTag>(code)) {
4503 // These methods should at minimum make sure that the client requested
4504 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004505 case BOOT_FINISHED:
4506 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004507 case CREATE_CONNECTION:
4508 case CREATE_DISPLAY:
4509 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004510 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004511 case GET_ACTIVE_COLOR_MODE:
4512 case GET_ANIMATION_FRAME_STATS:
4513 case GET_HDR_CAPABILITIES:
4514 case SET_ACTIVE_CONFIG:
4515 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004516 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004517 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004518 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4519 IPCThreadState* ipc = IPCThreadState::self();
4520 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4521 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004522 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004523 }
Robert Carr1db73f62016-12-21 12:58:51 -08004524 return OK;
4525 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004526 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004527 IPCThreadState* ipc = IPCThreadState::self();
4528 const int pid = ipc->getCallingPid();
4529 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004530 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4531 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004532 return PERMISSION_DENIED;
4533 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004534 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004535 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004536 // Used by apps to hook Choreographer to SurfaceFlinger.
4537 case CREATE_DISPLAY_EVENT_CONNECTION:
4538 // The following calls are currently used by clients that do not
4539 // request necessary permissions. However, they do not expose any secret
4540 // information, so it is OK to pass them.
4541 case AUTHENTICATE_SURFACE:
4542 case GET_ACTIVE_CONFIG:
4543 case GET_BUILT_IN_DISPLAY:
4544 case GET_DISPLAY_COLOR_MODES:
4545 case GET_DISPLAY_CONFIGS:
4546 case GET_DISPLAY_STATS:
Yiwei Zhangcd3f9e92018-08-21 15:15:42 -07004547 case GET_DISPLAY_VIEWPORT:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004548 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4549 // Calling setTransactionState is safe, because you need to have been
4550 // granted a reference to Client* and Handle* to do anything with it.
4551 case SET_TRANSACTION_STATE:
4552 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4553 case CREATE_SCOPED_CONNECTION: {
4554 return OK;
4555 }
4556 case CAPTURE_LAYERS:
4557 case CAPTURE_SCREEN: {
4558 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004559 IPCThreadState* ipc = IPCThreadState::self();
4560 const int pid = ipc->getCallingPid();
4561 const int uid = ipc->getCallingUid();
4562 if ((uid != AID_GRAPHICS) &&
4563 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4564 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4565 return PERMISSION_DENIED;
4566 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004567 return OK;
4568 }
4569 // The following codes are deprecated and should never be allowed to access SF.
4570 case CONNECT_DISPLAY_UNUSED:
4571 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4572 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4573 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004574 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004575 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004576
4577 // These codes are used for the IBinder protocol to either interrogate the recipient
4578 // side of the transaction for its canonical interface descriptor or to dump its state.
4579 // We let them pass by default.
4580 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4581 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4582 code == IBinder::SYSPROPS_TRANSACTION) {
4583 return OK;
4584 }
4585 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4586 // in onTransact verifies that the user is root, and has access to use SF.
4587 if (code >= 1000 && code <= 1029) {
4588 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4589 return OK;
4590 }
4591 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4592 return PERMISSION_DENIED;
4593#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004594}
4595
Ana Krulec13be8ad2018-08-21 02:43:56 +00004596status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4597 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004598 status_t credentialCheck = CheckTransactCodeCredentials(code);
4599 if (credentialCheck != OK) {
4600 return credentialCheck;
4601 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004602
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004603 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4604 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004605 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004606 IPCThreadState* ipc = IPCThreadState::self();
4607 const int uid = ipc->getCallingUid();
4608 if (CC_UNLIKELY(uid != AID_SYSTEM
4609 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004610 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004611 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004612 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004613 return PERMISSION_DENIED;
4614 }
4615 int n;
4616 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004617 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004618 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004619 return NO_ERROR;
4620 case 1002: // SHOW_UPDATES
4621 n = data.readInt32();
4622 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004623 invalidateHwcGeometry();
4624 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004625 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004626 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004627 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004628 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004629 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004630 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004631 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004632 setTransactionFlags(
4633 eTransactionNeeded|
4634 eDisplayTransactionNeeded|
4635 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004636 return NO_ERROR;
4637 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004638 case 1006:{ // send empty update
4639 signalRefresh();
4640 return NO_ERROR;
4641 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004642 case 1008: // toggle use of hw composer
4643 n = data.readInt32();
4644 mDebugDisableHWC = n ? 1 : 0;
4645 invalidateHwcGeometry();
4646 repaintEverything();
4647 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004648 case 1009: // toggle use of transform hint
4649 n = data.readInt32();
4650 mDebugDisableTransformHint = n ? 1 : 0;
4651 invalidateHwcGeometry();
4652 repaintEverything();
4653 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004654 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004655 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004656 reply->writeInt32(0);
4657 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004658 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004659 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004660 return NO_ERROR;
4661 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004662 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004663 if (!display) {
4664 return NAME_NOT_FOUND;
4665 }
4666
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004667 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004668 return NO_ERROR;
4669 }
4670 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004671 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004672 // daltonize
4673 n = data.readInt32();
4674 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004675 case 1:
4676 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4677 break;
4678 case 2:
4679 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4680 break;
4681 case 3:
4682 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4683 break;
4684 default:
4685 mDaltonizer.setType(ColorBlindnessType::None);
4686 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004687 }
4688 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004689 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004690 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004691 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004692 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004693
4694 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004695 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004696 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004697 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004698 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004699 // apply a color matrix
4700 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004701 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004702 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004703 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004704 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004705 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004706 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004707 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004708 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004709 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004710 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004711
4712 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4713 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004714 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004715 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4716 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4717 }
4718
Chia-I Wu28f320b2018-05-03 11:02:56 -07004719 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004720 return NO_ERROR;
4721 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004722 // This is an experimental interface
4723 // Needs to be shifted to proper binder interface when we productize
4724 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004725 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07004726 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004727 return NO_ERROR;
4728 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004729 case 1017: {
4730 n = data.readInt32();
4731 mForceFullDamage = static_cast<bool>(n);
4732 return NO_ERROR;
4733 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004734 case 1018: { // Modify Choreographer's phase offset
4735 n = data.readInt32();
4736 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4737 return NO_ERROR;
4738 }
4739 case 1019: { // Modify SurfaceFlinger's phase offset
4740 n = data.readInt32();
4741 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4742 return NO_ERROR;
4743 }
Irvel468051e2016-06-13 16:44:44 -07004744 case 1020: { // Layer updates interceptor
4745 n = data.readInt32();
4746 if (n) {
4747 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004748 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004749 }
4750 else{
4751 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004752 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004753 }
4754 return NO_ERROR;
4755 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004756 case 1021: { // Disable HWC virtual displays
4757 n = data.readInt32();
4758 mUseHwcVirtualDisplays = !n;
4759 return NO_ERROR;
4760 }
Romain Guy0147a172017-06-01 13:53:56 -07004761 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004762 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004763 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004764
Chia-I Wu28f320b2018-05-03 11:02:56 -07004765 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004766 return NO_ERROR;
4767 }
Romain Guy54f154a2017-10-24 21:40:32 +01004768 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004769 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004770 invalidateHwcGeometry();
4771 repaintEverything();
4772 return NO_ERROR;
4773 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004774 // TODO(b/111505327): Find out whether the usage of 1024 can switch to 1030,
4775 // deprecate 1024 if they can.
4776 case 1024: { // Does device have wide color gamut display?
Romain Guy54f154a2017-10-24 21:40:32 +01004777 reply->writeBool(hasWideColorDisplay);
4778 return NO_ERROR;
4779 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004780 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004781 n = data.readInt32();
4782 if (n) {
4783 ALOGV("LayerTracing enabled");
4784 mTracing.enable();
4785 doTracing("tracing.enable");
4786 reply->writeInt32(NO_ERROR);
4787 } else {
4788 ALOGV("LayerTracing disabled");
4789 status_t err = mTracing.disable();
4790 reply->writeInt32(err);
4791 }
4792 return NO_ERROR;
4793 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004794 case 1026: { // Get layer tracing status
4795 reply->writeBool(mTracing.isEnabled());
4796 return NO_ERROR;
4797 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004798 // Is a DisplayColorSetting supported?
4799 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004800 const auto display = getDefaultDisplayDevice();
4801 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004802 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004803 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004804
4805 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4806 switch (setting) {
4807 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07004808 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004809 break;
4810 case DisplayColorSetting::UNMANAGED:
4811 reply->writeBool(true);
4812 break;
4813 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004814 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004815 break;
4816 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004817 reply->writeBool(
4818 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004819 break;
4820 }
4821 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004822 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004823 // Is VrFlinger active?
4824 case 1028: {
4825 Mutex::Autolock _l(mStateLock);
4826 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4827 return NO_ERROR;
4828 }
David Sodman6d46c1e2018-07-13 12:59:48 -07004829 case 1029: {
4830 // Code 1029 is an experimental feature that allows applications to
4831 // simulate a high frequency panel by setting a multiplier and divisor
4832 // on the VSYNC-sf clock. If either the multiplier or divisor are
4833 // 0, then the code will set both to 1 to return the VSYNC-sf clock
4834 // to it's normal frequency.
4835 int multiplier = data.readInt32();
4836 int divisor = data.readInt32();
4837
4838 if ((multiplier == 0) || (divisor == 0)) {
4839 multiplier = 1;
4840 divisor = 1;
4841 }
4842
4843 if ((multiplier == 1) && (divisor == 1)) {
4844 enableHardwareVsync();
4845 } else {
4846 disableHardwareVsync(true);
4847 }
4848 getBE().mHwc->getActiveConfig(DisplayDevice::DISPLAY_PRIMARY)
4849 ->scalePanelFrequency(multiplier, divisor);
4850 mPrimaryDispSync->scalePeriod(multiplier, divisor);
4851
4852 ATRACE_INT("PeriodMultiplier", multiplier);
4853 ATRACE_INT("PeriodDivisor", divisor);
4854 return NO_ERROR;
4855 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004856 // Is device color managed?
4857 case 1030: {
4858 reply->writeBool(useColorManagement);
4859 return NO_ERROR;
4860 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004861 }
4862 }
4863 return err;
4864}
4865
Steven Thomas6d8110b2017-08-31 18:24:21 -07004866void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004867 android_atomic_or(1, &mRepaintEverything);
4868 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004869}
4870
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004871// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4872class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004873public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004874 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4875 ~WindowDisconnector() {
4876 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004877 }
4878
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004879private:
4880 ANativeWindow* mWindow;
4881 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004882};
4883
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004884status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4885 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4886 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4887 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004888 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004889 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004890
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004891 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004892
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004893 const auto display = getDisplayDeviceLocked(displayToken);
4894 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004895
Yiwei Zhang06a58e22018-08-20 16:42:23 -07004896 const Rect& dispScissor = display->getScissor();
4897 if (!dispScissor.isEmpty()) {
4898 sourceCrop.set(dispScissor);
4899 // adb shell screencap will default reqWidth and reqHeight to zeros.
4900 if (reqWidth == 0 || reqHeight == 0) {
Yiwei Zhangec90e582018-08-21 22:11:37 -07004901 reqWidth = uint32_t(display->getViewport().width());
4902 reqHeight = uint32_t(display->getViewport().height());
Yiwei Zhang06a58e22018-08-20 16:42:23 -07004903 }
4904 }
4905
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004906 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004907
4908 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004909 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004910 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004911}
4912
4913status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004914 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004915 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004916 ATRACE_CALL();
4917
4918 class LayerRenderArea : public RenderArea {
4919 public:
Robert Carr578038f2018-03-09 12:25:24 -08004920 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4921 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004922 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004923 mLayer(layer),
4924 mCrop(crop),
4925 mFlinger(flinger),
4926 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07004927 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004928 Rect getBounds() const override {
4929 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07004930 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07004931 }
Marissa Wall61c58622018-07-18 10:12:20 -07004932 int getHeight() const override {
4933 return mLayer->getActiveHeight(mLayer->getDrawingState());
4934 }
4935 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07004936 bool isSecure() const override { return false; }
4937 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004938 Rect getSourceCrop() const override {
4939 if (mCrop.isEmpty()) {
4940 return getBounds();
4941 } else {
4942 return mCrop;
4943 }
4944 }
Robert Carr578038f2018-03-09 12:25:24 -08004945 class ReparentForDrawing {
4946 public:
4947 const sp<Layer>& oldParent;
4948 const sp<Layer>& newParent;
4949
4950 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4951 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004952 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004953 }
Robert Carr15eae092018-03-23 13:43:53 -07004954 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004955 };
4956
4957 void render(std::function<void()> drawLayers) override {
4958 if (!mChildrenOnly) {
4959 mTransform = mLayer->getTransform().inverse();
4960 drawLayers();
4961 } else {
4962 Rect bounds = getBounds();
4963 screenshotParentLayer =
4964 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4965 bounds.getWidth(), bounds.getHeight(), 0);
4966
4967 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4968 drawLayers();
4969 }
4970 }
chaviwa76b2712017-09-20 12:02:26 -07004971
chaviwa76b2712017-09-20 12:02:26 -07004972 private:
chaviw7206d492017-11-10 16:16:12 -08004973 const sp<Layer> mLayer;
4974 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004975
4976 // In the "childrenOnly" case we reparent the children to a screenshot
4977 // layer which has no properties set and which does not draw.
4978 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07004979 ui::Transform mTransform;
Robert Carr578038f2018-03-09 12:25:24 -08004980
4981 SurfaceFlinger* mFlinger;
4982 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004983 };
4984
4985 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4986 auto parent = layerHandle->owner.promote();
4987
chaviw7206d492017-11-10 16:16:12 -08004988 if (parent == nullptr || parent->isPendingRemoval()) {
4989 ALOGE("captureLayers called with a removed parent");
4990 return NAME_NOT_FOUND;
4991 }
4992
Robert Carr578038f2018-03-09 12:25:24 -08004993 const int uid = IPCThreadState::self()->getCallingUid();
4994 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4995 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4996 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4997 return PERMISSION_DENIED;
4998 }
4999
chaviw7206d492017-11-10 16:16:12 -08005000 Rect crop(sourceCrop);
5001 if (sourceCrop.width() <= 0) {
5002 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005003 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005004 }
5005
5006 if (sourceCrop.height() <= 0) {
5007 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005008 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005009 }
5010
5011 int32_t reqWidth = crop.width() * frameScale;
5012 int32_t reqHeight = crop.height() * frameScale;
5013
Robert Carr578038f2018-03-09 12:25:24 -08005014 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005015
Robert Carr578038f2018-03-09 12:25:24 -08005016 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005017 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5018 if (!layer->isVisible()) {
5019 return;
Robert Carr578038f2018-03-09 12:25:24 -08005020 } else if (childrenOnly && layer == parent.get()) {
5021 return;
chaviwa76b2712017-09-20 12:02:26 -07005022 }
5023 visitor(layer);
5024 });
5025 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005026 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005027}
5028
5029status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5030 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005031 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005032 bool useIdentityTransform) {
5033 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005034
Iris Chang7501ed62018-04-30 14:45:42 +08005035 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07005036
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005037 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5038 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5039 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5040 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005041
5042 // This mutex protects syncFd and captureResult for communication of the return values from the
5043 // main thread back to this Binder thread
5044 std::mutex captureMutex;
5045 std::condition_variable captureCondition;
5046 std::unique_lock<std::mutex> captureLock(captureMutex);
5047 int syncFd = -1;
5048 std::optional<status_t> captureResult;
5049
Robert Carr03480e22018-01-04 16:02:06 -08005050 const int uid = IPCThreadState::self()->getCallingUid();
5051 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5052
Dominik Laskowski8c001672018-05-30 16:52:06 -07005053 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005054 // If there is a refresh pending, bug out early and tell the binder thread to try again
5055 // after the refresh.
5056 if (mRefreshPending) {
5057 ATRACE_NAME("Skipping screenshot for now");
5058 std::unique_lock<std::mutex> captureLock(captureMutex);
5059 captureResult = std::make_optional<status_t>(EAGAIN);
5060 captureCondition.notify_one();
5061 return;
5062 }
5063
5064 status_t result = NO_ERROR;
5065 int fd = -1;
5066 {
5067 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005068 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005069 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5070 useIdentityTransform, forSystem, &fd);
5071 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005072 }
5073
5074 {
5075 std::unique_lock<std::mutex> captureLock(captureMutex);
5076 syncFd = fd;
5077 captureResult = std::make_optional<status_t>(result);
5078 captureCondition.notify_one();
5079 }
5080 });
5081
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005082 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005083 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005084 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005085 while (*captureResult == EAGAIN) {
5086 captureResult.reset();
5087 result = postMessageAsync(message);
5088 if (result != NO_ERROR) {
5089 return result;
5090 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005091 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005092 }
5093 result = *captureResult;
5094 }
5095
5096 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005097 sync_wait(syncFd, -1);
5098 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005099 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005100
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005101 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005102}
5103
chaviwa76b2712017-09-20 12:02:26 -07005104void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5105 TraverseLayersFunction traverseLayers, bool yswap,
5106 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005107 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005108
Lloyd Pique144e1162017-12-20 16:44:52 -08005109 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005110
5111 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005112 const auto raWidth = renderArea.getWidth();
5113 const auto raHeight = renderArea.getHeight();
5114
5115 const auto reqWidth = renderArea.getReqWidth();
5116 const auto reqHeight = renderArea.getReqHeight();
5117 Rect sourceCrop = renderArea.getSourceCrop();
5118
Iris Chang7501ed62018-04-30 14:45:42 +08005119 bool filtering = false;
5120 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5121 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5122 static_cast<int32_t>(reqHeight) != raWidth;
5123 } else {
5124 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5125 static_cast<int32_t>(reqHeight) != raHeight;
5126 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005127
Dan Stozac1879002014-05-22 15:59:05 -07005128 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005129 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005130 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005131 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005132 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
Peiyong Linefefaac2018-08-17 12:27:51 -07005133 ui::Transform tr;
Iris Chang7501ed62018-04-30 14:45:42 +08005134 uint32_t flags = 0x00;
5135 switch (mPrimaryDisplayOrientation) {
5136 case DisplayState::eOrientation90:
Peiyong Linefefaac2018-08-17 12:27:51 -07005137 flags = ui::Transform::ROT_90;
Iris Chang7501ed62018-04-30 14:45:42 +08005138 break;
5139 case DisplayState::eOrientation180:
Peiyong Linefefaac2018-08-17 12:27:51 -07005140 flags = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005141 break;
5142 case DisplayState::eOrientation270:
Peiyong Linefefaac2018-08-17 12:27:51 -07005143 flags = ui::Transform::ROT_270;
Iris Chang7501ed62018-04-30 14:45:42 +08005144 break;
5145 }
5146 tr.set(flags, raWidth, raHeight);
5147 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005148 }
5149
5150 // ensure that sourceCrop is inside screen
5151 if (sourceCrop.left < 0) {
5152 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5153 }
chaviwa76b2712017-09-20 12:02:26 -07005154 if (sourceCrop.right > raWidth) {
5155 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005156 }
5157 if (sourceCrop.top < 0) {
5158 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5159 }
chaviwa76b2712017-09-20 12:02:26 -07005160 if (sourceCrop.bottom > raHeight) {
5161 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005162 }
5163
Chia-I Wu36574d92018-05-16 10:54:36 -07005164 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5165 engine.setOutputDataSpace(Dataspace::SRGB);
5166 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005167
Mathias Agopian180f10d2013-04-10 22:55:41 -07005168 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005169 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005170
Peiyong Linefefaac2018-08-17 12:27:51 -07005171 ui::Transform::orientation_flags rotation = renderArea.getRotationFlags();
Iris Chang7501ed62018-04-30 14:45:42 +08005172 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5173 // convert hw orientation into flag presentation
5174 // here inverse transform needed
5175 uint8_t hw_rot_90 = 0x00;
5176 uint8_t hw_flip_hv = 0x00;
5177 switch (mPrimaryDisplayOrientation) {
5178 case DisplayState::eOrientation90:
Peiyong Linefefaac2018-08-17 12:27:51 -07005179 hw_rot_90 = ui::Transform::ROT_90;
5180 hw_flip_hv = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005181 break;
5182 case DisplayState::eOrientation180:
Peiyong Linefefaac2018-08-17 12:27:51 -07005183 hw_flip_hv = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005184 break;
5185 case DisplayState::eOrientation270:
Peiyong Linefefaac2018-08-17 12:27:51 -07005186 hw_rot_90 = ui::Transform::ROT_90;
Iris Chang7501ed62018-04-30 14:45:42 +08005187 break;
5188 }
5189
5190 // transform flags operation
5191 // 1) flip H V if both have ROT_90 flag
5192 // 2) XOR these flags
Peiyong Linefefaac2018-08-17 12:27:51 -07005193 uint8_t rotation_rot_90 = rotation & ui::Transform::ROT_90;
5194 uint8_t rotation_flip_hv = rotation & ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005195 if (rotation_rot_90 & hw_rot_90) {
Peiyong Linefefaac2018-08-17 12:27:51 -07005196 rotation_flip_hv = (~rotation_flip_hv) & ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005197 }
Peiyong Linefefaac2018-08-17 12:27:51 -07005198 rotation = static_cast<ui::Transform::orientation_flags>
Iris Chang7501ed62018-04-30 14:45:42 +08005199 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5200 }
5201
Mathias Agopian180f10d2013-04-10 22:55:41 -07005202 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005203 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005204 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005205 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005206
chaviw50da5042018-04-09 13:49:37 -07005207 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005208 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005209 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005210
chaviwa76b2712017-09-20 12:02:26 -07005211 traverseLayers([&](Layer* layer) {
5212 if (filtering) layer->setFiltering(true);
David Sodmanca10ed22018-04-16 14:10:25 -07005213 layer->drawNow(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005214 if (filtering) layer->setFiltering(false);
5215 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005216}
5217
chaviwa76b2712017-09-20 12:02:26 -07005218status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5219 TraverseLayersFunction traverseLayers,
5220 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005221 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005222 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005223 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005224 ATRACE_CALL();
5225
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005226 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005227
5228 traverseLayers([&](Layer* layer) {
5229 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5230 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005231
Robert Carr03480e22018-01-04 16:02:06 -08005232 // We allow the system server to take screenshots of secure layers for
5233 // use in situations like the Screen-rotation animation and place
5234 // the impetus on WindowManager to not persist them.
5235 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005236 ALOGW("FB is protected: PERMISSION_DENIED");
5237 return PERMISSION_DENIED;
5238 }
5239
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005240 // this binds the given EGLImage as a framebuffer for the
5241 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005242 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005243 if (bufferBond.getStatus() != NO_ERROR) {
5244 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005245 return INVALID_OPERATION;
5246 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005247
Dan Stozaabcda352017-06-01 14:37:39 -07005248 // this will in fact render into our dequeued buffer
5249 // via an FBO, which means we didn't have to create
5250 // an EGLSurface and therefore we're not
5251 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005252 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005253
Dan Stozaabcda352017-06-01 14:37:39 -07005254 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005255 getRenderEngine().finish();
5256 *outSyncFd = -1;
5257
chaviwa76b2712017-09-20 12:02:26 -07005258 const auto reqWidth = renderArea.getReqWidth();
5259 const auto reqHeight = renderArea.getReqHeight();
5260
Dan Stozaabcda352017-06-01 14:37:39 -07005261 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5262 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005263 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005264 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005265 } else {
5266 base::unique_fd syncFd = getRenderEngine().flush();
5267 if (syncFd < 0) {
5268 getRenderEngine().finish();
5269 }
5270 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005271 }
5272
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005273 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005274}
5275
Mathias Agopiand5556842013-09-19 17:08:37 -07005276void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005277 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005278 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005279 for (size_t y = 0; y < h; y++) {
5280 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5281 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005282 if (p[x] != 0xFF000000) return;
5283 }
5284 }
chaviwa76b2712017-09-20 12:02:26 -07005285 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005286
Robert Carr2047fae2016-11-28 14:09:09 -08005287 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005288 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005289 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005290 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5291 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5292 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5293 static_cast<float>(state.color.a));
5294 i++;
5295 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005296 }
5297}
5298
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005299// ---------------------------------------------------------------------------
5300
Dan Stoza412903f2017-04-27 13:42:17 -07005301void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5302 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005303}
5304
Dan Stoza412903f2017-04-27 13:42:17 -07005305void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5306 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005307}
5308
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005309void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5310 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005311 const LayerVector::Visitor& visitor) {
5312 // We loop through the first level of layers without traversing,
5313 // as we need to interpret min/max layer Z in the top level Z space.
5314 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005315 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005316 continue;
5317 }
5318 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005319 // relative layers are traversed in Layer::traverseInZOrder
5320 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005321 continue;
5322 }
5323 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005324 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005325 return;
5326 }
chaviwa76b2712017-09-20 12:02:26 -07005327 if (!layer->isVisible()) {
5328 return;
5329 }
5330 visitor(layer);
5331 });
5332 }
5333}
5334
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005335}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005336
Lloyd Pique074e8122018-07-26 12:57:23 -07005337
Mathias Agopian3f844832013-08-07 21:24:32 -07005338#if defined(__gl_h_)
5339#error "don't include gl/gl.h in this file"
5340#endif
5341
5342#if defined(__gl2_h_)
5343#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005344#endif