blob: 6162b1632237ff4f4fc6d68cb78aca4fa9d08483 [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 {
Hernan Liatis57568932018-08-16 17:07:08 -0700783 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700784 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700785 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800786 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700787 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700788 }
789 return density;
790 }
791 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700792 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700793 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700794 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700795 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
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700808 info.w = hwConfig->getWidth();
809 info.h = hwConfig->getHeight();
810 // Default display viewport to display width and height
811 info.viewportW = info.w;
812 info.viewportH = info.h;
813
Dan Stoza7f7da322014-05-02 15:26:25 -0700814 if (type == DisplayDevice::DISPLAY_PRIMARY) {
815 // The density of the device is provided by a build property
816 float density = Density::getBuildDensity() / 160.0f;
817 if (density == 0) {
818 // the build doesn't provide a density -- this is wrong!
819 // use xdpi instead
820 ALOGE("ro.sf.lcd_density must be defined as a build property");
821 density = xdpi / 160.0f;
822 }
823 if (Density::getEmuDensity()) {
824 // if "qemu.sf.lcd_density" is specified, it overrides everything
825 xdpi = ydpi = density = Density::getEmuDensity();
826 density /= 160.0f;
827 }
828 info.density = density;
829
830 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700831 const auto display = getDefaultDisplayDeviceLocked();
832 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700833
834 // This is for screenrecord
835 const Rect viewport = display->getViewport();
836 if (viewport.isValid()) {
837 info.viewportW = uint32_t(viewport.getWidth());
838 info.viewportH = uint32_t(viewport.getHeight());
839 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700840 } else {
841 // TODO: where should this value come from?
842 static const int TV_DENSITY = 213;
843 info.density = TV_DENSITY / 160.0f;
844 info.orientation = 0;
845 }
846
Dan Stoza7f7da322014-05-02 15:26:25 -0700847 info.xdpi = xdpi;
848 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800849 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900850 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800851
Andy McFadden91b2ca82014-06-13 14:04:23 -0700852 // This is how far in advance a buffer must be queued for
853 // presentation at a given time. If you want a buffer to appear
854 // on the screen at time N, you must submit the buffer before
855 // (N - presentationDeadline).
856 //
857 // Normally it's one full refresh period (to give SF a chance to
858 // latch the buffer), but this can be reduced by configuring a
859 // DispSync offset. Any additional delays introduced by the hardware
860 // composer or panel must be accounted for here.
861 //
862 // We add an additional 1ms to allow for processing time and
863 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800864 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800865 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700866
867 // All non-virtual displays are currently considered secure.
868 info.secure = true;
869
Iris Chang7501ed62018-04-30 14:45:42 +0800870 if (type == DisplayDevice::DISPLAY_PRIMARY &&
871 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
872 std::swap(info.w, info.h);
873 }
874
Michael Wright28f24d02016-07-12 13:30:53 -0700875 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700876 }
877
Dan Stoza7f7da322014-05-02 15:26:25 -0700878 return NO_ERROR;
879}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700880
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700881status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
882 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700883 return BAD_VALUE;
884 }
885
886 // FIXME for now we always return stats for the primary display
887 memset(stats, 0, sizeof(*stats));
Lloyd Pique41be5d22018-06-21 13:11:48 -0700888 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
889 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700890 return NO_ERROR;
891}
892
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700893int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
894 const auto display = getDisplayDevice(displayToken);
895 if (!display) {
896 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800897 return BAD_VALUE;
898 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700899
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700900 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700901}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700902
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700903void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
904 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700905 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700906 return;
907 }
908
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700909 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700910 ALOGW("Trying to set config for virtual display");
911 return;
912 }
913
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700914 display->setActiveConfig(mode);
915 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700916}
917
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700918status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700919 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700920 Vector<DisplayInfo> configs;
921 getDisplayConfigs(displayToken, &configs);
922 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
923 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
924 configs.size());
925 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700926 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700927 const auto display = getDisplayDevice(displayToken);
928 if (!display) {
929 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
930 displayToken.get());
931 } else if (display->isVirtual()) {
932 ALOGW("Attempt to set active config %d for virtual display", mode);
933 } else {
934 setActiveConfigInternal(display, mode);
935 }
936 }));
937
Mathias Agopian888c8222012-08-04 21:10:38 -0700938 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700939}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700940status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
941 Vector<ColorMode>* outColorModes) {
942 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700943 return BAD_VALUE;
944 }
945
Michael Wright28f24d02016-07-12 13:30:53 -0700946 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700947 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
948 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700949 type = i;
950 break;
951 }
952 }
953
954 if (type < 0) {
955 return type;
956 }
957
Peiyong Lina52f0292018-03-14 17:26:31 -0700958 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700959 {
960 ConditionalLock _l(mStateLock,
961 std::this_thread::get_id() != mMainThreadId);
962 modes = getHwComposer().getColorModes(type);
963 }
Michael Wright28f24d02016-07-12 13:30:53 -0700964 outColorModes->clear();
965 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
966
967 return NO_ERROR;
968}
969
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700970ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
971 if (const auto display = getDisplayDevice(displayToken)) {
972 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -0700973 }
Peiyong Lina52f0292018-03-14 17:26:31 -0700974 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -0700975}
976
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700977void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
978 Dataspace dataSpace, RenderIntent renderIntent) {
979 ColorMode currentMode = display->getActiveColorMode();
980 Dataspace currentDataSpace = display->getCompositionDataSpace();
981 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -0700982
Peiyong Lin38e9a562018-04-10 16:24:20 -0700983 if (mode == currentMode && dataSpace == currentDataSpace &&
984 renderIntent == currentRenderIntent) {
985 return;
986 }
987
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700988 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -0700989 ALOGW("Trying to set config for virtual display");
990 return;
991 }
992
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700993 display->setActiveColorMode(mode);
994 display->setCompositionDataSpace(dataSpace);
995 display->setActiveRenderIntent(renderIntent);
996 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800997
998 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700999 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1000 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001001}
1002
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001003status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001004 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001005 Vector<ColorMode> modes;
1006 getDisplayColorModes(displayToken, &modes);
1007 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1008 if (mode < ColorMode::NATIVE || !exists) {
1009 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1010 decodeColorMode(mode).c_str(), mode, displayToken.get());
1011 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001012 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001013 const auto display = getDisplayDevice(displayToken);
1014 if (!display) {
1015 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1016 decodeColorMode(mode).c_str(), mode, displayToken.get());
1017 } else if (display->isVirtual()) {
1018 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1019 decodeColorMode(mode).c_str(), mode);
1020 } else {
1021 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1022 RenderIntent::COLORIMETRIC);
1023 }
1024 }));
1025
Michael Wright28f24d02016-07-12 13:30:53 -07001026 return NO_ERROR;
1027}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001028
Svetoslavd85084b2014-03-20 10:28:31 -07001029status_t SurfaceFlinger::clearAnimationFrameStats() {
1030 Mutex::Autolock _l(mStateLock);
1031 mAnimFrameTracker.clearStats();
1032 return NO_ERROR;
1033}
1034
1035status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1036 Mutex::Autolock _l(mStateLock);
1037 mAnimFrameTracker.getStats(outStats);
1038 return NO_ERROR;
1039}
1040
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001041status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1042 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001043 Mutex::Autolock _l(mStateLock);
1044
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001045 const auto display = getDisplayDeviceLocked(displayToken);
1046 if (!display) {
1047 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001048 return BAD_VALUE;
1049 }
1050
Peiyong Linfb069302018-04-25 14:34:31 -07001051 // At this point the DisplayDeivce should already be set up,
1052 // meaning the luminance information is already queried from
1053 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001054 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001055 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1056 capabilities.getDesiredMaxLuminance(),
1057 capabilities.getDesiredMaxAverageLuminance(),
1058 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001059
1060 return NO_ERROR;
1061}
1062
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001063status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001064 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001065 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001066
Chia-I Wu90f669f2017-10-05 14:24:41 -07001067 if (mInjectVSyncs == enable) {
1068 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001069 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001070
1071 if (enable) {
1072 ALOGV("VSync Injections enabled");
1073 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001074 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001075 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001076 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001077 impl::EventThread::InterceptVSyncsCallback(),
1078 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001079 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001080 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001081 } else {
1082 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001083 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001084 }
1085
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001086 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001087 }));
1088
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001089 return NO_ERROR;
1090}
1091
1092status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001093 Mutex::Autolock _l(mStateLock);
1094
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001095 if (!mInjectVSyncs) {
1096 ALOGE("VSync Injections not enabled");
1097 return BAD_VALUE;
1098 }
1099 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1100 ALOGV("Injecting VSync inside SurfaceFlinger");
1101 mVSyncInjector->onInjectSyncEvent(when);
1102 }
1103 return NO_ERROR;
1104}
1105
Lloyd Pique755e3192018-01-31 16:46:15 -08001106status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1107 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001108 // Try to acquire a lock for 1s, fail gracefully
1109 const status_t err = mStateLock.timedLock(s2ns(1));
1110 const bool locked = (err == NO_ERROR);
1111 if (!locked) {
1112 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1113 return TIMED_OUT;
1114 }
1115
1116 outLayers->clear();
1117 mCurrentState.traverseInZOrder([&](Layer* layer) {
1118 outLayers->push_back(layer->getLayerDebugInfo());
1119 });
1120
1121 mStateLock.unlock();
1122 return NO_ERROR;
1123}
1124
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001125// ----------------------------------------------------------------------------
1126
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001127sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1128 ISurfaceComposer::VsyncSource vsyncSource) {
1129 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1130 return mSFEventThread->createEventConnection();
1131 } else {
1132 return mEventThread->createEventConnection();
1133 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001134}
1135
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001136// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001137
1138void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001139 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001140}
1141
1142void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001143 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001144}
1145
1146void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001147 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001148}
1149
1150void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001151 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001152 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001153}
1154
1155status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001156 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001157 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001158}
1159
1160status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001161 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001162 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001163 if (res == NO_ERROR) {
1164 msg->wait();
1165 }
1166 return res;
1167}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001168
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001169void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001170 do {
1171 waitForEvent();
1172 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001173}
1174
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001175void SurfaceFlinger::enableHardwareVsync() {
1176 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001177 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001178 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001179 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001180 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001181 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001182}
1183
Jesse Hall948fe0c2013-10-14 12:56:09 -07001184void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001185 Mutex::Autolock _l(mHWVsyncLock);
1186
Jesse Hall948fe0c2013-10-14 12:56:09 -07001187 if (makeAvailable) {
1188 mHWVsyncAvailable = true;
1189 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001190 // Hardware vsync is not currently available, so abort the resync
1191 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001192 return;
1193 }
1194
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001195 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1196 if (!getHwComposer().isConnected(displayId)) {
1197 return;
1198 }
1199
1200 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001201 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001202
Lloyd Pique41be5d22018-06-21 13:11:48 -07001203 mPrimaryDispSync->reset();
1204 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001205
1206 if (!mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001207 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001208 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001209 mPrimaryHWVsyncEnabled = true;
1210 }
1211}
1212
Jesse Hall948fe0c2013-10-14 12:56:09 -07001213void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001214 Mutex::Autolock _l(mHWVsyncLock);
1215 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001216 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001217 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001218 mPrimaryHWVsyncEnabled = false;
1219 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001220 if (makeUnavailable) {
1221 mHWVsyncAvailable = false;
1222 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001223}
1224
Tim Murray4a4e4a22016-04-19 16:29:23 +00001225void SurfaceFlinger::resyncWithRateLimit() {
1226 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001227
1228 // No explicit locking is needed here since EventThread holds a lock while calling this method
1229 static nsecs_t sLastResyncAttempted = 0;
1230 const nsecs_t now = systemTime();
1231 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001232 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001233 }
Dan Stoza57164302017-05-08 14:03:54 -07001234 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001235}
1236
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001237void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1238 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001239 ATRACE_NAME("SF onVsync");
1240
Steven Thomas3cfac282017-02-06 12:29:30 -08001241 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001242 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001243 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001244 return;
1245 }
1246
1247 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001248 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001249 return;
1250 }
1251
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001252 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1253 // For now, we don't do anything with external display vsyncs.
1254 return;
1255 }
1256
Jamie Gennisd1700752013-10-14 12:22:52 -07001257 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001258
Jamie Gennisd1700752013-10-14 12:22:52 -07001259 { // Scope for the lock
1260 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001261 if (mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001262 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001263 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001264 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001265
1266 if (needsHwVsync) {
1267 enableHardwareVsync();
1268 } else {
1269 disableHardwareVsync(false);
1270 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001271}
1272
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001273void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001274 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1275 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001276}
1277
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001278void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001279 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001280 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001281 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001282
Lloyd Piqueba04e622017-12-14 17:11:26 -08001283 // Ignore events that do not have the right sequenceId.
1284 if (sequenceId != getBE().mComposerSequenceId) {
1285 return;
1286 }
1287
Steven Thomasb02664d2017-07-26 18:48:28 -07001288 // Only lock if we're not on the main thread. This function is normally
1289 // called on a hwbinder thread, but for the primary display it's called on
1290 // the main thread with the state lock already held, so don't attempt to
1291 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001292 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001293
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001294 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001295
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001296 if (std::this_thread::get_id() == mMainThreadId) {
1297 // Process all pending hot plug events immediately if we are on the main thread.
1298 processDisplayHotplugEventsLocked();
1299 }
1300
Lloyd Piqueba04e622017-12-14 17:11:26 -08001301 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001302}
1303
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001304void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001305 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001306 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001307 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001308 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001309 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001310}
1311
Dan Stoza9e56aa02015-11-02 13:00:03 -08001312void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001313 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001314 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001315 getHwComposer().setVsyncEnabled(disp,
1316 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001317}
1318
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001319// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001320void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001321 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001322 // Clear the drawing state so that the logic inside of
1323 // handleTransactionLocked will fire. It will determine the delta between
1324 // mCurrentState and mDrawingState and re-apply all changes when we make the
1325 // transition.
1326 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001327 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001328 mDisplays.clear();
1329}
1330
Steven Thomas050b2c82017-03-06 11:45:16 -08001331void SurfaceFlinger::updateVrFlinger() {
1332 if (!mVrFlinger)
1333 return;
1334 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001335 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001336 return;
1337 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001338
David Sodman105b7dc2017-11-04 20:28:14 -07001339 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001340 ALOGE("Vr flinger is only supported for remote hardware composer"
1341 " service connections. Ignoring request to transition to vr"
1342 " flinger.");
1343 mVrFlingerRequestsDisplay = false;
1344 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001345 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001346
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001347 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001348
Steven Thomas0123ac62018-07-12 11:32:34 -07001349 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001350 LOG_ALWAYS_FATAL_IF(!display);
1351 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001352 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1353 // called below. Clear the reference now so we don't accidentally use it
1354 // later.
1355 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001356
Steven Thomasb02664d2017-07-26 18:48:28 -07001357 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001358 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001359 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001360
Steven Thomasb02664d2017-07-26 18:48:28 -07001361 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001362 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001363 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1364 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001365 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001366
David Sodman105b7dc2017-11-04 20:28:14 -07001367 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1368 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001369
1370 if (vrFlingerRequestsDisplay) {
1371 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001372 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001373
1374 mVisibleRegionsDirty = true;
1375 invalidateHwcGeometry();
1376
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001377 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001378 display = getDefaultDisplayDeviceLocked();
1379 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001380 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001381
Steven Thomasb02664d2017-07-26 18:48:28 -07001382 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001383 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001384 const nsecs_t period = activeConfig->getVsyncPeriod();
1385 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001386
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001387 // The present fences returned from vr_hwc are not an accurate
1388 // representation of vsync times.
Lloyd Pique41be5d22018-06-21 13:11:48 -07001389 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1390 !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001391
Steven Thomasb02664d2017-07-26 18:48:28 -07001392 // Use phase of 0 since phase is not known.
1393 // Use latency of 0, which will snap to the ideal latency.
1394 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001395
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001396 resyncToHardwareVsync(false);
1397
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001398 android_atomic_or(1, &mRepaintEverything);
1399 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001400}
1401
Mathias Agopian4fec8732012-06-29 14:12:52 -07001402void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001403 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001404 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001405 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001406 bool frameMissed = !mHadClientComposition &&
1407 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001408 (mPreviousPresentFence->getSignalTime() ==
1409 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001410 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001411 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001412 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001413 mTimeStats.incrementMissedFrames();
1414 if (mPropagateBackpressure) {
1415 signalLayerUpdate();
1416 break;
1417 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001418 }
Dan Stoza50182882016-07-08 12:02:20 -07001419
Steven Thomas050b2c82017-03-06 11:45:16 -08001420 // Now that we're going to make it to the handleMessageTransaction()
1421 // call below it's safe to call updateVrFlinger(), which will
1422 // potentially trigger a display handoff.
1423 updateVrFlinger();
1424
Dan Stoza6b9454d2014-11-07 16:00:59 -08001425 bool refreshNeeded = handleMessageTransaction();
1426 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001427 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001428 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001429 // Signal a refresh if a transaction modified the window state,
1430 // a new buffer was latched, or if HWC has requested a full
1431 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001432 signalRefresh();
1433 }
1434 break;
1435 }
1436 case MessageQueue::REFRESH: {
1437 handleMessageRefresh();
1438 break;
1439 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001440 }
1441}
1442
Dan Stoza6b9454d2014-11-07 16:00:59 -08001443bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001444 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001445 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001446 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001447 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001448 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001449 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001450}
1451
Mathias Agopian4fec8732012-06-29 14:12:52 -07001452void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001453 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001454
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001455 mRefreshPending = false;
1456
David Sodmanfa9b2af2017-12-24 13:28:59 -08001457 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
David Sodman2b406362017-12-15 13:33:47 -08001458 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001459 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001460 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001461 for (const auto& [token, display] : mDisplays) {
1462 beginFrame(display);
1463 prepareFrame(display);
1464 doDebugFlashRegions(display, repaintEverything);
1465 doComposition(display, repaintEverything);
1466 }
1467
Adrian Roos1e1a1282017-11-01 19:05:31 +01001468 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001469 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001470
1471 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001472 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001473
Dan Stozabfbffeb2016-07-21 14:49:33 -07001474 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001475 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001476 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001477 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001478 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001479
Jorim Jaggi90535212018-05-23 23:44:06 +02001480 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001481
David Sodman7e4ae112018-02-09 15:02:28 -08001482 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001483 for (const auto& [token, display] : mDisplays) {
1484 const auto displayId = display->getId();
David Sodman7e4ae112018-02-09 15:02:28 -08001485 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[displayId]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001486 compositionInfo.hwc.hwcLayer = nullptr;
1487 }
David Sodmanba340492018-08-05 21:51:33 -07001488 }
David Sodman7e4ae112018-02-09 15:02:28 -08001489
1490 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001491}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001492
David Sodmanfa9b2af2017-12-24 13:28:59 -08001493
1494bool SurfaceFlinger::handleMessageInvalidate() {
1495 ATRACE_CALL();
1496 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001497}
1498
David Sodman79bba0e2018-08-05 18:07:49 -07001499void SurfaceFlinger::calculateWorkingSet() {
1500 ATRACE_CALL();
1501 ALOGV(__FUNCTION__);
1502
David Sodman79bba0e2018-08-05 18:07:49 -07001503 // build the h/w work list
1504 if (CC_UNLIKELY(mGeometryInvalid)) {
1505 mGeometryInvalid = false;
1506 for (const auto& [token, display] : mDisplays) {
1507 const auto displayId = display->getId();
1508 if (displayId >= 0) {
1509 const Vector<sp<Layer>>& currentLayers(
1510 display->getVisibleLayersSortedByZ());
1511 for (size_t i = 0; i < currentLayers.size(); i++) {
1512 const auto& layer = currentLayers[i];
1513
1514 if (!layer->hasHwcLayer(displayId)) {
1515 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1516 layer->forceClientComposition(displayId);
1517 continue;
1518 }
1519 }
1520
1521 layer->setGeometry(display, i);
1522 if (mDebugDisableHWC || mDebugRegion) {
1523 layer->forceClientComposition(displayId);
1524 }
1525 }
1526 }
1527 }
1528 }
1529
1530 // Set the per-frame data
1531 for (const auto& [token, display] : mDisplays) {
1532 const auto displayId = display->getId();
1533 if (displayId < 0) {
1534 continue;
1535 }
1536
1537 if (mDrawingState.colorMatrixChanged) {
1538 display->setColorTransform(mDrawingState.colorMatrix);
1539 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1540 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1541 "display %d: %d", displayId, result);
1542 }
1543 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1544 if (layer->isHdrY410()) {
1545 layer->forceClientComposition(displayId);
1546 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1547 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1548 !display->hasHDR10Support()) {
1549 layer->forceClientComposition(displayId);
1550 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1551 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1552 !display->hasHLGSupport()) {
1553 layer->forceClientComposition(displayId);
1554 }
1555
1556 if (layer->getForceClientComposition(displayId)) {
1557 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1558 layer->setCompositionType(displayId, HWC2::Composition::Client);
1559 continue;
1560 }
1561
1562 layer->setPerFrameData(display);
1563 }
1564
Peiyong Lin13effd12018-07-24 17:01:47 -07001565 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001566 ColorMode colorMode;
1567 Dataspace dataSpace;
1568 RenderIntent renderIntent;
1569 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1570 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1571 }
1572 }
1573
1574 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001575
1576 for (const auto& [token, display] : mDisplays) {
David Sodman15fb96e2018-01-07 10:23:24 -08001577 const auto displayId = display->getId();
1578 getBE().mCompositionInfo[displayId].clear();
David Sodmanba340492018-08-05 21:51:33 -07001579 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1580 auto displayId = display->getId();
1581 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1582 if (!layer->setHwcLayer(displayId)) {
1583 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1584 }
David Sodman15fb96e2018-01-07 10:23:24 -08001585 layer->getBE().compositionInfo.hwc.displayId = displayId;
1586 getBE().mCompositionInfo[displayId].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001587 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1588 }
1589 }
David Sodman79bba0e2018-08-05 18:07:49 -07001590}
1591
David Sodmanfa9b2af2017-12-24 13:28:59 -08001592void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001593{
1594 // is debugging enabled
1595 if (CC_LIKELY(!mDebugRegion))
1596 return;
1597
David Sodmanfa9b2af2017-12-24 13:28:59 -08001598 if (display->isPoweredOn()) {
1599 // transform the dirty region into this screen's coordinate space
1600 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1601 if (!dirtyRegion.isEmpty()) {
1602 // redraw the whole screen
1603 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001604
David Sodmanfa9b2af2017-12-24 13:28:59 -08001605 // and draw the dirty region
1606 const int32_t height = display->getHeight();
1607 auto& engine(getRenderEngine());
1608 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001609
David Sodmanfa9b2af2017-12-24 13:28:59 -08001610 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001611 }
1612 }
1613
David Sodmanfa9b2af2017-12-24 13:28:59 -08001614 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001615
1616 if (mDebugRegion > 1) {
1617 usleep(mDebugRegion * 1000);
1618 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001619
David Sodmanfa9b2af2017-12-24 13:28:59 -08001620 if (display->isPoweredOn()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001621 status_t result = display->prepareFrame(*getBE().mHwc);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001622 ALOGE_IF(result != NO_ERROR,
1623 "prepareFrame for display %d failed:"
1624 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001625 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001626 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001627}
1628
Adrian Roos1e1a1282017-11-01 19:05:31 +01001629void SurfaceFlinger::doTracing(const char* where) {
1630 ATRACE_CALL();
1631 ATRACE_NAME(where);
1632 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001633 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001634 }
1635}
1636
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001637void SurfaceFlinger::logLayerStats() {
1638 ATRACE_CALL();
1639 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001640 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001641 if (display->isPrimary()) {
1642 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001643 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001644 }
1645 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001646
1647 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001648 }
1649}
1650
David Sodman2b406362017-12-15 13:33:47 -08001651void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001652{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001653 ATRACE_CALL();
1654 ALOGV("preComposition");
1655
David Sodman2b406362017-12-15 13:33:47 -08001656 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1657
Mathias Agopiancd60f992012-08-16 16:28:27 -07001658 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001659 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001660 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001661 needExtraInvalidate = true;
1662 }
Robert Carr2047fae2016-11-28 14:09:09 -08001663 });
1664
Mathias Agopiancd60f992012-08-16 16:28:27 -07001665 if (needExtraInvalidate) {
1666 signalLayerUpdate();
1667 }
1668}
1669
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001670void SurfaceFlinger::updateCompositorTiming(
1671 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1672 std::shared_ptr<FenceTime>& presentFenceTime) {
1673 // Update queue of past composite+present times and determine the
1674 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001675 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001676 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001677 while (!getBE().mCompositePresentTimes.empty()) {
1678 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001679 // Cached values should have been updated before calling this method,
1680 // which helps avoid duplicate syscalls.
1681 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1682 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1683 break;
1684 }
1685 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001686 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001687 }
1688
1689 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001690 while (getBE().mCompositePresentTimes.size() > 16) {
1691 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001692 }
1693
Brian Andersond0010582017-03-07 13:20:31 -08001694 setCompositorTimingSnapped(
1695 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1696}
1697
1698void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1699 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001700 // Integer division and modulo round toward 0 not -inf, so we need to
1701 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001702 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001703 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1704 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1705
Brian Andersond0010582017-03-07 13:20:31 -08001706 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1707 if (idealLatency <= 0) {
1708 idealLatency = vsyncInterval;
1709 }
1710
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001711 // Snap the latency to a value that removes scheduling jitter from the
1712 // composition and present times, which often have >1ms of jitter.
1713 // Reducing jitter is important if an app attempts to extrapolate
1714 // something (such as user input) to an accurate diasplay time.
1715 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1716 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001717 nsecs_t bias = vsyncInterval / 2;
1718 int64_t extraVsyncs =
1719 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1720 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1721 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001722
David Sodman99974d22017-11-28 12:04:33 -08001723 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1724 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1725 getBE().mCompositorTiming.interval = vsyncInterval;
1726 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001727}
1728
David Sodman2b406362017-12-15 13:33:47 -08001729void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001730{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001731 ATRACE_CALL();
1732 ALOGV("postComposition");
1733
Brian Anderson3546a3f2016-07-14 11:51:14 -07001734 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001735 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001736 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001737 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001738 }
1739
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001740 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001741 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001742
David Sodman73beded2017-11-15 11:56:06 -08001743 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001744 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001745 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001746 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001747 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001748 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001749 } else {
1750 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1751 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001752
David Sodman73beded2017-11-15 11:56:06 -08001753 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001754 mPreviousPresentFence =
1755 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1756 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001757 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001758
Lloyd Pique41be5d22018-06-21 13:11:48 -07001759 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1760 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001761
David Sodman2b406362017-12-15 13:33:47 -08001762 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001763 // when we started doing work for this frame, but that should be okay
1764 // since updateCompositorTiming has snapping logic.
1765 updateCompositorTiming(
David Sodman2b406362017-12-15 13:33:47 -08001766 vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001767 CompositorTiming compositorTiming;
1768 {
David Sodman99974d22017-11-28 12:04:33 -08001769 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1770 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001771 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001772
Robert Carr2047fae2016-11-28 14:09:09 -08001773 mDrawingState.traverseInZOrder([&](Layer* layer) {
1774 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001775 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001776 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001777 recordBufferingStats(layer->getName().string(),
1778 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001779 }
Robert Carr2047fae2016-11-28 14:09:09 -08001780 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001781
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001782 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001783 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001784 enableHardwareVsync();
1785 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001786 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001787 }
1788 }
1789
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001790 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001791 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001792 enableHardwareVsync();
1793 }
1794 }
1795
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001796 if (mAnimCompositionPending) {
1797 mAnimCompositionPending = false;
1798
Brian Anderson4e606e32017-03-16 15:34:57 -07001799 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001800 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001801 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001802 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001803 // The HWC doesn't support present fences, so use the refresh
1804 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001805 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001806 mAnimFrameTracker.setActualPresentTime(presentTime);
1807 }
1808 mAnimFrameTracker.advanceFrame();
1809 }
Dan Stozab90cf072015-03-05 11:05:59 -08001810
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001811 mTimeStats.incrementTotalFrames();
1812 if (mHadClientComposition) {
1813 mTimeStats.incrementClientCompositionFrames();
1814 }
1815
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001816 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001817 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001818 return;
1819 }
1820
1821 nsecs_t currentTime = systemTime();
1822 if (mHasPoweredOff) {
1823 mHasPoweredOff = false;
1824 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001825 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001826 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001827 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1828 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001829 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001830 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001831 }
David Sodman4a36e932017-11-07 14:29:47 -08001832 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001833 }
David Sodman4a36e932017-11-07 14:29:47 -08001834 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001835
1836 {
1837 std::lock_guard lock(mTexturePoolMutex);
1838 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1839 if (refillCount > 0) {
1840 const size_t offset = mTexturePool.size();
1841 mTexturePool.resize(mTexturePoolSize);
1842 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1843 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1844 }
1845 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001846}
1847
1848void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001849 ATRACE_CALL();
1850 ALOGV("rebuildLayerStacks");
1851
Mathias Agopiancd60f992012-08-16 16:28:27 -07001852 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001853 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001854 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001855 mVisibleRegionsDirty = false;
1856 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001857
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001858 for (const auto& pair : mDisplays) {
1859 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001860 Region opaqueRegion;
1861 Region dirtyRegion;
1862 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001863 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001864 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001865 const Rect bounds = display->getBounds();
1866 if (display->isPoweredOn()) {
1867 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001868
Jeff Sharkey76488112017-02-27 14:15:18 -07001869 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001870 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001871 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001872 Region drawRegion(tr.transform(
1873 layer->visibleNonTransparentRegion));
1874 drawRegion.andSelf(bounds);
1875 if (!drawRegion.isEmpty()) {
1876 layersSortedByZ.add(layer);
1877 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001878 // Clear out the HWC layer if this layer was
1879 // previously visible, but no longer is
1880 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001881 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001882 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001883 // WM changes display->layerStack upon sleep/awake.
1884 // Here we make sure we delete the HWC layers even if
1885 // WM changed their layer stack.
1886 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001887 }
1888
1889 // If a layer is not going to get a release fence because
1890 // it is invisible, but it is also going to release its
1891 // old buffer, add it to the list of layers needing
1892 // fences.
1893 if (hwcLayerDestroyed) {
1894 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1895 mLayersWithQueuedFrames.cend(), layer);
1896 if (found != mLayersWithQueuedFrames.cend()) {
1897 layersNeedingFences.add(layer);
1898 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001899 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001900 });
1901 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001902 display->setVisibleLayersSortedByZ(layersSortedByZ);
1903 display->setLayersNeedingFences(layersNeedingFences);
1904 display->undefinedRegion.set(bounds);
1905 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1906 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001907 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001908 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001909}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001910
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001911// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001912// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001913// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001914// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001915// The returned HDR data space is one of
1916// - Dataspace::UNKNOWN
1917// - Dataspace::BT2020_HLG
1918// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001919Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1920 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001921 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001922 *outHdrDataSpace = Dataspace::UNKNOWN;
1923
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001924 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001925 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001926 case Dataspace::V0_SCRGB:
1927 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001928 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001929 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001930 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001931 case Dataspace::BT2020_PQ:
1932 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001933 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001934 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001935 case Dataspace::BT2020_HLG:
1936 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001937 // When there's mixed PQ content and HLG content, we set the HDR
1938 // data space to be BT2020_PQ and convert HLG to PQ.
1939 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1940 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001941 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001942 break;
1943 default:
1944 break;
1945 }
Romain Guy54f154a2017-10-24 21:40:32 +01001946 }
1947
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001948 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001949}
1950
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001951// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001952void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1953 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001954 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1955 *outMode = ColorMode::NATIVE;
1956 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001957 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001958 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001959 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001960
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001961 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001962 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001963
Peiyong Lindfde5112018-06-05 10:58:41 -07001964 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001965 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001966 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001967 if (isHdr) {
1968 bestDataSpace = hdrDataSpace;
1969 }
1970
Chia-I Wu0d711262018-05-21 15:19:35 -07001971 RenderIntent intent;
1972 switch (mDisplayColorSetting) {
1973 case DisplayColorSetting::MANAGED:
1974 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001975 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001976 break;
1977 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001978 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001979 break;
1980 default: // vendor display color setting
1981 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1982 break;
1983 }
Chia-I Wube02ec02018-05-18 10:59:36 -07001984
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001985 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001986}
1987
David Sodmanfa9b2af2017-12-24 13:28:59 -08001988void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08001989{
David Sodmanfa9b2af2017-12-24 13:28:59 -08001990 bool dirty = !display->getDirtyRegion(false).isEmpty();
1991 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
1992 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08001993
David Sodmanfa9b2af2017-12-24 13:28:59 -08001994 // If nothing has changed (!dirty), don't recompose.
1995 // If something changed, but we don't currently have any visible layers,
1996 // and didn't when we last did a composition, then skip it this time.
1997 // The second rule does two things:
1998 // - When all layers are removed from a display, we'll emit one black
1999 // frame, then nothing more until we get new layers.
2000 // - When a display is created with a private layer stack, we won't
2001 // emit any black frames until a layer is added to the layer stack.
2002 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002003
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002004 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2005 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002006 mustRecompose ? "doing" : "skipping",
2007 dirty ? "+" : "-",
2008 empty ? "+" : "-",
2009 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002010
David Sodmanfa9b2af2017-12-24 13:28:59 -08002011 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002012
David Sodmanfa9b2af2017-12-24 13:28:59 -08002013 if (mustRecompose) {
2014 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002015 }
2016}
2017
David Sodmanfa9b2af2017-12-24 13:28:59 -08002018void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002019{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002020 if (!display->isPoweredOn()) {
2021 return;
David Sodman2b406362017-12-15 13:33:47 -08002022 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002023
2024 status_t result = display->prepareFrame(*getBE().mHwc);
2025 ALOGE_IF(result != NO_ERROR,
2026 "prepareFrame for display %d failed:"
2027 " %d (%s)",
2028 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002029}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002030
David Sodmanfa9b2af2017-12-24 13:28:59 -08002031void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002032 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002033 ALOGV("doComposition");
2034
David Sodmanfa9b2af2017-12-24 13:28:59 -08002035 if (display->isPoweredOn()) {
2036 // transform the dirty region into this screen's coordinate space
2037 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002038
David Sodmanfa9b2af2017-12-24 13:28:59 -08002039 // repaint the framebuffer (if needed)
2040 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002041
David Sodmanfa9b2af2017-12-24 13:28:59 -08002042 display->dirtyRegion.clear();
2043 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002044 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002045 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002046}
2047
David Sodmanfa9b2af2017-12-24 13:28:59 -08002048void SurfaceFlinger::postFrame()
2049{
2050 // |mStateLock| not needed as we are on the main thread
2051 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2052 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2053 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2054 logFrameStats();
2055 }
2056 }
2057}
2058
2059void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002060{
Mathias Agopian841cde52012-03-01 15:44:37 -08002061 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002062 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002063
David Sodmanfa9b2af2017-12-24 13:28:59 -08002064 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002065
David Sodmanfa9b2af2017-12-24 13:28:59 -08002066 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002067 const auto displayId = display->getId();
2068 if (displayId >= 0) {
2069 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002070 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002071 display->onSwapBuffersCompleted();
2072 display->makeCurrent();
2073 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002074 sp<Fence> releaseFence = Fence::NO_FENCE;
2075
Chia-I Wu7b549592017-11-15 09:14:57 -08002076 // The layer buffer from the previous frame (if any) is released
2077 // by HWC only when the release fence from this frame (if any) is
2078 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002079 auto hwcLayer = layer->getHwcLayer(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002080 if (displayId >= 0) {
2081 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
2082 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002083
2084 // If the layer was client composited in the previous frame, we
2085 // need to merge with the previous client target acquire fence.
2086 // Since we do not track that, always merge with the current
2087 // client target acquire fence when it is available, even though
2088 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002089 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002090 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002091 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002092 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002093
David Sodmanb8af7922017-12-21 15:17:55 -08002094 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002095 }
Chia-I Wu83806892017-11-16 10:50:20 -08002096
2097 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002098 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002099 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002100 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002101 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002102 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002103 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002104 }
2105 }
2106
Dominik Laskowski7e045462018-05-30 13:02:02 -07002107 if (displayId >= 0) {
2108 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002109 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002110 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002111}
2112
Mathias Agopian87baae12012-07-31 12:38:26 -07002113void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002114{
Mathias Agopian841cde52012-03-01 15:44:37 -08002115 ATRACE_CALL();
2116
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002117 // here we keep a copy of the drawing state (that is the state that's
2118 // going to be overwritten by handleTransactionLocked()) outside of
2119 // mStateLock so that the side-effects of the State assignment
2120 // don't happen with mStateLock held (which can cause deadlocks).
2121 State drawingState(mDrawingState);
2122
Mathias Agopianca4d3602011-05-19 15:38:14 -07002123 Mutex::Autolock _l(mStateLock);
2124 const nsecs_t now = systemTime();
2125 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002126
Mathias Agopianca4d3602011-05-19 15:38:14 -07002127 // Here we're guaranteed that some transaction flags are set
2128 // so we can call handleTransactionLocked() unconditionally.
2129 // We call getTransactionFlags(), which will also clear the flags,
2130 // with mStateLock held to guarantee that mCurrentState won't change
2131 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002132
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002133 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002134 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002135 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002136
Mathias Agopianca4d3602011-05-19 15:38:14 -07002137 mLastTransactionTime = systemTime() - now;
2138 mDebugInTransaction = 0;
2139 invalidateHwcGeometry();
2140 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002141}
2142
Dominik Laskowski7e045462018-05-30 13:02:02 -07002143DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002144 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002145 // Figure out whether the event is for the primary display or an
2146 // external display by matching the Hwc display id against one for a
2147 // connected display. If we did not find a match, we then check what
2148 // displays are not already connected to determine the type. If we don't
2149 // have a connected primary display, we assume the new display is meant to
2150 // be the primary display, and then if we don't have an external display,
2151 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002152 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2153 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002154 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002155 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002156 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002157 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002158 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002159 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002160 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002161 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002162 return DisplayDevice::DISPLAY_EXTERNAL;
2163 }
2164
2165 return DisplayDevice::DISPLAY_ID_INVALID;
2166}
2167
Lloyd Piqueba04e622017-12-14 17:11:26 -08002168void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2169 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002170 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002171 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002172 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002173 continue;
2174 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002175
2176 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2177 ALOGE("External displays are not supported by the vr hardware composer.");
2178 continue;
2179 }
2180
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002181 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002182 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002183 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002184 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002185 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002186
2187 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002188 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002189 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002190 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002191 DisplayDeviceState info;
2192 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002193 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2194 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002195 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002196 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002197 mInterceptor->saveDisplayCreation(info);
2198 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002199 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002200 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002201
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002202 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002203 if (idx >= 0) {
2204 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002205 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002206 mCurrentState.displays.removeItemsAt(idx);
2207 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002208 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002209 }
2210
2211 processDisplayChangesLocked();
2212 }
2213
2214 mPendingHotplugEvents.clear();
2215}
2216
Lloyd Pique99d3da52018-01-22 17:48:03 -08002217sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002218 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002219 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002220 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002221 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002222 HdrCapabilities hdrCapabilities;
2223 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002224
Peiyong Lin13effd12018-07-24 17:01:47 -07002225 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002226 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002227 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002228 if (isWideColorMode(colorMode)) {
2229 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002230 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002231
Dominik Laskowski7e045462018-05-30 13:02:02 -07002232 std::vector<RenderIntent> renderIntents =
2233 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002234 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002235 }
tangrobin6753a022018-08-10 10:58:54 +08002236 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002237
tangrobin6753a022018-08-10 10:58:54 +08002238 if (displayId >= 0) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002239 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2240 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2241 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002242
2243 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2244 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2245
2246 /*
2247 * Create our display's surface
2248 */
2249 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2250 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002251 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002252 renderSurface->setNativeWindow(nativeWindow.get());
2253 const int displayWidth = renderSurface->queryWidth();
2254 const int displayHeight = renderSurface->queryHeight();
2255
2256 // Make sure that composition can never be stalled by a virtual display
2257 // consumer that isn't processing buffers fast enough. We have to do this
2258 // in two places:
2259 // * Here, in case the display is composed entirely by HWC.
2260 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2261 // window's swap interval in eglMakeCurrent, so they'll override the
2262 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002263 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002264 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2265 }
2266
2267 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002268 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002269
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002270 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002271 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2272 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2273 displayHeight, hasWideColorGamut, hdrCapabilities,
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002274 supportedPerFrameMetadata, hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002275
2276 if (maxFrameBufferAcquiredBuffers >= 3) {
2277 nativeWindowSurface->preallocateBuffers();
2278 }
2279
2280 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002281 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2282 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002283 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002284 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002285 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002286 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002287 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002288 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002289 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002290 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002291 display->setLayerStack(state.layerStack);
2292 display->setProjection(state.orientation, state.viewport, state.frame);
2293 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002294
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002295 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002296}
2297
Lloyd Pique347200f2017-12-14 17:00:15 -08002298void SurfaceFlinger::processDisplayChangesLocked() {
2299 // here we take advantage of Vector's copy-on-write semantics to
2300 // improve performance by skipping the transaction entirely when
2301 // know that the lists are identical
2302 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2303 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2304 if (!curr.isIdenticalTo(draw)) {
2305 mVisibleRegionsDirty = true;
2306 const size_t cc = curr.size();
2307 size_t dc = draw.size();
2308
2309 // find the displays that were removed
2310 // (ie: in drawing state but not in current state)
2311 // also handle displays that changed
2312 // (ie: displays that are in both lists)
2313 for (size_t i = 0; i < dc;) {
2314 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2315 if (j < 0) {
2316 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002317 // Call makeCurrent() on the primary display so we can
2318 // be sure that nothing associated with this display
2319 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002320 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2321 defaultDisplay->makeCurrent();
2322 }
2323 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2324 display->disconnect(getHwComposer());
2325 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002326 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2327 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2328 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2329 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2330 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002331 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002332 } else {
2333 // this display is in both lists. see if something changed.
2334 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002335 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002336 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2337 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2338 if (state_binder != draw_binder) {
2339 // changing the surface is like destroying and
2340 // recreating the DisplayDevice, so we just remove it
2341 // from the drawing state, so that it get re-added
2342 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002343 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2344 display->disconnect(getHwComposer());
2345 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002346 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002347 mDrawingState.displays.removeItemsAt(i);
2348 dc--;
2349 // at this point we must loop to the next item
2350 continue;
2351 }
2352
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002353 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002354 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002355 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002356 }
2357 if ((state.orientation != draw[i].orientation) ||
2358 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002359 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002360 }
2361 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002362 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002363 }
2364 }
2365 }
2366 ++i;
2367 }
2368
2369 // find displays that were added
2370 // (ie: in current state but not in drawing state)
2371 for (size_t i = 0; i < cc; i++) {
2372 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2373 const DisplayDeviceState& state(curr[i]);
2374
2375 sp<DisplaySurface> dispSurface;
2376 sp<IGraphicBufferProducer> producer;
2377 sp<IGraphicBufferProducer> bqProducer;
2378 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002379 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002380
Dominik Laskowski7e045462018-05-30 13:02:02 -07002381 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002382 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002383 // Virtual displays without a surface are dormant:
2384 // they have external state (layer stack, projection,
2385 // etc.) but no internal state (i.e. a DisplayDevice).
2386 if (state.surface != nullptr) {
2387 // Allow VR composer to use virtual displays.
2388 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2389 int width = 0;
2390 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2391 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2392 int height = 0;
2393 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2394 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2395 int intFormat = 0;
2396 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2397 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002398 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002399
Dominik Laskowski7e045462018-05-30 13:02:02 -07002400 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2401 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002402 }
2403
2404 // TODO: Plumb requested format back up to consumer
2405
2406 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002407 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002408 bqProducer, bqConsumer,
2409 state.displayName);
2410
2411 dispSurface = vds;
2412 producer = vds;
2413 }
2414 } else {
2415 ALOGE_IF(state.surface != nullptr,
2416 "adding a supported display, but rendering "
2417 "surface is provided (%p), ignoring it",
2418 state.surface.get());
2419
Dominik Laskowski7e045462018-05-30 13:02:02 -07002420 displayId = state.type;
2421 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002422 producer = bqProducer;
2423 }
2424
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002425 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002426 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002427 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002428 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002429 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002430 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002431 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2432 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2433 true);
2434 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2435 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2436 true);
2437 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002438 }
2439 }
2440 }
2441 }
2442 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002443
2444 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002445}
2446
Mathias Agopian87baae12012-07-31 12:38:26 -07002447void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002448{
Dan Stoza7dde5992015-05-22 09:51:44 -07002449 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002450 mCurrentState.traverseInZOrder([](Layer* layer) {
2451 layer->notifyAvailableFrames();
2452 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002453
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002454 /*
2455 * Traversal of the children
2456 * (perform the transaction for each of them if needed)
2457 */
2458
Mathias Agopian3559b072012-08-15 13:46:03 -07002459 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002460 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002461 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002462 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002463
2464 const uint32_t flags = layer->doTransaction(0);
2465 if (flags & Layer::eVisibleRegion)
2466 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002467 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002468 }
2469
2470 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002471 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002472 */
2473
Mathias Agopiane57f2922012-08-09 16:29:12 -07002474 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002475 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002476 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002477 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002478
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002479 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002480 // The transform hint might have changed for some layers
2481 // (either because a display has changed, or because a layer
2482 // as changed).
2483 //
2484 // Walk through all the layers in currentLayers,
2485 // and update their transform hint.
2486 //
2487 // If a layer is visible only on a single display, then that
2488 // display is used to calculate the hint, otherwise we use the
2489 // default display.
2490 //
2491 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2492 // the hint is set before we acquire a buffer from the surface texture.
2493 //
2494 // NOTE: layer transactions have taken place already, so we use their
2495 // drawing state. However, SurfaceFlinger's own transaction has not
2496 // happened yet, so we must use the current state layer list
2497 // (soon to become the drawing state list).
2498 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002499 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002500 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002501 bool first = true;
2502 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002503 // NOTE: we rely on the fact that layers are sorted by
2504 // layerStack first (so we don't have to traverse the list
2505 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002506 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002507 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002508 currentlayerStack = layerStack;
2509 // figure out if this layerstack is mirrored
2510 // (more than one display) if so, pick the default display,
2511 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002512 hintDisplay = nullptr;
2513 for (const auto& [token, display] : mDisplays) {
2514 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2515 if (hintDisplay) {
2516 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002517 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002518 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002519 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002520 }
2521 }
2522 }
2523 }
Chet Haase91d25932013-04-11 15:24:55 -07002524
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002525 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002526 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2527 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002528
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002529 // could be null when this layer is using a layerStack
2530 // that is not visible on any display. Also can occur at
2531 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002532 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002533 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002534
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002535 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002536 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002537 if (hintDisplay) {
2538 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002539 }
Robert Carr2047fae2016-11-28 14:09:09 -08002540
2541 first = false;
2542 });
Mathias Agopian84300952012-11-21 16:02:13 -08002543 }
2544
2545
Mathias Agopian3559b072012-08-15 13:46:03 -07002546 /*
2547 * Perform our own transaction if needed
2548 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002549
2550 if (mLayersAdded) {
2551 mLayersAdded = false;
2552 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002553 mVisibleRegionsDirty = true;
2554 }
2555
2556 // some layers might have been removed, so
2557 // we need to update the regions they're exposing.
2558 if (mLayersRemoved) {
2559 mLayersRemoved = false;
2560 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002561 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002562 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002563 // this layer is not visible anymore
2564 // TODO: we could traverse the tree from front to back and
2565 // compute the actual visible region
2566 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002567 Region visibleReg;
2568 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002569 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002570 }
Robert Carr2047fae2016-11-28 14:09:09 -08002571 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002572 }
2573
2574 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002575
2576 updateCursorAsync();
2577}
2578
2579void SurfaceFlinger::updateCursorAsync()
2580{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002581 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002582 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002583 continue;
2584 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002585
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002586 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2587 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002588 }
2589 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002590}
2591
2592void SurfaceFlinger::commitTransaction()
2593{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002594 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002595 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002596 for (const auto& l : mLayersPendingRemoval) {
2597 recordBufferingStats(l->getName().string(),
2598 l->getOccupancyHistory(true));
2599 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002600 }
2601 mLayersPendingRemoval.clear();
2602 }
2603
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002604 // If this transaction is part of a window animation then the next frame
2605 // we composite should be considered an animation as well.
2606 mAnimCompositionPending = mAnimTransactionPending;
2607
Mathias Agopian4fec8732012-06-29 14:12:52 -07002608 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002609 // clear the "changed" flags in current state
2610 mCurrentState.colorMatrixChanged = false;
2611
Robert Carr1f0a16a2016-10-24 16:27:39 -07002612 mDrawingState.traverseInZOrder([](Layer* layer) {
2613 layer->commitChildList();
2614 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002615 mTransactionPending = false;
2616 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002617 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002618}
2619
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002620void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2621 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002622 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002623 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002624
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002625 Region aboveOpaqueLayers;
2626 Region aboveCoveredLayers;
2627 Region dirty;
2628
Mathias Agopian87baae12012-07-31 12:38:26 -07002629 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002630
Robert Carr2047fae2016-11-28 14:09:09 -08002631 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002632 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002633 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002634
Jesse Hall01e29052013-02-19 16:13:35 -08002635 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002636 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002637 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002638 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002639
Mathias Agopianab028732010-03-16 16:41:46 -07002640 /*
2641 * opaqueRegion: area of a surface that is fully opaque.
2642 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002643 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002644
2645 /*
2646 * visibleRegion: area of a surface that is visible on screen
2647 * and not fully transparent. This is essentially the layer's
2648 * footprint minus the opaque regions above it.
2649 * Areas covered by a translucent surface are considered visible.
2650 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002651 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002652
2653 /*
2654 * coveredRegion: area of a surface that is covered by all
2655 * visible regions above it (which includes the translucent areas).
2656 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002657 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002658
Jesse Halla8026d22012-09-25 13:25:04 -07002659 /*
2660 * transparentRegion: area of a surface that is hinted to be completely
2661 * transparent. This is only used to tell when the layer has no visible
2662 * non-transparent regions and can be removed from the layer list. It
2663 * does not affect the visibleRegion of this layer or any layers
2664 * beneath it. The hint may not be correct if apps don't respect the
2665 * SurfaceView restrictions (which, sadly, some don't).
2666 */
2667 Region transparentRegion;
2668
Mathias Agopianab028732010-03-16 16:41:46 -07002669
2670 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002671 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002672 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002673 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002674 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002675 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002676 if (!visibleRegion.isEmpty()) {
2677 // Remove the transparent area from the visible region
2678 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002679 if (tr.preserveRects()) {
2680 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002681 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002682 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002683 // transformation too complex, can't do the
2684 // transparent region optimization.
2685 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002686 }
Mathias Agopianab028732010-03-16 16:41:46 -07002687 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002688
Mathias Agopianab028732010-03-16 16:41:46 -07002689 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002690 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002691 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002692 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002693 // the opaque region is the layer's footprint
2694 opaqueRegion = visibleRegion;
2695 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002696 }
2697 }
2698
Robert Carre5f4f692018-01-12 13:12:28 -08002699 if (visibleRegion.isEmpty()) {
2700 layer->clearVisibilityRegions();
2701 return;
2702 }
2703
Mathias Agopianab028732010-03-16 16:41:46 -07002704 // Clip the covered region to the visible region
2705 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2706
2707 // Update aboveCoveredLayers for next (lower) layer
2708 aboveCoveredLayers.orSelf(visibleRegion);
2709
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002710 // subtract the opaque region covered by the layers above us
2711 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002712
2713 // compute this layer's dirty region
2714 if (layer->contentDirty) {
2715 // we need to invalidate the whole region
2716 dirty = visibleRegion;
2717 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002718 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002719 layer->contentDirty = false;
2720 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002721 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002722 * the exposed region consists of two components:
2723 * 1) what's VISIBLE now and was COVERED before
2724 * 2) what's EXPOSED now less what was EXPOSED before
2725 *
2726 * note that (1) is conservative, we start with the whole
2727 * visible region but only keep what used to be covered by
2728 * something -- which mean it may have been exposed.
2729 *
2730 * (2) handles areas that were not covered by anything but got
2731 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002732 */
Mathias Agopianab028732010-03-16 16:41:46 -07002733 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002734 const Region oldVisibleRegion = layer->visibleRegion;
2735 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002736 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2737 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002738 }
2739 dirty.subtractSelf(aboveOpaqueLayers);
2740
2741 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002742 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002743
Mathias Agopianab028732010-03-16 16:41:46 -07002744 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002745 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002746
Jesse Halla8026d22012-09-25 13:25:04 -07002747 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002748 layer->setVisibleRegion(visibleRegion);
2749 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002750 layer->setVisibleNonTransparentRegion(
2751 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002752 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002753
Mathias Agopian87baae12012-07-31 12:38:26 -07002754 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002755}
2756
Chia-I Wuab0c3192017-08-01 11:29:00 -07002757void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002758 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002759 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2760 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002761 }
2762 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002763}
2764
Dan Stoza6b9454d2014-11-07 16:00:59 -08002765bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002766{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002767 ALOGV("handlePageFlip");
2768
Brian Andersond6927fb2016-07-23 23:37:30 -07002769 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002770
Mathias Agopian4fec8732012-06-29 14:12:52 -07002771 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002772 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002773 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002774
2775 // Store the set of layers that need updates. This set must not change as
2776 // buffers are being latched, as this could result in a deadlock.
2777 // Example: Two producers share the same command stream and:
2778 // 1.) Layer 0 is latched
2779 // 2.) Layer 0 gets a new frame
2780 // 2.) Layer 1 gets a new frame
2781 // 3.) Layer 1 is latched.
2782 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2783 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002784 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002785 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002786 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07002787 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002788 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002789 } else {
2790 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002791 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002792 } else {
2793 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002794 }
Robert Carr2047fae2016-11-28 14:09:09 -08002795 });
2796
Dan Stoza9e56aa02015-11-02 13:00:03 -08002797 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002798 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002799 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002800 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002801 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002802 newDataLatched = true;
2803 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002804 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002805
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002806 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002807
2808 // If we will need to wake up at some time in the future to deal with a
2809 // queued frame that shouldn't be displayed during this vsync period, wake
2810 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002811 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002812 signalLayerUpdate();
2813 }
2814
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002815 // enter boot animation on first buffer latch
2816 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2817 ALOGI("Enter boot animation");
2818 mBootStage = BootStage::BOOTANIMATION;
2819 }
2820
Dan Stoza6b9454d2014-11-07 16:00:59 -08002821 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002822 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002823}
2824
Mathias Agopianad456f92011-01-13 17:53:01 -08002825void SurfaceFlinger::invalidateHwcGeometry()
2826{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002827 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002828}
2829
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002830void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2831 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002832 // We only need to actually compose the display if:
2833 // 1) It is being handled by hardware composer, which may need this to
2834 // keep its virtual display state machine in sync, or
2835 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002836 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002837 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002838 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002839 return;
2840 }
2841
Dan Stoza9e56aa02015-11-02 13:00:03 -08002842 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002843 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002844
2845 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002846 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002847}
2848
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002849bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002850 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002851
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002852 const Region bounds(display->bounds());
2853 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002854 const auto displayId = display->getId();
2855 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002856 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002857
Chia-I Wu8e50e692018-05-04 10:12:37 -07002858 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002859 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002860
Dan Stoza9e56aa02015-11-02 13:00:03 -08002861 if (hasClientComposition) {
2862 ALOGV("hasClientComposition");
2863
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002864 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002865 if (display->hasWideColorGamut()) {
2866 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002867 }
2868 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002869 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002870 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002871
Dominik Laskowski7e045462018-05-30 13:02:02 -07002872 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002873 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2874 HWC2::Capability::SkipClientColorTransform);
2875
Chia-I Wud49d6692018-06-27 07:17:41 +08002876 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002877 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2878 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08002879 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002880 }
2881
Chia-I Wud49d6692018-06-27 07:17:41 +08002882 // The current enhanced saturation matrix is designed to enhance Display P3,
2883 // thus we only apply this matrix when the render intent is not colorimetric
2884 // and the output color space is Display P3.
2885 needsEnhancedColorMatrix =
2886 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2887 outputDataspace == Dataspace::DISPLAY_P3);
2888 if (needsEnhancedColorMatrix) {
2889 colorMatrix *= mEnhancedSaturationMatrix;
2890 }
2891
2892 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002893
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002894 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002895 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002896 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002897 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002898
2899 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002900 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
2901 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
2902 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07002903 }
2904 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002905 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002906
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002907 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002908 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002909 // when using overlays, we assume a fully transparent framebuffer
2910 // NOTE: we could reduce how much we need to clear, for instance
2911 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002912 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002913 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002914 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002915 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08002916 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07002917 // we're left with the letterbox region
2918 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002919 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07002920
2921 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002922 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07002923
Mathias Agopianb9494d52012-04-18 02:28:45 -07002924 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002925 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002926 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002927 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002928 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002929 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002930
Yiwei Zhange4e26c02018-08-22 13:59:12 -07002931 const Rect& bounds = display->getBounds();
2932 const Rect& scissor = display->getScissor();
2933 if (scissor != bounds) {
2934 // scissor doesn't match the screen's dimensions, so we
2935 // need to clear everything outside of it and enable
2936 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002937
Yiwei Zhange4e26c02018-08-22 13:59:12 -07002938 // enable scissor for this frame
2939 const uint32_t height = display->getHeight();
2940 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
2941 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002942 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002943 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002944
Mathias Agopian85d751c2012-08-29 16:59:24 -07002945 /*
2946 * and then, render the layers targeted at the framebuffer
2947 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002948
Dan Stoza9e56aa02015-11-02 13:00:03 -08002949 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07002950 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002951 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002952 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002953 const Region clip(bounds.intersect(
2954 displayTransform.transform(layer->visibleRegion)));
2955 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002956 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002957 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002958 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002959 case HWC2::Composition::Cursor:
2960 case HWC2::Composition::Device:
2961 case HWC2::Composition::Sideband:
2962 case HWC2::Composition::SolidColor: {
2963 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07002964 if (layer->getClearClientTarget(displayId) && !firstLayer &&
Rajavenu Kyatham2eae6d32018-04-10 12:34:05 +05302965 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
2966 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002967 // never clear the very first layer since we're
2968 // guaranteed the FB is already cleared
2969 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002970 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002971 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002972 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002973 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002974 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002975 break;
2976 }
2977 default:
2978 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002979 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002980 } else {
2981 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002982 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07002983 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002984 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002985
Chia-I Wud49d6692018-06-27 07:17:41 +08002986 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07002987 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002988 }
2989
Mathias Agopianf45c5102012-10-24 16:29:17 -07002990 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08002991 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002992 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002993}
2994
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002995void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
2996 const Region& region) const {
2997 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08002998 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07002999 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003000}
3001
Dan Stoza7d89d062015-04-30 13:29:25 -07003002status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003003 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003004 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003005 const sp<Layer>& lbc,
3006 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003007{
Dan Stoza7d89d062015-04-30 13:29:25 -07003008 // add this layer to the current state list
3009 {
3010 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003011 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003012 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3013 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003014 return NO_MEMORY;
3015 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003016 if (parent == nullptr) {
3017 mCurrentState.layersSortedByZ.add(lbc);
3018 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003019 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003020 ALOGE("addClientLayer called with a removed parent");
3021 return NAME_NOT_FOUND;
3022 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003023 parent->addChild(lbc);
3024 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003025
Yiwei Zhang243b3782018-05-15 17:40:04 -07003026 if (gbc != nullptr) {
3027 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3028 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3029 mMaxGraphicBufferProducerListSize,
3030 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3031 mGraphicBufferProducerList.size(),
3032 mMaxGraphicBufferProducerListSize, mNumLayers);
3033 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003034 mLayersAdded = true;
3035 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003036 }
3037
Mathias Agopian96f08192010-06-02 23:28:45 -07003038 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003039 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003040
Dan Stoza7d89d062015-04-30 13:29:25 -07003041 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003042}
3043
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003044status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003045 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003046 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3047}
Robert Carr7f9b8992017-03-10 11:08:39 -08003048
chaviwca27f252018-02-06 16:46:39 -08003049status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3050 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003051 if (layer->isPendingRemoval()) {
3052 return NO_ERROR;
3053 }
3054
Robert Carr1f0a16a2016-10-24 16:27:39 -07003055 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003056 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003057 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003058 if (topLevelOnly) {
3059 return NO_ERROR;
3060 }
3061
Chia-I Wu98f1c102017-05-30 14:54:08 -07003062 sp<Layer> ancestor = p;
3063 while (ancestor->getParent() != nullptr) {
3064 ancestor = ancestor->getParent();
3065 }
3066 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3067 ALOGE("removeLayer called with a layer whose parent has been removed");
3068 return NAME_NOT_FOUND;
3069 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003070
3071 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003072 } else {
3073 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003074 }
3075
Robert Carr136e2f62017-02-08 17:54:29 -08003076 // As a matter of normal operation, the LayerCleaner will produce a second
3077 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3078 // so we will succeed in promoting it, but it's already been removed
3079 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3080 // otherwise something has gone wrong and we are leaking the layer.
3081 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003082 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3083 layer->getName().string(),
3084 (p != nullptr) ? p->getName().string() : "no-parent");
3085 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003086 } else if (index < 0) {
3087 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003088 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003089
Chia-I Wuc6657022017-08-15 11:18:17 -07003090 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003091 mLayersPendingRemoval.add(layer);
3092 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003093 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003094 setTransactionFlags(eTransactionNeeded);
3095 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003096}
3097
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003098uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003099 return android_atomic_release_load(&mTransactionFlags);
3100}
3101
Mathias Agopian3f844832013-08-07 21:24:32 -07003102uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003103 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3104}
3105
Mathias Agopian3f844832013-08-07 21:24:32 -07003106uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003107 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3108}
3109
3110uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3111 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003112 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003113 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003114 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003115 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003116 }
3117 return old;
3118}
3119
chaviwca27f252018-02-06 16:46:39 -08003120bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3121 for (const ComposerState& state : states) {
3122 // Here we need to check that the interface we're given is indeed
3123 // one of our own. A malicious client could give us a nullptr
3124 // IInterface, or one of its own or even one of our own but a
3125 // different type. All these situations would cause us to crash.
3126 if (state.client == nullptr) {
3127 return true;
3128 }
3129
3130 sp<IBinder> binder = IInterface::asBinder(state.client);
3131 if (binder == nullptr) {
3132 return true;
3133 }
3134
3135 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3136 return true;
3137 }
3138 }
3139 return false;
3140}
3141
Mathias Agopian8b33f032012-07-24 20:43:54 -07003142void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003143 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003144 const Vector<DisplayState>& displays,
3145 uint32_t flags)
3146{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003147 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003148 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003149 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003150
chaviwca27f252018-02-06 16:46:39 -08003151 if (containsAnyInvalidClientState(states)) {
3152 return;
3153 }
3154
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003155 if (flags & eAnimation) {
3156 // For window updates that are part of an animation we must wait for
3157 // previous animation "frames" to be handled.
3158 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003159 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003160 if (CC_UNLIKELY(err != NO_ERROR)) {
3161 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003162 // caller after a few seconds.
3163 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3164 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003165 mAnimTransactionPending = false;
3166 break;
3167 }
3168 }
3169 }
3170
chaviwca27f252018-02-06 16:46:39 -08003171 for (const DisplayState& display : displays) {
3172 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003173 }
3174
chaviwca27f252018-02-06 16:46:39 -08003175 for (const ComposerState& state : states) {
3176 transactionFlags |= setClientStateLocked(state);
3177 }
3178
3179 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3180 // as destroyed should only occur after setting all other states. This is to allow for a
3181 // child re-parent to happen before marking its original parent as destroyed (which would
3182 // then mark the child as destroyed).
3183 for (const ComposerState& state : states) {
3184 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003185 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003186
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003187 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3188 // anyway. This can be used as a flush mechanism for previous async transactions.
3189 // Empty animation transaction can be used to simulate back-pressure, so also force a
3190 // transaction for empty animation transactions.
3191 if (transactionFlags == 0 &&
3192 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003193 transactionFlags = eTransactionNeeded;
3194 }
3195
Mathias Agopian386aa982011-11-07 21:58:03 -08003196 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003197 if (mInterceptor->isEnabled()) {
3198 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003199 }
Irvel468051e2016-06-13 16:44:44 -07003200
Mathias Agopian386aa982011-11-07 21:58:03 -08003201 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003202 const auto start = (flags & eEarlyWakeup)
3203 ? VSyncModulator::TransactionStart::EARLY
3204 : VSyncModulator::TransactionStart::NORMAL;
3205 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003206
3207 // if this is a synchronous transaction, wait for it to take effect
3208 // before returning.
3209 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003210 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003211 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003212 if (flags & eAnimation) {
3213 mAnimTransactionPending = true;
3214 }
3215 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003216 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3217 if (CC_UNLIKELY(err != NO_ERROR)) {
3218 // just in case something goes wrong in SF, return to the
3219 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003220 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3221 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003222 break;
3223 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003224 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003225 }
3226}
3227
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003228uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3229 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3230 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003231
Mathias Agopiane57f2922012-08-09 16:29:12 -07003232 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003233 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3234
3235 const uint32_t what = s.what;
3236 if (what & DisplayState::eSurfaceChanged) {
3237 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3238 state.surface = s.surface;
3239 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003240 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003241 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003242 if (what & DisplayState::eLayerStackChanged) {
3243 if (state.layerStack != s.layerStack) {
3244 state.layerStack = s.layerStack;
3245 flags |= eDisplayTransactionNeeded;
3246 }
3247 }
3248 if (what & DisplayState::eDisplayProjectionChanged) {
3249 if (state.orientation != s.orientation) {
3250 state.orientation = s.orientation;
3251 flags |= eDisplayTransactionNeeded;
3252 }
3253 if (state.frame != s.frame) {
3254 state.frame = s.frame;
3255 flags |= eDisplayTransactionNeeded;
3256 }
3257 if (state.viewport != s.viewport) {
3258 state.viewport = s.viewport;
3259 flags |= eDisplayTransactionNeeded;
3260 }
3261 }
3262 if (what & DisplayState::eDisplaySizeChanged) {
3263 if (state.width != s.width) {
3264 state.width = s.width;
3265 flags |= eDisplayTransactionNeeded;
3266 }
3267 if (state.height != s.height) {
3268 state.height = s.height;
3269 flags |= eDisplayTransactionNeeded;
3270 }
3271 }
3272
Mathias Agopiane57f2922012-08-09 16:29:12 -07003273 return flags;
3274}
3275
Robert Carrd4ae7f32018-06-07 16:10:57 -07003276bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3277 IPCThreadState* ipc = IPCThreadState::self();
3278 const int pid = ipc->getCallingPid();
3279 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003280 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003281 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003282 return false;
3283 }
3284 return true;
3285}
3286
chaviwca27f252018-02-06 16:46:39 -08003287uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3288 const layer_state_t& s = composerState.state;
3289 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3290
Mathias Agopian13127d82013-03-05 17:47:11 -08003291 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003292 if (layer == nullptr) {
3293 return 0;
3294 }
3295
3296 if (layer->isPendingRemoval()) {
3297 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3298 return 0;
3299 }
3300
3301 uint32_t flags = 0;
3302
3303 const uint32_t what = s.what;
3304 bool geometryAppliesWithResize =
3305 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003306
3307 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3308 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003309 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003310 layer->pushPendingState();
3311 }
3312
chaviw8b3871a2017-11-01 17:41:01 -07003313 if (what & layer_state_t::ePositionChanged) {
3314 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3315 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003316 }
chaviw8b3871a2017-11-01 17:41:01 -07003317 }
3318 if (what & layer_state_t::eLayerChanged) {
3319 // NOTE: index needs to be calculated before we update the state
3320 const auto& p = layer->getParent();
3321 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003322 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003323 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003324 mCurrentState.layersSortedByZ.removeAt(idx);
3325 mCurrentState.layersSortedByZ.add(layer);
3326 // we need traversal (state changed)
3327 // AND transaction (list changed)
3328 flags |= eTransactionNeeded|eTraversalNeeded;
3329 }
chaviw8b3871a2017-11-01 17:41:01 -07003330 } else {
3331 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003332 flags |= eTransactionNeeded|eTraversalNeeded;
3333 }
3334 }
chaviw8b3871a2017-11-01 17:41:01 -07003335 }
3336 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003337 // NOTE: index needs to be calculated before we update the state
3338 const auto& p = layer->getParent();
3339 if (p == nullptr) {
3340 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3341 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3342 mCurrentState.layersSortedByZ.removeAt(idx);
3343 mCurrentState.layersSortedByZ.add(layer);
3344 // we need traversal (state changed)
3345 // AND transaction (list changed)
3346 flags |= eTransactionNeeded|eTraversalNeeded;
3347 }
3348 } else {
3349 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3350 flags |= eTransactionNeeded|eTraversalNeeded;
3351 }
chaviw8b3871a2017-11-01 17:41:01 -07003352 }
3353 }
3354 if (what & layer_state_t::eSizeChanged) {
3355 if (layer->setSize(s.w, s.h)) {
3356 flags |= eTraversalNeeded;
3357 }
3358 }
3359 if (what & layer_state_t::eAlphaChanged) {
3360 if (layer->setAlpha(s.alpha))
3361 flags |= eTraversalNeeded;
3362 }
3363 if (what & layer_state_t::eColorChanged) {
3364 if (layer->setColor(s.color))
3365 flags |= eTraversalNeeded;
3366 }
3367 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003368 // TODO: b/109894387
3369 //
3370 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3371 // rotation. To see the problem observe that if we have a square parent, and a child
3372 // of the same size, then we rotate the child 45 degrees around it's center, the child
3373 // must now be cropped to a non rectangular 8 sided region.
3374 //
3375 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3376 // private API, and the WindowManager only uses rotation in one case, which is on a top
3377 // level layer in which cropping is not an issue.
3378 //
3379 // However given that abuse of rotation matrices could lead to surfaces extending outside
3380 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3381 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3382 // transformations.
3383 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003384 flags |= eTraversalNeeded;
3385 }
3386 if (what & layer_state_t::eTransparentRegionChanged) {
3387 if (layer->setTransparentRegionHint(s.transparentRegion))
3388 flags |= eTraversalNeeded;
3389 }
3390 if (what & layer_state_t::eFlagsChanged) {
3391 if (layer->setFlags(s.flags, s.mask))
3392 flags |= eTraversalNeeded;
3393 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003394 if (what & layer_state_t::eCropChanged_legacy) {
3395 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003396 flags |= eTraversalNeeded;
3397 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003398 if (what & layer_state_t::eFinalCropChanged_legacy) {
3399 if (layer->setFinalCrop_legacy(s.finalCrop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003400 flags |= eTraversalNeeded;
3401 }
3402 if (what & layer_state_t::eLayerStackChanged) {
3403 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3404 // We only allow setting layer stacks for top level layers,
3405 // everything else inherits layer stack from its parent.
3406 if (layer->hasParent()) {
3407 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3408 layer->getName().string());
3409 } else if (idx < 0) {
3410 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3411 "that also does not appear in the top level layer list. Something"
3412 " has gone wrong.", layer->getName().string());
3413 } else if (layer->setLayerStack(s.layerStack)) {
3414 mCurrentState.layersSortedByZ.removeAt(idx);
3415 mCurrentState.layersSortedByZ.add(layer);
3416 // we need traversal (state changed)
3417 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003418 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003419 }
3420 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003421 if (what & layer_state_t::eDeferTransaction_legacy) {
3422 if (s.barrierHandle_legacy != nullptr) {
3423 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3424 } else if (s.barrierGbp_legacy != nullptr) {
3425 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003426 if (authenticateSurfaceTextureLocked(gbp)) {
3427 const auto& otherLayer =
3428 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003429 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003430 } else {
3431 ALOGE("Attempt to defer transaction to to an"
3432 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003433 }
3434 }
chaviw8b3871a2017-11-01 17:41:01 -07003435 // We don't trigger a traversal here because if no other state is
3436 // changed, we don't want this to cause any more work
3437 }
3438 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003439 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003440 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003441 if (!hadParent) {
3442 mCurrentState.layersSortedByZ.remove(layer);
3443 }
chaviw8b3871a2017-11-01 17:41:01 -07003444 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003445 }
chaviw8b3871a2017-11-01 17:41:01 -07003446 }
3447 if (what & layer_state_t::eReparentChildren) {
3448 if (layer->reparentChildren(s.reparentHandle)) {
3449 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003450 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003451 }
chaviw8b3871a2017-11-01 17:41:01 -07003452 if (what & layer_state_t::eDetachChildren) {
3453 layer->detachChildren();
3454 }
3455 if (what & layer_state_t::eOverrideScalingModeChanged) {
3456 layer->setOverrideScalingMode(s.overrideScalingMode);
3457 // We don't trigger a traversal here because if no other state is
3458 // changed, we don't want this to cause any more work
3459 }
Marissa Wall61c58622018-07-18 10:12:20 -07003460 if (what & layer_state_t::eTransformChanged) {
3461 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3462 }
3463 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3464 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3465 flags |= eTraversalNeeded;
3466 }
3467 if (what & layer_state_t::eCropChanged) {
3468 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3469 }
3470 if (what & layer_state_t::eBufferChanged) {
3471 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3472 }
3473 if (what & layer_state_t::eAcquireFenceChanged) {
3474 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3475 }
3476 if (what & layer_state_t::eDataspaceChanged) {
3477 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3478 }
3479 if (what & layer_state_t::eHdrMetadataChanged) {
3480 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3481 }
3482 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3483 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3484 }
3485 if (what & layer_state_t::eApiChanged) {
3486 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3487 }
3488 if (what & layer_state_t::eSidebandStreamChanged) {
3489 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3490 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003491 return flags;
3492}
3493
chaviwca27f252018-02-06 16:46:39 -08003494void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3495 const layer_state_t& state = composerState.state;
3496 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3497
3498 sp<Layer> layer(client->getLayerUser(state.surface));
3499 if (layer == nullptr) {
3500 return;
3501 }
3502
3503 if (layer->isPendingRemoval()) {
3504 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3505 return;
3506 }
3507
3508 if (state.what & layer_state_t::eDestroySurface) {
3509 removeLayerLocked(mStateLock, layer);
3510 }
3511}
3512
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003513status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003514 const String8& name,
3515 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003516 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003517 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003518 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003519{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003520 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003521 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003522 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003523 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003524 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003525
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003526 status_t result = NO_ERROR;
3527
3528 sp<Layer> layer;
3529
Cody Northropbc755282017-03-31 12:00:08 -06003530 String8 uniqueName = getUniqueLayerName(name);
3531
Mathias Agopian3165cc22012-08-08 19:42:09 -07003532 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003533 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003534 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3535 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003536
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003537 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003538 case ISurfaceComposerClient::eFXSurfaceBufferState:
3539 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3540 break;
chaviw13fdc492017-06-27 12:40:18 -07003541 case ISurfaceComposerClient::eFXSurfaceColor:
3542 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003543 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003544 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003545 break;
3546 default:
3547 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003548 break;
3549 }
3550
Dan Stoza7d89d062015-04-30 13:29:25 -07003551 if (result != NO_ERROR) {
3552 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003553 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003554
Chia-I Wuab0c3192017-08-01 11:29:00 -07003555 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3556 // TODO b/64227542
3557 if (windowType == 441731) {
3558 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3559 layer->setPrimaryDisplayOnly();
3560 }
3561
Albert Chaulk479c60c2017-01-27 14:21:34 -05003562 layer->setInfo(windowType, ownerUid);
3563
Robert Carr1f0a16a2016-10-24 16:27:39 -07003564 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003565 if (result != NO_ERROR) {
3566 return result;
3567 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003568 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003569
3570 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003571 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003572}
3573
Cody Northropbc755282017-03-31 12:00:08 -06003574String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3575{
3576 bool matchFound = true;
3577 uint32_t dupeCounter = 0;
3578
3579 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3580 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3581
Dan Stoza436ccf32018-06-21 12:10:12 -07003582 // Grab the state lock since we're accessing mCurrentState
3583 Mutex::Autolock lock(mStateLock);
3584
Cody Northropbc755282017-03-31 12:00:08 -06003585 // Loop over layers until we're sure there is no matching name
3586 while (matchFound) {
3587 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003588 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003589 if (layer->getName() == uniqueName) {
3590 matchFound = true;
3591 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3592 }
3593 });
3594 }
3595
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003596 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3597 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003598
3599 return uniqueName;
3600}
3601
Marissa Wallfd668622018-05-10 10:21:13 -07003602status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3603 uint32_t w, uint32_t h, uint32_t flags,
3604 PixelFormat& format, sp<IBinder>* handle,
3605 sp<IGraphicBufferProducer>* gbp,
3606 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003607 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003608 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003609 case PIXEL_FORMAT_TRANSPARENT:
3610 case PIXEL_FORMAT_TRANSLUCENT:
3611 format = PIXEL_FORMAT_RGBA_8888;
3612 break;
3613 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003614 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003615 break;
3616 }
3617
Marissa Wallfd668622018-05-10 10:21:13 -07003618 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3619 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003620 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003621 *handle = layer->getHandle();
3622 *gbp = layer->getProducer();
3623 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003624 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003625
Marissa Wallfd668622018-05-10 10:21:13 -07003626 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003627 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003628}
3629
Marissa Wall61c58622018-07-18 10:12:20 -07003630status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3631 uint32_t w, uint32_t h, uint32_t flags,
3632 sp<IBinder>* handle, sp<Layer>* outLayer) {
3633 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3634 *handle = layer->getHandle();
3635 *outLayer = layer;
3636
3637 return NO_ERROR;
3638}
3639
chaviw13fdc492017-06-27 12:40:18 -07003640status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003641 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003642 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003643{
chaviw13fdc492017-06-27 12:40:18 -07003644 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003645 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003646 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003647}
3648
Mathias Agopianac9fa422013-02-11 16:40:36 -08003649status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003650{
Robert Carr9524cb32017-02-13 11:32:32 -08003651 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003652 status_t err = NO_ERROR;
3653 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003654 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003655 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003656 err = removeLayer(l);
3657 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3658 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003659 }
3660 return err;
3661}
3662
Mathias Agopian13127d82013-03-05 17:47:11 -08003663status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003664{
Mathias Agopian67106042013-03-14 19:18:13 -07003665 // called by ~LayerCleaner() when all references to the IBinder (handle)
3666 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003667 sp<Layer> l = layer.promote();
3668 if (l == nullptr) {
3669 // The layer has already been removed, carry on
3670 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003671 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003672 // If we have a parent, then we can continue to live as long as it does.
3673 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003674}
3675
Mathias Agopianb60314a2012-04-10 22:09:54 -07003676// ---------------------------------------------------------------------------
3677
Andy McFadden13a082e2012-08-24 10:16:42 -07003678void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003679 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3680 if (!displayToken) return;
3681
Jesse Hall01e29052013-02-19 16:13:35 -08003682 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003683 Vector<ComposerState> state;
3684 Vector<DisplayState> displays;
3685 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003686 d.what = DisplayState::eDisplayProjectionChanged |
3687 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003688 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003689 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003690 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003691 d.frame.makeInvalid();
3692 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003693 d.width = 0;
3694 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003695 displays.add(d);
3696 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003697
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003698 const auto display = getDisplayDevice(displayToken);
3699 if (!display) return;
3700
3701 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3702
3703 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003704 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003705 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003706
Brian Andersond0010582017-03-07 13:20:31 -08003707 // Use phase of 0 since phase is not known.
3708 // Use latency of 0, which will snap to the ideal latency.
3709 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003710}
3711
3712void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003713 // Async since we may be called from the main thread.
3714 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003715}
3716
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003717void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3718 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003719 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003720 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003721
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003722 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003723 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003724 return;
3725 }
3726
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003727 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003728 ALOGW("Trying to set power mode for virtual display");
3729 return;
3730 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003731
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003732 display->setPowerMode(mode);
3733
Lloyd Pique4dccc412018-01-22 17:21:36 -08003734 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003735 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003736 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003737 if (idx < 0) {
3738 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3739 return;
3740 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003741 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003742 }
3743
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003744 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003745 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003746 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003747 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003748 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003749 // FIXME: eventthread only knows about the main display right now
3750 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003751 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003752 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003753
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003754 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003755 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003756 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003757
3758 struct sched_param param = {0};
3759 param.sched_priority = 1;
3760 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3761 ALOGW("Couldn't set SCHED_FIFO on display on");
3762 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003763 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003764 // Turn off the display
3765 struct sched_param param = {0};
3766 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3767 ALOGW("Couldn't set SCHED_OTHER on display off");
3768 }
3769
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003770 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003771 disableHardwareVsync(true); // also cancels any in-progress resync
3772
Mathias Agopiancde87a32012-09-13 14:09:01 -07003773 // FIXME: eventthread only knows about the main display right now
3774 mEventThread->onScreenReleased();
3775 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003776
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003777 getHwComposer().setPowerMode(type, mode);
3778 mVisibleRegionsDirty = true;
3779 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003780 } else if (mode == HWC_POWER_MODE_DOZE ||
3781 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003782 // Update display while dozing
3783 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003784 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003785 // FIXME: eventthread only knows about the main display right now
3786 mEventThread->onScreenAcquired();
3787 resyncToHardwareVsync(true);
3788 }
3789 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3790 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003791 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003792 disableHardwareVsync(true); // also cancels any in-progress resync
3793 // FIXME: eventthread only knows about the main display right now
3794 mEventThread->onScreenReleased();
3795 }
3796 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003797 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003798 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003799 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003800 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003801
3802 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003803}
3804
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003805void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003806 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003807 const auto display = getDisplayDevice(displayToken);
3808 if (!display) {
3809 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3810 displayToken.get());
3811 } else if (display->isVirtual()) {
3812 ALOGW("Attempt to set power mode %d for virtual display", mode);
3813 } else {
3814 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003815 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003816 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003817}
3818
3819// ---------------------------------------------------------------------------
3820
Lloyd Pique755e3192018-01-31 16:46:15 -08003821status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3822 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003823 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003824
Mathias Agopianbd115332013-04-18 16:41:04 -07003825 IPCThreadState* ipc = IPCThreadState::self();
3826 const int pid = ipc->getCallingPid();
3827 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003828
Mathias Agopianbd115332013-04-18 16:41:04 -07003829 if ((uid != AID_SHELL) &&
3830 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003831 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003832 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003833 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003834 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003835 // (this would indicate SF is stuck, but we want to be able to
3836 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003837 status_t err = mStateLock.timedLock(s2ns(1));
3838 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003839 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003840 result.appendFormat(
3841 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3842 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003843 }
3844
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003845 bool dumpAll = true;
3846 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003847 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003848
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003849 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003850 if ((index < numArgs) &&
3851 (args[index] == String16("--list"))) {
3852 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003853 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003854 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003855 }
3856
3857 if ((index < numArgs) &&
3858 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003859 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003860 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003861 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003862 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003863
3864 if ((index < numArgs) &&
3865 (args[index] == String16("--latency-clear"))) {
3866 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003867 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003868 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003869 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003870
3871 if ((index < numArgs) &&
3872 (args[index] == String16("--dispsync"))) {
3873 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07003874 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07003875 dumpAll = false;
3876 }
Dan Stozab90cf072015-03-05 11:05:59 -08003877
3878 if ((index < numArgs) &&
3879 (args[index] == String16("--static-screen"))) {
3880 index++;
3881 dumpStaticScreenStats(result);
3882 dumpAll = false;
3883 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003884
3885 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003886 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003887 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003888 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003889 dumpAll = false;
3890 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003891
3892 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3893 index++;
3894 dumpWideColorInfo(result);
3895 dumpAll = false;
3896 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003897
3898 if ((index < numArgs) &&
3899 (args[index] == String16("--enable-layer-stats"))) {
3900 index++;
3901 mLayerStats.enable();
3902 dumpAll = false;
3903 }
3904
3905 if ((index < numArgs) &&
3906 (args[index] == String16("--disable-layer-stats"))) {
3907 index++;
3908 mLayerStats.disable();
3909 dumpAll = false;
3910 }
3911
3912 if ((index < numArgs) &&
3913 (args[index] == String16("--clear-layer-stats"))) {
3914 index++;
3915 mLayerStats.clear();
3916 dumpAll = false;
3917 }
3918
3919 if ((index < numArgs) &&
3920 (args[index] == String16("--dump-layer-stats"))) {
3921 index++;
3922 mLayerStats.dump(result);
3923 dumpAll = false;
3924 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003925
3926 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08003927 (args[index] == String16("--frame-composition"))) {
3928 index++;
3929 dumpFrameCompositionInfo(result);
3930 dumpAll = false;
3931 }
3932
3933 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003934 (args[index] == String16("--display-identification"))) {
3935 index++;
3936 dumpDisplayIdentificationData(result);
3937 dumpAll = false;
3938 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003939
3940 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3941 index++;
3942 mTimeStats.parseArgs(asProto, args, index, result);
3943 dumpAll = false;
3944 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003945 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003946
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003947 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003948 if (asProto) {
3949 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3950 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3951 } else {
3952 dumpAllLocked(args, index, result);
3953 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003954 }
3955
Mathias Agopian9795c422009-08-26 16:36:26 -07003956 if (locked) {
3957 mStateLock.unlock();
3958 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003959 }
3960 write(fd, result.string(), result.size());
3961 return NO_ERROR;
3962}
3963
Dan Stozac7014012014-02-14 15:03:43 -08003964void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3965 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003966{
Robert Carr2047fae2016-11-28 14:09:09 -08003967 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003968 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003969 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003970}
3971
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003972void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003973 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003974{
3975 String8 name;
3976 if (index < args.size()) {
3977 name = String8(args[index]);
3978 index++;
3979 }
3980
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003981 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
3982 getHwComposer().isConnected(displayId)) {
3983 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
3984 const nsecs_t period = activeConfig->getVsyncPeriod();
3985 result.appendFormat("%" PRId64 "\n", period);
3986 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003987
3988 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003989 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003990 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003991 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003992 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003993 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003994 }
Robert Carr2047fae2016-11-28 14:09:09 -08003995 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003996 }
3997}
3998
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003999void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004000 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004001{
4002 String8 name;
4003 if (index < args.size()) {
4004 name = String8(args[index]);
4005 index++;
4006 }
4007
Robert Carr2047fae2016-11-28 14:09:09 -08004008 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004009 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004010 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004011 }
Robert Carr2047fae2016-11-28 14:09:09 -08004012 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004013
Svetoslavd85084b2014-03-20 10:28:31 -07004014 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004015}
4016
Jamie Gennis6547ff42013-07-16 20:12:42 -07004017// This should only be called from the main thread. Otherwise it would need
4018// the lock and should use mCurrentState rather than mDrawingState.
4019void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004020 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004021 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004022 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004023
4024 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4025}
4026
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004027void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004028{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004029 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004030
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004031 if (isLayerTripleBufferingDisabled())
4032 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004033
4034 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004035 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004036 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004037 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004038 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4039 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004040 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004041}
4042
Dan Stozab90cf072015-03-05 11:05:59 -08004043void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4044{
4045 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004046 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4047 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004048 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004049 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004050 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4051 b + 1, bucketTimeSec, percent);
4052 }
David Sodman4a36e932017-11-07 14:29:47 -08004053 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004054 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004055 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004056 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004057 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004058}
4059
Dan Stozae77c7662016-05-13 11:37:28 -07004060void SurfaceFlinger::recordBufferingStats(const char* layerName,
4061 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004062 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4063 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004064 for (const auto& segment : history) {
4065 if (!segment.usedThirdBuffer) {
4066 stats.twoBufferTime += segment.totalTime;
4067 }
4068 if (segment.occupancyAverage < 1.0f) {
4069 stats.doubleBufferedTime += segment.totalTime;
4070 } else if (segment.occupancyAverage < 2.0f) {
4071 stats.tripleBufferedTime += segment.totalTime;
4072 }
4073 ++stats.numSegments;
4074 stats.totalTime += segment.totalTime;
4075 }
4076}
4077
Brian Andersond6927fb2016-07-23 23:37:30 -07004078void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4079 result.appendFormat("Layer frame timestamps:\n");
4080
4081 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4082 const size_t count = currentLayers.size();
4083 for (size_t i=0 ; i<count ; i++) {
4084 currentLayers[i]->dumpFrameEvents(result);
4085 }
4086}
4087
Dan Stozae77c7662016-05-13 11:37:28 -07004088void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4089 result.append("Buffering stats:\n");
4090 result.append(" [Layer name] <Active time> <Two buffer> "
4091 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004092 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004093 typedef std::tuple<std::string, float, float, float> BufferTuple;
4094 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004095 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004096 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004097 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004098 if (stats.numSegments == 0) {
4099 continue;
4100 }
4101 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4102 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4103 stats.totalTime;
4104 float doubleBufferRatio = static_cast<float>(
4105 stats.doubleBufferedTime) / stats.totalTime;
4106 float tripleBufferRatio = static_cast<float>(
4107 stats.tripleBufferedTime) / stats.totalTime;
4108 sorted.insert({activeTime, {name, twoBufferRatio,
4109 doubleBufferRatio, tripleBufferRatio}});
4110 }
4111 for (const auto& sortedPair : sorted) {
4112 float activeTime = sortedPair.first;
4113 const BufferTuple& values = sortedPair.second;
4114 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4115 std::get<0>(values).c_str(), activeTime,
4116 std::get<1>(values), std::get<2>(values),
4117 std::get<3>(values));
4118 }
4119 result.append("\n");
4120}
4121
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004122void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004123 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004124 const int32_t displayId = display->getId();
4125 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4126 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004127 continue;
4128 }
4129
Dominik Laskowski7e045462018-05-30 13:02:02 -07004130 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004131 uint8_t port;
4132 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004133 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004134 result.append("no identification data\n");
4135 continue;
4136 }
4137
4138 if (!isEdid(data)) {
4139 result.append("unknown identification data: ");
4140 for (uint8_t byte : data) {
4141 result.appendFormat("%x ", byte);
4142 }
4143 result.append("\n");
4144 continue;
4145 }
4146
4147 const auto edid = parseEdid(data);
4148 if (!edid) {
4149 result.append("invalid EDID: ");
4150 for (uint8_t byte : data) {
4151 result.appendFormat("%x ", byte);
4152 }
4153 result.append("\n");
4154 continue;
4155 }
4156
4157 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4158 result.append(edid->displayName.data(), edid->displayName.length());
4159 result.append("\"\n");
4160 }
4161 result.append("\n");
4162}
4163
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004164void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004165 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4166 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004167 result.appendFormat("DisplayColorSetting: %s\n",
4168 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004169
4170 // TODO: print out if wide-color mode is active or not
4171
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004172 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004173 const int32_t displayId = display->getId();
4174 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004175 continue;
4176 }
4177
Dominik Laskowski7e045462018-05-30 13:02:02 -07004178 result.appendFormat("Display %d color modes:\n", displayId);
4179 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004180 for (auto&& mode : modes) {
4181 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4182 }
4183
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004184 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004185 result.appendFormat(" Current color mode: %s (%d)\n",
4186 decodeColorMode(currentMode).c_str(), currentMode);
4187 }
4188 result.append("\n");
4189}
4190
David Sodman7e4ae112018-02-09 15:02:28 -08004191void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4192 std::string stringResult;
4193
4194 for (const auto& [token, display] : mDisplays) {
4195 const auto displayId = display->getId();
4196 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
4197 continue;
4198 }
4199
4200 const auto& compositionInfoIt = getBE().mEndOfFrameCompositionInfo.find(displayId);
4201 if (compositionInfoIt == getBE().mEndOfFrameCompositionInfo.end()) {
4202 break;
4203 }
4204 const auto& compositionInfoList = compositionInfoIt->second;
4205 stringResult += base::StringPrintf("Display: %d\n", displayId);
4206 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4207 for (const auto& compositionInfo : compositionInfoList) {
4208 compositionInfo.dump(stringResult, nullptr);
4209 stringResult += base::StringPrintf("\n");
4210 }
4211 }
4212
4213 result.append(stringResult.c_str());
4214}
4215
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004216LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004217 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004218 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4219 const State& state = useDrawing ? mDrawingState : mCurrentState;
4220 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004221 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004222 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004223 });
4224
4225 return layersProto;
4226}
4227
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004228LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004229 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004230
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004231 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004232 resolution->set_w(display.getWidth());
4233 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004234
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004235 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4236 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4237 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004238
Dominik Laskowski7e045462018-05-30 13:02:02 -07004239 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004240 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004241 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004242 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004243 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004244 }
4245 });
4246
4247 return layersProto;
4248}
4249
Mathias Agopian74d211a2013-04-22 16:55:35 +02004250void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4251 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004252{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004253 bool colorize = false;
4254 if (index < args.size()
4255 && (args[index] == String16("--color"))) {
4256 colorize = true;
4257 index++;
4258 }
4259
4260 Colorizer colorizer(colorize);
4261
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004262 // figure out if we're stuck somewhere
4263 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004264 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004265 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4266
4267 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004268 * Dump library configuration.
4269 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004270
4271 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004272 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004273 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004274 appendSfConfigString(result);
4275 appendUiConfigString(result);
4276 appendGuiConfigString(result);
4277 result.append("\n");
4278
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004279 result.append("\nDisplay identification data:\n");
4280 dumpDisplayIdentificationData(result);
4281
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004282 result.append("\nWide-Color information:\n");
4283 dumpWideColorInfo(result);
4284
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004285 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004286 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004287 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004288 result.append(SyncFeatures::getInstance().toString());
4289 result.append("\n");
4290
Andy McFadden41d67d72014-04-25 16:58:34 -07004291 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004292 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004293 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004294
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004295 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4296 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004297 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4298 getHwComposer().isConnected(displayId)) {
4299 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004300 result.appendFormat("Display %d: "
4301 "app phase %" PRId64 " ns, "
4302 "sf phase %" PRId64 " ns, "
4303 "early app phase %" PRId64 " ns, "
4304 "early sf phase %" PRId64 " ns, "
4305 "early app gl phase %" PRId64 " ns, "
4306 "early sf gl phase %" PRId64 " ns, "
4307 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4308 displayId,
4309 vsyncPhaseOffsetNs,
4310 sfVsyncPhaseOffsetNs,
4311 appEarlyOffset,
4312 sfEarlyOffset,
4313 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004314 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004315 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004316 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004317 result.append("\n");
4318
Dan Stozab90cf072015-03-05 11:05:59 -08004319 // Dump static screen stats
4320 result.append("\n");
4321 dumpStaticScreenStats(result);
4322 result.append("\n");
4323
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004324 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4325
Dan Stozae77c7662016-05-13 11:37:28 -07004326 dumpBufferingStats(result);
4327
Andy McFadden4803b742012-09-24 19:07:20 -07004328 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004329 * Dump the visible layer list
4330 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004331 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004332 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004333 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4334 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004335 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004336
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004337 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004338 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004339 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004340 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004341
David Sodman7e4ae112018-02-09 15:02:28 -08004342 result.append("\nFrame-Composition information:\n");
4343 dumpFrameCompositionInfo(result);
4344 result.append("\n");
4345
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004346 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004347 * Dump Display state
4348 */
4349
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004350 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004351 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004352 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004353 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004354 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004355 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004356 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004357
4358 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004359 * Dump SurfaceFlinger global state
4360 */
4361
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004362 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004363 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004364 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004365
Mathias Agopian888c8222012-08-04 21:10:38 -07004366 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004367 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004368
David Sodmanbc815282017-11-05 18:57:52 -08004369 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004370
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004371 if (display) {
4372 display->undefinedRegion.dump(result, "undefinedRegion");
4373 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4374 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004375 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004376 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004377 " gpu_to_cpu_unsupported : %d\n",
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004378 mTransactionFlags, !mGpuToCpuSupported);
4379
4380 if (display) {
4381 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4382 result.appendFormat(" refresh-rate : %f fps\n"
4383 " x-dpi : %f\n"
4384 " y-dpi : %f\n",
4385 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4386 activeConfig->getDpiY());
4387 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004388
Mathias Agopian74d211a2013-04-22 16:55:35 +02004389 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004390 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004391
4392 /*
4393 * VSYNC state
4394 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004395 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004396 result.append("\n");
4397
4398 /*
4399 * HWC layer minidump
4400 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004401 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004402 const int32_t displayId = display->getId();
4403 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004404 continue;
4405 }
4406
Dominik Laskowski7e045462018-05-30 13:02:02 -07004407 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004408 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004409 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004410 result.append("\n");
4411 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004412
4413 /*
4414 * Dump HWComposer state
4415 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004416 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004417 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004418 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004419 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004420 result.appendFormat(" h/w composer %s\n",
4421 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004422 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004423
4424 /*
4425 * Dump gralloc state
4426 */
4427 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4428 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004429
4430 /*
4431 * Dump VrFlinger state if in use.
4432 */
4433 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4434 result.append("VrFlinger state:\n");
4435 result.append(mVrFlinger->Dump().c_str());
4436 result.append("\n");
4437 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004438}
4439
Dominik Laskowski7e045462018-05-30 13:02:02 -07004440const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004441 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004442 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004443 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004444 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004445 }
4446 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004447
4448 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4449 static const Vector<sp<Layer>> empty;
4450 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004451}
4452
Keun young Park63f165f2012-08-31 10:53:36 -07004453bool SurfaceFlinger::startDdmConnection()
4454{
4455 void* libddmconnection_dso =
4456 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4457 if (!libddmconnection_dso) {
4458 return false;
4459 }
4460 void (*DdmConnection_start)(const char* name);
4461 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004462 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004463 if (!DdmConnection_start) {
4464 dlclose(libddmconnection_dso);
4465 return false;
4466 }
4467 (*DdmConnection_start)(getServiceName());
4468 return true;
4469}
4470
Chia-I Wu28f320b2018-05-03 11:02:56 -07004471void SurfaceFlinger::updateColorMatrixLocked() {
4472 mat4 colorMatrix;
4473 if (mGlobalSaturationFactor != 1.0f) {
4474 // Rec.709 luma coefficients
4475 float3 luminance{0.213f, 0.715f, 0.072f};
4476 luminance *= 1.0f - mGlobalSaturationFactor;
4477 mat4 saturationMatrix = mat4(
4478 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4479 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4480 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4481 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4482 );
4483 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4484 } else {
4485 colorMatrix = mClientColorMatrix * mDaltonizer();
4486 }
4487
4488 if (mCurrentState.colorMatrix != colorMatrix) {
4489 mCurrentState.colorMatrix = colorMatrix;
4490 mCurrentState.colorMatrixChanged = true;
4491 setTransactionFlags(eTransactionNeeded);
4492 }
4493}
4494
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004495status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004496#pragma clang diagnostic push
4497#pragma clang diagnostic error "-Wswitch-enum"
4498 switch (static_cast<ISurfaceComposerTag>(code)) {
4499 // These methods should at minimum make sure that the client requested
4500 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004501 case BOOT_FINISHED:
4502 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004503 case CREATE_CONNECTION:
4504 case CREATE_DISPLAY:
4505 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004506 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004507 case GET_ACTIVE_COLOR_MODE:
4508 case GET_ANIMATION_FRAME_STATS:
4509 case GET_HDR_CAPABILITIES:
4510 case SET_ACTIVE_CONFIG:
4511 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004512 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004513 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004514 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4515 IPCThreadState* ipc = IPCThreadState::self();
4516 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4517 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004518 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004519 }
Robert Carr1db73f62016-12-21 12:58:51 -08004520 return OK;
4521 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004522 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004523 IPCThreadState* ipc = IPCThreadState::self();
4524 const int pid = ipc->getCallingPid();
4525 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004526 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4527 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004528 return PERMISSION_DENIED;
4529 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004530 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004531 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004532 // Used by apps to hook Choreographer to SurfaceFlinger.
4533 case CREATE_DISPLAY_EVENT_CONNECTION:
4534 // The following calls are currently used by clients that do not
4535 // request necessary permissions. However, they do not expose any secret
4536 // information, so it is OK to pass them.
4537 case AUTHENTICATE_SURFACE:
4538 case GET_ACTIVE_CONFIG:
4539 case GET_BUILT_IN_DISPLAY:
4540 case GET_DISPLAY_COLOR_MODES:
4541 case GET_DISPLAY_CONFIGS:
4542 case GET_DISPLAY_STATS:
4543 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4544 // Calling setTransactionState is safe, because you need to have been
4545 // granted a reference to Client* and Handle* to do anything with it.
4546 case SET_TRANSACTION_STATE:
4547 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4548 case CREATE_SCOPED_CONNECTION: {
4549 return OK;
4550 }
4551 case CAPTURE_LAYERS:
4552 case CAPTURE_SCREEN: {
4553 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004554 IPCThreadState* ipc = IPCThreadState::self();
4555 const int pid = ipc->getCallingPid();
4556 const int uid = ipc->getCallingUid();
4557 if ((uid != AID_GRAPHICS) &&
4558 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4559 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4560 return PERMISSION_DENIED;
4561 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004562 return OK;
4563 }
4564 // The following codes are deprecated and should never be allowed to access SF.
4565 case CONNECT_DISPLAY_UNUSED:
4566 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4567 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4568 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004569 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004570 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004571
4572 // These codes are used for the IBinder protocol to either interrogate the recipient
4573 // side of the transaction for its canonical interface descriptor or to dump its state.
4574 // We let them pass by default.
4575 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4576 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4577 code == IBinder::SYSPROPS_TRANSACTION) {
4578 return OK;
4579 }
4580 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4581 // in onTransact verifies that the user is root, and has access to use SF.
4582 if (code >= 1000 && code <= 1029) {
4583 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4584 return OK;
4585 }
4586 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4587 return PERMISSION_DENIED;
4588#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004589}
4590
Ana Krulec13be8ad2018-08-21 02:43:56 +00004591status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4592 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004593 status_t credentialCheck = CheckTransactCodeCredentials(code);
4594 if (credentialCheck != OK) {
4595 return credentialCheck;
4596 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004597
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004598 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4599 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004600 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004601 IPCThreadState* ipc = IPCThreadState::self();
4602 const int uid = ipc->getCallingUid();
4603 if (CC_UNLIKELY(uid != AID_SYSTEM
4604 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004605 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004606 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004607 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004608 return PERMISSION_DENIED;
4609 }
4610 int n;
4611 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004612 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004613 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004614 return NO_ERROR;
4615 case 1002: // SHOW_UPDATES
4616 n = data.readInt32();
4617 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004618 invalidateHwcGeometry();
4619 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004620 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004621 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004622 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004623 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004624 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004625 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004626 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004627 setTransactionFlags(
4628 eTransactionNeeded|
4629 eDisplayTransactionNeeded|
4630 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004631 return NO_ERROR;
4632 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004633 case 1006:{ // send empty update
4634 signalRefresh();
4635 return NO_ERROR;
4636 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004637 case 1008: // toggle use of hw composer
4638 n = data.readInt32();
4639 mDebugDisableHWC = n ? 1 : 0;
4640 invalidateHwcGeometry();
4641 repaintEverything();
4642 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004643 case 1009: // toggle use of transform hint
4644 n = data.readInt32();
4645 mDebugDisableTransformHint = n ? 1 : 0;
4646 invalidateHwcGeometry();
4647 repaintEverything();
4648 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004649 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004650 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004651 reply->writeInt32(0);
4652 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004653 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004654 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004655 return NO_ERROR;
4656 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004657 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004658 if (!display) {
4659 return NAME_NOT_FOUND;
4660 }
4661
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004662 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004663 return NO_ERROR;
4664 }
4665 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004666 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004667 // daltonize
4668 n = data.readInt32();
4669 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004670 case 1:
4671 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4672 break;
4673 case 2:
4674 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4675 break;
4676 case 3:
4677 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4678 break;
4679 default:
4680 mDaltonizer.setType(ColorBlindnessType::None);
4681 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004682 }
4683 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004684 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004685 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004686 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004687 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004688
4689 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004690 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004691 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004692 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004693 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004694 // apply a color matrix
4695 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004696 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004697 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004698 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004699 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004700 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004701 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004702 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004703 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004704 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004705 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004706
4707 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4708 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004709 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004710 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4711 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4712 }
4713
Chia-I Wu28f320b2018-05-03 11:02:56 -07004714 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004715 return NO_ERROR;
4716 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004717 // This is an experimental interface
4718 // Needs to be shifted to proper binder interface when we productize
4719 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004720 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07004721 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004722 return NO_ERROR;
4723 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004724 case 1017: {
4725 n = data.readInt32();
4726 mForceFullDamage = static_cast<bool>(n);
4727 return NO_ERROR;
4728 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004729 case 1018: { // Modify Choreographer's phase offset
4730 n = data.readInt32();
4731 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4732 return NO_ERROR;
4733 }
4734 case 1019: { // Modify SurfaceFlinger's phase offset
4735 n = data.readInt32();
4736 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4737 return NO_ERROR;
4738 }
Irvel468051e2016-06-13 16:44:44 -07004739 case 1020: { // Layer updates interceptor
4740 n = data.readInt32();
4741 if (n) {
4742 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004743 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004744 }
4745 else{
4746 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004747 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004748 }
4749 return NO_ERROR;
4750 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004751 case 1021: { // Disable HWC virtual displays
4752 n = data.readInt32();
4753 mUseHwcVirtualDisplays = !n;
4754 return NO_ERROR;
4755 }
Romain Guy0147a172017-06-01 13:53:56 -07004756 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004757 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004758 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004759
Chia-I Wu28f320b2018-05-03 11:02:56 -07004760 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004761 return NO_ERROR;
4762 }
Romain Guy54f154a2017-10-24 21:40:32 +01004763 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004764 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004765 invalidateHwcGeometry();
4766 repaintEverything();
4767 return NO_ERROR;
4768 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004769 // TODO(b/111505327): Find out whether the usage of 1024 can switch to 1030,
4770 // deprecate 1024 if they can.
4771 case 1024: { // Does device have wide color gamut display?
Romain Guy54f154a2017-10-24 21:40:32 +01004772 reply->writeBool(hasWideColorDisplay);
4773 return NO_ERROR;
4774 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004775 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004776 n = data.readInt32();
4777 if (n) {
4778 ALOGV("LayerTracing enabled");
4779 mTracing.enable();
4780 doTracing("tracing.enable");
4781 reply->writeInt32(NO_ERROR);
4782 } else {
4783 ALOGV("LayerTracing disabled");
4784 status_t err = mTracing.disable();
4785 reply->writeInt32(err);
4786 }
4787 return NO_ERROR;
4788 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004789 case 1026: { // Get layer tracing status
4790 reply->writeBool(mTracing.isEnabled());
4791 return NO_ERROR;
4792 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004793 // Is a DisplayColorSetting supported?
4794 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004795 const auto display = getDefaultDisplayDevice();
4796 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004797 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004798 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004799
4800 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4801 switch (setting) {
4802 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07004803 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004804 break;
4805 case DisplayColorSetting::UNMANAGED:
4806 reply->writeBool(true);
4807 break;
4808 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004809 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004810 break;
4811 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004812 reply->writeBool(
4813 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004814 break;
4815 }
4816 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004817 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004818 // Is VrFlinger active?
4819 case 1028: {
4820 Mutex::Autolock _l(mStateLock);
4821 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4822 return NO_ERROR;
4823 }
David Sodman6d46c1e2018-07-13 12:59:48 -07004824 case 1029: {
4825 // Code 1029 is an experimental feature that allows applications to
4826 // simulate a high frequency panel by setting a multiplier and divisor
4827 // on the VSYNC-sf clock. If either the multiplier or divisor are
4828 // 0, then the code will set both to 1 to return the VSYNC-sf clock
4829 // to it's normal frequency.
4830 int multiplier = data.readInt32();
4831 int divisor = data.readInt32();
4832
4833 if ((multiplier == 0) || (divisor == 0)) {
4834 multiplier = 1;
4835 divisor = 1;
4836 }
4837
4838 if ((multiplier == 1) && (divisor == 1)) {
4839 enableHardwareVsync();
4840 } else {
4841 disableHardwareVsync(true);
4842 }
4843 getBE().mHwc->getActiveConfig(DisplayDevice::DISPLAY_PRIMARY)
4844 ->scalePanelFrequency(multiplier, divisor);
4845 mPrimaryDispSync->scalePeriod(multiplier, divisor);
4846
4847 ATRACE_INT("PeriodMultiplier", multiplier);
4848 ATRACE_INT("PeriodDivisor", divisor);
4849 return NO_ERROR;
4850 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004851 // Is device color managed?
4852 case 1030: {
4853 reply->writeBool(useColorManagement);
4854 return NO_ERROR;
4855 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004856 }
4857 }
4858 return err;
4859}
4860
Steven Thomas6d8110b2017-08-31 18:24:21 -07004861void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004862 android_atomic_or(1, &mRepaintEverything);
4863 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004864}
4865
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004866// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4867class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004868public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004869 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4870 ~WindowDisconnector() {
4871 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004872 }
4873
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004874private:
4875 ANativeWindow* mWindow;
4876 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004877};
4878
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004879status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4880 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4881 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4882 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004883 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004884 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004885
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004886 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004887
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004888 const auto display = getDisplayDeviceLocked(displayToken);
4889 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004890
Yiwei Zhang06a58e22018-08-20 16:42:23 -07004891 const Rect& dispScissor = display->getScissor();
4892 if (!dispScissor.isEmpty()) {
4893 sourceCrop.set(dispScissor);
4894 // adb shell screencap will default reqWidth and reqHeight to zeros.
4895 if (reqWidth == 0 || reqHeight == 0) {
Yiwei Zhangec90e582018-08-21 22:11:37 -07004896 reqWidth = uint32_t(display->getViewport().width());
4897 reqHeight = uint32_t(display->getViewport().height());
Yiwei Zhang06a58e22018-08-20 16:42:23 -07004898 }
4899 }
4900
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004901 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004902
4903 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004904 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004905 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004906}
4907
4908status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004909 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004910 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004911 ATRACE_CALL();
4912
4913 class LayerRenderArea : public RenderArea {
4914 public:
Robert Carr578038f2018-03-09 12:25:24 -08004915 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4916 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004917 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004918 mLayer(layer),
4919 mCrop(crop),
4920 mFlinger(flinger),
4921 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07004922 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004923 Rect getBounds() const override {
4924 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07004925 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07004926 }
Marissa Wall61c58622018-07-18 10:12:20 -07004927 int getHeight() const override {
4928 return mLayer->getActiveHeight(mLayer->getDrawingState());
4929 }
4930 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07004931 bool isSecure() const override { return false; }
4932 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004933 Rect getSourceCrop() const override {
4934 if (mCrop.isEmpty()) {
4935 return getBounds();
4936 } else {
4937 return mCrop;
4938 }
4939 }
Robert Carr578038f2018-03-09 12:25:24 -08004940 class ReparentForDrawing {
4941 public:
4942 const sp<Layer>& oldParent;
4943 const sp<Layer>& newParent;
4944
4945 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4946 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004947 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004948 }
Robert Carr15eae092018-03-23 13:43:53 -07004949 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004950 };
4951
4952 void render(std::function<void()> drawLayers) override {
4953 if (!mChildrenOnly) {
4954 mTransform = mLayer->getTransform().inverse();
4955 drawLayers();
4956 } else {
4957 Rect bounds = getBounds();
4958 screenshotParentLayer =
4959 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4960 bounds.getWidth(), bounds.getHeight(), 0);
4961
4962 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4963 drawLayers();
4964 }
4965 }
chaviwa76b2712017-09-20 12:02:26 -07004966
chaviwa76b2712017-09-20 12:02:26 -07004967 private:
chaviw7206d492017-11-10 16:16:12 -08004968 const sp<Layer> mLayer;
4969 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004970
4971 // In the "childrenOnly" case we reparent the children to a screenshot
4972 // layer which has no properties set and which does not draw.
4973 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07004974 ui::Transform mTransform;
Robert Carr578038f2018-03-09 12:25:24 -08004975
4976 SurfaceFlinger* mFlinger;
4977 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004978 };
4979
4980 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4981 auto parent = layerHandle->owner.promote();
4982
chaviw7206d492017-11-10 16:16:12 -08004983 if (parent == nullptr || parent->isPendingRemoval()) {
4984 ALOGE("captureLayers called with a removed parent");
4985 return NAME_NOT_FOUND;
4986 }
4987
Robert Carr578038f2018-03-09 12:25:24 -08004988 const int uid = IPCThreadState::self()->getCallingUid();
4989 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4990 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4991 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4992 return PERMISSION_DENIED;
4993 }
4994
chaviw7206d492017-11-10 16:16:12 -08004995 Rect crop(sourceCrop);
4996 if (sourceCrop.width() <= 0) {
4997 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07004998 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08004999 }
5000
5001 if (sourceCrop.height() <= 0) {
5002 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005003 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005004 }
5005
5006 int32_t reqWidth = crop.width() * frameScale;
5007 int32_t reqHeight = crop.height() * frameScale;
5008
Robert Carr578038f2018-03-09 12:25:24 -08005009 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005010
Robert Carr578038f2018-03-09 12:25:24 -08005011 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005012 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5013 if (!layer->isVisible()) {
5014 return;
Robert Carr578038f2018-03-09 12:25:24 -08005015 } else if (childrenOnly && layer == parent.get()) {
5016 return;
chaviwa76b2712017-09-20 12:02:26 -07005017 }
5018 visitor(layer);
5019 });
5020 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005021 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005022}
5023
5024status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5025 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005026 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005027 bool useIdentityTransform) {
5028 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005029
Iris Chang7501ed62018-04-30 14:45:42 +08005030 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07005031
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005032 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5033 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5034 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5035 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005036
5037 // This mutex protects syncFd and captureResult for communication of the return values from the
5038 // main thread back to this Binder thread
5039 std::mutex captureMutex;
5040 std::condition_variable captureCondition;
5041 std::unique_lock<std::mutex> captureLock(captureMutex);
5042 int syncFd = -1;
5043 std::optional<status_t> captureResult;
5044
Robert Carr03480e22018-01-04 16:02:06 -08005045 const int uid = IPCThreadState::self()->getCallingUid();
5046 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5047
Dominik Laskowski8c001672018-05-30 16:52:06 -07005048 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005049 // If there is a refresh pending, bug out early and tell the binder thread to try again
5050 // after the refresh.
5051 if (mRefreshPending) {
5052 ATRACE_NAME("Skipping screenshot for now");
5053 std::unique_lock<std::mutex> captureLock(captureMutex);
5054 captureResult = std::make_optional<status_t>(EAGAIN);
5055 captureCondition.notify_one();
5056 return;
5057 }
5058
5059 status_t result = NO_ERROR;
5060 int fd = -1;
5061 {
5062 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005063 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005064 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5065 useIdentityTransform, forSystem, &fd);
5066 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005067 }
5068
5069 {
5070 std::unique_lock<std::mutex> captureLock(captureMutex);
5071 syncFd = fd;
5072 captureResult = std::make_optional<status_t>(result);
5073 captureCondition.notify_one();
5074 }
5075 });
5076
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005077 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005078 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005079 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005080 while (*captureResult == EAGAIN) {
5081 captureResult.reset();
5082 result = postMessageAsync(message);
5083 if (result != NO_ERROR) {
5084 return result;
5085 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005086 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005087 }
5088 result = *captureResult;
5089 }
5090
5091 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005092 sync_wait(syncFd, -1);
5093 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005094 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005095
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005096 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005097}
5098
chaviwa76b2712017-09-20 12:02:26 -07005099void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5100 TraverseLayersFunction traverseLayers, bool yswap,
5101 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005102 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005103
Lloyd Pique144e1162017-12-20 16:44:52 -08005104 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005105
5106 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005107 const auto raWidth = renderArea.getWidth();
5108 const auto raHeight = renderArea.getHeight();
5109
5110 const auto reqWidth = renderArea.getReqWidth();
5111 const auto reqHeight = renderArea.getReqHeight();
5112 Rect sourceCrop = renderArea.getSourceCrop();
5113
Iris Chang7501ed62018-04-30 14:45:42 +08005114 bool filtering = false;
5115 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5116 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5117 static_cast<int32_t>(reqHeight) != raWidth;
5118 } else {
5119 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5120 static_cast<int32_t>(reqHeight) != raHeight;
5121 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005122
Dan Stozac1879002014-05-22 15:59:05 -07005123 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005124 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005125 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005126 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005127 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
Peiyong Linefefaac2018-08-17 12:27:51 -07005128 ui::Transform tr;
Iris Chang7501ed62018-04-30 14:45:42 +08005129 uint32_t flags = 0x00;
5130 switch (mPrimaryDisplayOrientation) {
5131 case DisplayState::eOrientation90:
Peiyong Linefefaac2018-08-17 12:27:51 -07005132 flags = ui::Transform::ROT_90;
Iris Chang7501ed62018-04-30 14:45:42 +08005133 break;
5134 case DisplayState::eOrientation180:
Peiyong Linefefaac2018-08-17 12:27:51 -07005135 flags = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005136 break;
5137 case DisplayState::eOrientation270:
Peiyong Linefefaac2018-08-17 12:27:51 -07005138 flags = ui::Transform::ROT_270;
Iris Chang7501ed62018-04-30 14:45:42 +08005139 break;
5140 }
5141 tr.set(flags, raWidth, raHeight);
5142 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005143 }
5144
5145 // ensure that sourceCrop is inside screen
5146 if (sourceCrop.left < 0) {
5147 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5148 }
chaviwa76b2712017-09-20 12:02:26 -07005149 if (sourceCrop.right > raWidth) {
5150 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005151 }
5152 if (sourceCrop.top < 0) {
5153 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5154 }
chaviwa76b2712017-09-20 12:02:26 -07005155 if (sourceCrop.bottom > raHeight) {
5156 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005157 }
5158
Chia-I Wu36574d92018-05-16 10:54:36 -07005159 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5160 engine.setOutputDataSpace(Dataspace::SRGB);
5161 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005162
Mathias Agopian180f10d2013-04-10 22:55:41 -07005163 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005164 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005165
Peiyong Linefefaac2018-08-17 12:27:51 -07005166 ui::Transform::orientation_flags rotation = renderArea.getRotationFlags();
Iris Chang7501ed62018-04-30 14:45:42 +08005167 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5168 // convert hw orientation into flag presentation
5169 // here inverse transform needed
5170 uint8_t hw_rot_90 = 0x00;
5171 uint8_t hw_flip_hv = 0x00;
5172 switch (mPrimaryDisplayOrientation) {
5173 case DisplayState::eOrientation90:
Peiyong Linefefaac2018-08-17 12:27:51 -07005174 hw_rot_90 = ui::Transform::ROT_90;
5175 hw_flip_hv = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005176 break;
5177 case DisplayState::eOrientation180:
Peiyong Linefefaac2018-08-17 12:27:51 -07005178 hw_flip_hv = ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005179 break;
5180 case DisplayState::eOrientation270:
Peiyong Linefefaac2018-08-17 12:27:51 -07005181 hw_rot_90 = ui::Transform::ROT_90;
Iris Chang7501ed62018-04-30 14:45:42 +08005182 break;
5183 }
5184
5185 // transform flags operation
5186 // 1) flip H V if both have ROT_90 flag
5187 // 2) XOR these flags
Peiyong Linefefaac2018-08-17 12:27:51 -07005188 uint8_t rotation_rot_90 = rotation & ui::Transform::ROT_90;
5189 uint8_t rotation_flip_hv = rotation & ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005190 if (rotation_rot_90 & hw_rot_90) {
Peiyong Linefefaac2018-08-17 12:27:51 -07005191 rotation_flip_hv = (~rotation_flip_hv) & ui::Transform::ROT_180;
Iris Chang7501ed62018-04-30 14:45:42 +08005192 }
Peiyong Linefefaac2018-08-17 12:27:51 -07005193 rotation = static_cast<ui::Transform::orientation_flags>
Iris Chang7501ed62018-04-30 14:45:42 +08005194 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5195 }
5196
Mathias Agopian180f10d2013-04-10 22:55:41 -07005197 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005198 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005199 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005200 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005201
chaviw50da5042018-04-09 13:49:37 -07005202 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005203 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005204 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005205
chaviwa76b2712017-09-20 12:02:26 -07005206 traverseLayers([&](Layer* layer) {
5207 if (filtering) layer->setFiltering(true);
David Sodmanca10ed22018-04-16 14:10:25 -07005208 layer->drawNow(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005209 if (filtering) layer->setFiltering(false);
5210 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005211}
5212
chaviwa76b2712017-09-20 12:02:26 -07005213status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5214 TraverseLayersFunction traverseLayers,
5215 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005216 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005217 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005218 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005219 ATRACE_CALL();
5220
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005221 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005222
5223 traverseLayers([&](Layer* layer) {
5224 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5225 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005226
Robert Carr03480e22018-01-04 16:02:06 -08005227 // We allow the system server to take screenshots of secure layers for
5228 // use in situations like the Screen-rotation animation and place
5229 // the impetus on WindowManager to not persist them.
5230 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005231 ALOGW("FB is protected: PERMISSION_DENIED");
5232 return PERMISSION_DENIED;
5233 }
5234
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005235 // this binds the given EGLImage as a framebuffer for the
5236 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005237 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005238 if (bufferBond.getStatus() != NO_ERROR) {
5239 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005240 return INVALID_OPERATION;
5241 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005242
Dan Stozaabcda352017-06-01 14:37:39 -07005243 // this will in fact render into our dequeued buffer
5244 // via an FBO, which means we didn't have to create
5245 // an EGLSurface and therefore we're not
5246 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005247 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005248
Dan Stozaabcda352017-06-01 14:37:39 -07005249 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005250 getRenderEngine().finish();
5251 *outSyncFd = -1;
5252
chaviwa76b2712017-09-20 12:02:26 -07005253 const auto reqWidth = renderArea.getReqWidth();
5254 const auto reqHeight = renderArea.getReqHeight();
5255
Dan Stozaabcda352017-06-01 14:37:39 -07005256 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5257 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005258 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005259 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005260 } else {
5261 base::unique_fd syncFd = getRenderEngine().flush();
5262 if (syncFd < 0) {
5263 getRenderEngine().finish();
5264 }
5265 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005266 }
5267
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005268 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005269}
5270
Mathias Agopiand5556842013-09-19 17:08:37 -07005271void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005272 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005273 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005274 for (size_t y = 0; y < h; y++) {
5275 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5276 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005277 if (p[x] != 0xFF000000) return;
5278 }
5279 }
chaviwa76b2712017-09-20 12:02:26 -07005280 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005281
Robert Carr2047fae2016-11-28 14:09:09 -08005282 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005283 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005284 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005285 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5286 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5287 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5288 static_cast<float>(state.color.a));
5289 i++;
5290 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005291 }
5292}
5293
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005294// ---------------------------------------------------------------------------
5295
Dan Stoza412903f2017-04-27 13:42:17 -07005296void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5297 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005298}
5299
Dan Stoza412903f2017-04-27 13:42:17 -07005300void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5301 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005302}
5303
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005304void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5305 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005306 const LayerVector::Visitor& visitor) {
5307 // We loop through the first level of layers without traversing,
5308 // as we need to interpret min/max layer Z in the top level Z space.
5309 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005310 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005311 continue;
5312 }
5313 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005314 // relative layers are traversed in Layer::traverseInZOrder
5315 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005316 continue;
5317 }
5318 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005319 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005320 return;
5321 }
chaviwa76b2712017-09-20 12:02:26 -07005322 if (!layer->isVisible()) {
5323 return;
5324 }
5325 visitor(layer);
5326 });
5327 }
5328}
5329
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005330}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005331
Lloyd Pique074e8122018-07-26 12:57:23 -07005332
Mathias Agopian3f844832013-08-07 21:24:32 -07005333#if defined(__gl_h_)
5334#error "don't include gl/gl.h in this file"
5335#endif
5336
5337#if defined(__gl2_h_)
5338#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005339#endif