blob: 399fbd83bc8a540f21695a68818da876f974261e [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"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070073#include "DispSync.h"
Robert Carr578038f2018-03-09 12:25:24 -080074#include "DisplayDevice.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070075#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080076#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070078#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080079#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080#include "SurfaceFlinger.h"
Robert Carr578038f2018-03-09 12:25:24 -080081#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082
Steven Thomasb02664d2017-07-26 18:48:28 -070083#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070084#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070085#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070086#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070087#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080088
Mathias Agopianff2ed702013-09-01 21:36:12 -070089#include "Effects/Daltonizer.h"
90
Mathias Agopian875d8e12013-06-07 15:35:48 -070091#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070092#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070093
Jiyong Park4b20c2e2017-01-14 19:45:11 +090094#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080095#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
96#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090097#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090098
chaviw1d044282017-09-27 12:19:28 -070099#include <layerproto/LayerProtoParser.h>
100
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800101#define DISPLAY_COUNT 1
102
Mathias Agopianfee2b462013-07-03 12:34:01 -0700103/*
104 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
105 * black pixels.
106 */
107#define DEBUG_SCREENSHOTS false
108
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800109namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700110
Jaesoo Lee43518572017-01-23 19:03:16 +0900111using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900112using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700113using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700114using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700115using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700116using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900117
Steven Thomasb02664d2017-07-26 18:48:28 -0700118namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700119
120#pragma clang diagnostic push
121#pragma clang diagnostic error "-Wswitch-enum"
122
123bool isWideColorMode(const ColorMode colorMode) {
124 switch (colorMode) {
125 case ColorMode::DISPLAY_P3:
126 case ColorMode::ADOBE_RGB:
127 case ColorMode::DCI_P3:
128 case ColorMode::BT2020:
129 case ColorMode::BT2100_PQ:
130 case ColorMode::BT2100_HLG:
131 return true;
132 case ColorMode::NATIVE:
133 case ColorMode::STANDARD_BT601_625:
134 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
135 case ColorMode::STANDARD_BT601_525:
136 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
137 case ColorMode::STANDARD_BT709:
138 case ColorMode::SRGB:
139 return false;
140 }
141 return false;
142}
143
144#pragma clang diagnostic pop
145
Steven Thomasb02664d2017-07-26 18:48:28 -0700146class ConditionalLock {
147public:
148 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
149 if (lock) {
150 mMutex.lock();
151 }
152 }
153 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
154private:
155 Mutex& mMutex;
156 bool mLocked;
157};
Peiyong Linfca547f2018-07-09 13:03:33 -0700158
Steven Thomasb02664d2017-07-26 18:48:28 -0700159} // namespace anonymous
160
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800161// ---------------------------------------------------------------------------
162
Mathias Agopian99b49842011-06-27 16:05:52 -0700163const String16 sHardwareTest("android.permission.HARDWARE_TEST");
164const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
165const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
166const String16 sDump("android.permission.DUMP");
167
168// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800169int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
170int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700171int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700172bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800173uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800174bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800175bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800176int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800177// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600178bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700179
Kalle Raitaa099a242017-01-11 11:17:29 -0800180
181std::string getHwcServiceName() {
182 char value[PROPERTY_VALUE_MAX] = {};
183 property_get("debug.sf.hwc_service_name", value, "default");
184 ALOGI("Using HWComposer service: '%s'", value);
185 return std::string(value);
186}
187
188bool useTrebleTestingOverride() {
189 char value[PROPERTY_VALUE_MAX] = {};
190 property_get("debug.sf.treble_testing_override", value, "false");
191 ALOGI("Treble testing override: '%s'", value);
192 return std::string(value) == "true";
193}
194
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800195std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
196 switch(displayColorSetting) {
197 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700198 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800199 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700200 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800201 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700202 return std::string("Enhanced");
203 default:
204 return std::string("Unknown ") +
205 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800206 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800207}
208
Lloyd Pique99d3da52018-01-22 17:48:03 -0800209NativeWindowSurface::~NativeWindowSurface() = default;
210
211namespace impl {
212
213class NativeWindowSurface final : public android::NativeWindowSurface {
214public:
215 static std::unique_ptr<android::NativeWindowSurface> create(
216 const sp<IGraphicBufferProducer>& producer) {
217 return std::make_unique<NativeWindowSurface>(producer);
218 }
219
220 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
221 : surface(new Surface(producer, false)) {}
222
223 ~NativeWindowSurface() override = default;
224
225private:
226 sp<ANativeWindow> getNativeWindow() const override { return surface; }
227
228 void preallocateBuffers() override { surface->allocateBuffers(); }
229
230 sp<Surface> surface;
231};
232
233} // namespace impl
234
David Sodmanbc815282017-11-05 18:57:52 -0800235SurfaceFlingerBE::SurfaceFlingerBE()
236 : mHwcServiceName(getHwcServiceName()),
237 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800238 mFrameBuckets(),
239 mTotalTime(0),
240 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800241 mComposerSequenceId(0) {
242}
243
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800244SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800245 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800246 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700247 mTransactionPending(false),
248 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700249 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700250 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700251 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800252 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700253 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800254 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800255 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800256 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800257 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800258 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700259 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700260 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700261 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700262 mDebugInSwapBuffers(0),
263 mLastSwapBufferTime(0),
264 mDebugInTransaction(0),
265 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700266 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000267 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700268 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700269 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800270 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800271 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700272 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800273 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800274 mCreateBufferQueue(&BufferQueue::createBufferQueue),
275 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800276
277SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800278 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800279
280 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
281 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
282
283 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
284 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
285
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800286 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
287 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700289 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
290 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
291
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700292 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
293 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
294
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800295 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
296 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
297
Steven Thomas050b2c82017-03-06 11:45:16 -0800298 // Vr flinger is only enabled on Daydream ready devices.
299 useVrFlinger = getBool< ISurfaceFlingerConfigs,
300 &ISurfaceFlingerConfigs::useVrFlinger>(false);
301
Fabien Sanglard1971b632017-03-10 14:50:03 -0800302 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
303 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
304
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600305 hasWideColorDisplay =
306 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
307
Iris Chang7501ed62018-04-30 14:45:42 +0800308 V1_1::DisplayOrientation primaryDisplayOrientation =
309 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
310 V1_1::DisplayOrientation::ORIENTATION_0);
311
312 switch (primaryDisplayOrientation) {
313 case V1_1::DisplayOrientation::ORIENTATION_90:
314 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
315 break;
316 case V1_1::DisplayOrientation::ORIENTATION_180:
317 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
318 break;
319 case V1_1::DisplayOrientation::ORIENTATION_270:
320 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
321 break;
322 default:
323 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
324 break;
325 }
326 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
327
David Sodman99974d22017-11-28 12:04:33 -0800328 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700329
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800330 // debugging stuff...
331 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700332
Mathias Agopianb4b17302013-03-20 18:36:41 -0700333 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700334 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700335
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800336 property_get("debug.sf.showupdates", value, "0");
337 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700338
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700339 property_get("debug.sf.ddms", value, "0");
340 mDebugDDMS = atoi(value);
341 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700342 if (!startDdmConnection()) {
343 // start failed, and DDMS debugging not enabled
344 mDebugDDMS = 0;
345 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700346 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700347 ALOGI_IF(mDebugRegion, "showupdates enabled");
348 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700349
350 property_get("debug.sf.disable_backpressure", value, "0");
351 mPropagateBackpressure = !atoi(value);
352 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700353
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800354 property_get("debug.sf.enable_hwc_vds", value, "0");
355 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800356 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800357
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800358 property_get("ro.sf.disable_triple_buffer", value, "1");
359 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800360 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700361
Yiwei Zhang243b3782018-05-15 17:40:04 -0700362 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700363 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
364 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
365
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200366 property_get("debug.sf.early_phase_offset_ns", value, "-1");
367 const int earlySfOffsetNs = atoi(value);
368
369 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
370 const int earlyGlSfOffsetNs = atoi(value);
371
372 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
373 const int earlyAppOffsetNs = atoi(value);
374
375 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
376 const int earlyGlAppOffsetNs = atoi(value);
377
378 const VSyncModulator::Offsets earlyOffsets =
379 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
380 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
381 const VSyncModulator::Offsets earlyGlOffsets =
382 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
383 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
384 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
385 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700386
Romain Guy11d63f42017-07-20 12:47:14 -0700387 // We should be reading 'persist.sys.sf.color_saturation' here
388 // but since /data may be encrypted, we need to wait until after vold
389 // comes online to attempt to read the property. The property is
390 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800391
392 if (useTrebleTestingOverride()) {
393 // Without the override SurfaceFlinger cannot connect to HIDL
394 // services that are not listed in the manifests. Considered
395 // deriving the setting from the set service name, but it
396 // would be brittle if the name that's not 'default' is used
397 // for production purposes later on.
398 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
399 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800400}
401
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800402void SurfaceFlinger::onFirstRef()
403{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800404 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800405}
406
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800407SurfaceFlinger::~SurfaceFlinger()
408{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800409}
410
Dan Stozac7014012014-02-14 15:03:43 -0800411void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800412{
413 // the window manager died on us. prepare its eulogy.
414
Andy McFadden13a082e2012-08-24 10:16:42 -0700415 // restore initial conditions (default device unblank, etc)
416 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800417
418 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700419 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800420}
421
Robert Carr1db73f62016-12-21 12:58:51 -0800422static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700423 status_t err = client->initCheck();
424 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800425 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800426 }
Robert Carr1db73f62016-12-21 12:58:51 -0800427 return nullptr;
428}
429
430sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
431 return initClient(new Client(this));
432}
433
434sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
435 const sp<IGraphicBufferProducer>& gbp) {
436 if (authenticateSurfaceTexture(gbp) == false) {
437 return nullptr;
438 }
439 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
440 if (layer == nullptr) {
441 return nullptr;
442 }
443
444 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800445}
446
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700447sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
448 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700449{
450 class DisplayToken : public BBinder {
451 sp<SurfaceFlinger> flinger;
452 virtual ~DisplayToken() {
453 // no more references, this display must be terminated
454 Mutex::Autolock _l(flinger->mStateLock);
455 flinger->mCurrentState.displays.removeItem(this);
456 flinger->setTransactionFlags(eDisplayTransactionNeeded);
457 }
458 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700459 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700460 : flinger(flinger) {
461 }
462 };
463
464 sp<BBinder> token = new DisplayToken(this);
465
466 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700467 DisplayDeviceState info;
468 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700469 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700470 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700471 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800472 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700473 return token;
474}
475
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700476void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700477 Mutex::Autolock _l(mStateLock);
478
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700479 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700480 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700481 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700482 return;
483 }
484
485 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700486 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700487 ALOGE("destroyDisplay called for non-virtual display");
488 return;
489 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700490 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700491 mCurrentState.displays.removeItemsAt(idx);
492 setTransactionFlags(eDisplayTransactionNeeded);
493}
494
Mathias Agopiane57f2922012-08-09 16:29:12 -0700495sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700496 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700497 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800498 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700499 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700500 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700501}
502
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800503void SurfaceFlinger::bootFinished()
504{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700505 if (mStartPropertySetThread->join() != NO_ERROR) {
506 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800507 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800508 const nsecs_t now = systemTime();
509 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000510 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700511
512 // wait patiently for the window manager death
513 const String16 name("window");
514 sp<IBinder> window(defaultServiceManager()->getService(name));
515 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700516 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700517 }
518
Steven Thomas050b2c82017-03-06 11:45:16 -0800519 if (mVrFlinger) {
520 mVrFlinger->OnBootFinished();
521 }
522
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700523 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700524 // formerly we would just kill the process, but we now ask it to exit so it
525 // can choose where to stop the animation.
526 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700527
528 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
529 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
530 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700531
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800532 postMessageAsync(new LambdaMessage([this] {
533 readPersistentProperties();
534 mBootStage = BootStage::FINISHED;
535 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800536}
537
Dan Stoza436ccf32018-06-21 12:10:12 -0700538uint32_t SurfaceFlinger::getNewTexture() {
539 {
540 std::lock_guard lock(mTexturePoolMutex);
541 if (!mTexturePool.empty()) {
542 uint32_t name = mTexturePool.back();
543 mTexturePool.pop_back();
544 ATRACE_INT("TexturePoolSize", mTexturePool.size());
545 return name;
546 }
547
548 // The pool was too small, so increase it for the future
549 ++mTexturePoolSize;
550 }
551
552 // The pool was empty, so we need to get a new texture name directly using a
553 // blocking call to the main thread
554 uint32_t name = 0;
555 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
556 return name;
557}
558
Mathias Agopian3f844832013-08-07 21:24:32 -0700559void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700560 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700561}
562
Lloyd Piquee83f9312018-02-01 12:53:17 -0800563class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700564public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700565 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000566 const char* name) :
567 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700568 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700569 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000570 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
571 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700572 mDispSync(dispSync),
573 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700574 mVsyncMutex(),
575 mPhaseOffset(phaseOffset),
576 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700577
Lloyd Piquee83f9312018-02-01 12:53:17 -0800578 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700579
Lloyd Piquee83f9312018-02-01 12:53:17 -0800580 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700581 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700582 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000583 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700584 static_cast<DispSync::Callback*>(this));
585 if (err != NO_ERROR) {
586 ALOGE("error registering vsync callback: %s (%d)",
587 strerror(-err), err);
588 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700589 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700590 } else {
591 status_t err = mDispSync->removeEventListener(
592 static_cast<DispSync::Callback*>(this));
593 if (err != NO_ERROR) {
594 ALOGE("error unregistering vsync callback: %s (%d)",
595 strerror(-err), err);
596 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700597 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700598 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700599 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700600 }
601
Lloyd Piquee83f9312018-02-01 12:53:17 -0800602 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700603 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700604 mCallback = callback;
605 }
606
Lloyd Piquee83f9312018-02-01 12:53:17 -0800607 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700608 Mutex::Autolock lock(mVsyncMutex);
609
610 // Normalize phaseOffset to [0, period)
611 auto period = mDispSync->getPeriod();
612 phaseOffset %= period;
613 if (phaseOffset < 0) {
614 // If we're here, then phaseOffset is in (-period, 0). After this
615 // operation, it will be in (0, period)
616 phaseOffset += period;
617 }
618 mPhaseOffset = phaseOffset;
619
620 // If we're not enabled, we don't need to mess with the listeners
621 if (!mEnabled) {
622 return;
623 }
624
Dan Stoza84d619e2018-03-28 17:07:36 -0700625 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
626 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700627 if (err != NO_ERROR) {
Dan Stoza84d619e2018-03-28 17:07:36 -0700628 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700629 strerror(-err), err);
630 }
631 }
632
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700633private:
634 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800635 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700636 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700637 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700638 callback = mCallback;
639
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700640 if (mTraceVsync) {
641 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700642 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700643 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700644 }
645
Peiyong Lin566a3b42018-01-09 18:22:43 -0800646 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700647 callback->onVSyncEvent(when);
648 }
649 }
650
Tim Murray4a4e4a22016-04-19 16:29:23 +0000651 const char* const mName;
652
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700653 int mValue;
654
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700655 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700656 const String8 mVsyncOnLabel;
657 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700658
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700659 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700660
661 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800662 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700663
664 Mutex mVsyncMutex; // Protects the following
665 nsecs_t mPhaseOffset;
666 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700667};
668
Lloyd Piquee83f9312018-02-01 12:53:17 -0800669class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700670public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800671 InjectVSyncSource() = default;
672 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700673
Lloyd Piquee83f9312018-02-01 12:53:17 -0800674 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700675 std::lock_guard<std::mutex> lock(mCallbackMutex);
676 mCallback = callback;
677 }
678
Lloyd Piquee83f9312018-02-01 12:53:17 -0800679 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700680 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700681 if (mCallback) {
682 mCallback->onVSyncEvent(when);
683 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700684 }
685
Lloyd Piquee83f9312018-02-01 12:53:17 -0800686 void setVSyncEnabled(bool) override {}
687 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700688
689private:
690 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800691 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700692};
693
Wei Wangf9b05ee2017-07-19 20:59:39 -0700694// Do not call property_set on main thread which will be blocked by init
695// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700696void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700697 ALOGI( "SurfaceFlinger's main thread ready to run. "
698 "Initializing graphics H/W...");
699
Thierry Strudel2924d012017-08-14 15:19:37 -0700700 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900701
Steven Thomasb02664d2017-07-26 18:48:28 -0700702 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800703
Steven Thomasb02664d2017-07-26 18:48:28 -0700704 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800705 mEventThreadSource =
706 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
707 true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800708 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700709 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800710 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800711 "appEventThread");
712 mSfEventThreadSource =
713 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
714 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800715
Lloyd Pique24b0a482018-03-09 18:52:26 -0800716 mSFEventThread =
717 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700718 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800719 [this](nsecs_t timestamp) {
720 mInterceptor->saveVSyncEvent(timestamp);
721 },
722 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800723 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200724 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800725
Steven Thomasb02664d2017-07-26 18:48:28 -0700726 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800727 getBE().mRenderEngine =
728 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
729 hasWideColorDisplay
730 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
731 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800732 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700733
734 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
735 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800736 getBE().mHwc.reset(
737 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700738 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800739 // Process any initial hotplug and resulting display changes.
740 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700741 const auto display = getDefaultDisplayDeviceLocked();
742 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
743 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
744 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800745
Lloyd Piquefcd86612017-12-14 17:15:36 -0800746 // make the default display GLContext current so that we can create textures
747 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700748 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800749
Steven Thomas050b2c82017-03-06 11:45:16 -0800750 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700751 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700752 // This callback is called from the vr flinger dispatch thread. We
753 // need to call signalTransaction(), which requires holding
754 // mStateLock when we're not on the main thread. Acquiring
755 // mStateLock from the vr flinger dispatch thread might trigger a
756 // deadlock in surface flinger (see b/66916578), so post a message
757 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700758 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700759 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
760 mVrFlingerRequestsDisplay = requestDisplay;
761 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700762 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800763 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700764 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
765 getHwComposer()
766 .getHwcDisplayId(display->getId())
767 .value_or(0),
768 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800769 if (!mVrFlinger) {
770 ALOGE("Failed to start vrflinger");
771 }
772 }
773
Lloyd Pique379adc12018-01-22 17:31:47 -0800774 mEventControlThread = std::make_unique<impl::EventControlThread>(
775 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700776
Mathias Agopian92a979a2012-08-02 18:32:23 -0700777 // initialize our drawing state
778 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700779
Andy McFadden13a082e2012-08-24 10:16:42 -0700780 // set initial conditions (e.g. unblank default device)
781 initializeDisplays();
782
David Sodmanbc815282017-11-05 18:57:52 -0800783 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700784
Wei Wangf9b05ee2017-07-19 20:59:39 -0700785 // Inform native graphics APIs whether the present timestamp is supported:
786 if (getHwComposer().hasCapability(
787 HWC2::Capability::PresentFenceIsNotReliable)) {
788 mStartPropertySetThread = new StartPropertySetThread(false);
789 } else {
790 mStartPropertySetThread = new StartPropertySetThread(true);
791 }
792
793 if (mStartPropertySetThread->Start() != NO_ERROR) {
794 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800795 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800796
Chia-I Wud49d6692018-06-27 07:17:41 +0800797 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
798 // is used to saturate legacy sRGB content. However, to make sure the same color under
799 // Display P3 will be saturated to the same color, we intentionally break the API spec
800 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
801 // such saturation matrix on Display P3 is understood fully, the API should always return
802 // identify matrix.
803 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
804 Dataspace::SRGB_LINEAR);
805
806 // we will apply this on Display P3.
807 if (mEnhancedSaturationMatrix != mat4()) {
808 ColorSpace srgb(ColorSpace::sRGB());
809 ColorSpace displayP3(ColorSpace::DisplayP3());
810 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
811 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
812 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
813 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800814
Dan Stoza9e56aa02015-11-02 13:00:03 -0800815 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700816}
817
Romain Guy11d63f42017-07-20 12:47:14 -0700818void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700819 Mutex::Autolock _l(mStateLock);
820
Romain Guy11d63f42017-07-20 12:47:14 -0700821 char value[PROPERTY_VALUE_MAX];
822
823 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800824 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700825 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800826 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100827
828 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700829 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700830}
831
Mathias Agopiana67e4182012-06-19 17:26:12 -0700832void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800833 // Start boot animation service by setting a property mailbox
834 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700835 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800836 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700837 if (mStartPropertySetThread->join() != NO_ERROR) {
838 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800839 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700840}
841
Mathias Agopian875d8e12013-06-07 15:35:48 -0700842size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800843 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700844}
845
Mathias Agopian875d8e12013-06-07 15:35:48 -0700846size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800847 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700848}
849
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800850// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800851
Jamie Gennis582270d2011-08-17 18:19:00 -0700852bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800853 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800854 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800855 return authenticateSurfaceTextureLocked(bufferProducer);
856}
857
858bool SurfaceFlinger::authenticateSurfaceTextureLocked(
859 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800860 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800861 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800862}
863
Brian Anderson6b376712017-04-04 10:51:39 -0700864status_t SurfaceFlinger::getSupportedFrameTimestamps(
865 std::vector<FrameEvent>* outSupported) const {
866 *outSupported = {
867 FrameEvent::REQUESTED_PRESENT,
868 FrameEvent::ACQUIRE,
869 FrameEvent::LATCH,
870 FrameEvent::FIRST_REFRESH_START,
871 FrameEvent::LAST_REFRESH_START,
872 FrameEvent::GPU_COMPOSITION_DONE,
873 FrameEvent::DEQUEUE_READY,
874 FrameEvent::RELEASE,
875 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700876 ConditionalLock _l(mStateLock,
877 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700878 if (!getHwComposer().hasCapability(
879 HWC2::Capability::PresentFenceIsNotReliable)) {
880 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
881 }
882 return NO_ERROR;
883}
884
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700885status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
886 Vector<DisplayInfo>* configs) {
887 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700888 return BAD_VALUE;
889 }
890
Jesse Hall692c7232012-11-08 15:41:56 -0800891 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700892 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
893 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700894 type = i;
895 break;
896 }
897 }
898
899 if (type < 0) {
900 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700901 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700902
Mathias Agopian8b736f12012-08-13 17:54:26 -0700903 // TODO: Not sure if display density should handled by SF any longer
904 class Density {
905 static int getDensityFromProperty(char const* propName) {
906 char property[PROPERTY_VALUE_MAX];
907 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800908 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700909 density = atoi(property);
910 }
911 return density;
912 }
913 public:
914 static int getEmuDensity() {
915 return getDensityFromProperty("qemu.sf.lcd_density"); }
916 static int getBuildDensity() {
917 return getDensityFromProperty("ro.sf.lcd_density"); }
918 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700919
Dan Stoza7f7da322014-05-02 15:26:25 -0700920 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700921
Steven Thomas6d8110b2017-08-31 18:24:21 -0700922 ConditionalLock _l(mStateLock,
923 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800924 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700925 DisplayInfo info = DisplayInfo();
926
Dan Stoza9e56aa02015-11-02 13:00:03 -0800927 float xdpi = hwConfig->getDpiX();
928 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700929
930 if (type == DisplayDevice::DISPLAY_PRIMARY) {
931 // The density of the device is provided by a build property
932 float density = Density::getBuildDensity() / 160.0f;
933 if (density == 0) {
934 // the build doesn't provide a density -- this is wrong!
935 // use xdpi instead
936 ALOGE("ro.sf.lcd_density must be defined as a build property");
937 density = xdpi / 160.0f;
938 }
939 if (Density::getEmuDensity()) {
940 // if "qemu.sf.lcd_density" is specified, it overrides everything
941 xdpi = ydpi = density = Density::getEmuDensity();
942 density /= 160.0f;
943 }
944 info.density = density;
945
946 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700947 const auto display = getDefaultDisplayDeviceLocked();
948 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700949 } else {
950 // TODO: where should this value come from?
951 static const int TV_DENSITY = 213;
952 info.density = TV_DENSITY / 160.0f;
953 info.orientation = 0;
954 }
955
Dan Stoza9e56aa02015-11-02 13:00:03 -0800956 info.w = hwConfig->getWidth();
957 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700958 info.xdpi = xdpi;
959 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800960 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900961 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800962
Andy McFadden91b2ca82014-06-13 14:04:23 -0700963 // This is how far in advance a buffer must be queued for
964 // presentation at a given time. If you want a buffer to appear
965 // on the screen at time N, you must submit the buffer before
966 // (N - presentationDeadline).
967 //
968 // Normally it's one full refresh period (to give SF a chance to
969 // latch the buffer), but this can be reduced by configuring a
970 // DispSync offset. Any additional delays introduced by the hardware
971 // composer or panel must be accounted for here.
972 //
973 // We add an additional 1ms to allow for processing time and
974 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800975 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800976 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700977
978 // All non-virtual displays are currently considered secure.
979 info.secure = true;
980
Iris Chang7501ed62018-04-30 14:45:42 +0800981 if (type == DisplayDevice::DISPLAY_PRIMARY &&
982 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
983 std::swap(info.w, info.h);
984 }
985
Michael Wright28f24d02016-07-12 13:30:53 -0700986 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700987 }
988
Dan Stoza7f7da322014-05-02 15:26:25 -0700989 return NO_ERROR;
990}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700991
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700992status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
993 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700994 return BAD_VALUE;
995 }
996
997 // FIXME for now we always return stats for the primary display
998 memset(stats, 0, sizeof(*stats));
999 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
1000 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
1001 return NO_ERROR;
1002}
1003
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001004int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
1005 const auto display = getDisplayDevice(displayToken);
1006 if (!display) {
1007 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +08001008 return BAD_VALUE;
1009 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001010
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001011 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -07001012}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001013
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001014void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
1015 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001016 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001017 return;
1018 }
1019
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001020 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001021 ALOGW("Trying to set config for virtual display");
1022 return;
1023 }
1024
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001025 display->setActiveConfig(mode);
1026 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001027}
1028
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001029status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001030 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001031 Vector<DisplayInfo> configs;
1032 getDisplayConfigs(displayToken, &configs);
1033 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
1034 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
1035 configs.size());
1036 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001037 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001038 const auto display = getDisplayDevice(displayToken);
1039 if (!display) {
1040 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
1041 displayToken.get());
1042 } else if (display->isVirtual()) {
1043 ALOGW("Attempt to set active config %d for virtual display", mode);
1044 } else {
1045 setActiveConfigInternal(display, mode);
1046 }
1047 }));
1048
Mathias Agopian888c8222012-08-04 21:10:38 -07001049 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001050}
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001051status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1052 Vector<ColorMode>* outColorModes) {
1053 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001054 return BAD_VALUE;
1055 }
1056
Michael Wright28f24d02016-07-12 13:30:53 -07001057 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001058 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
1059 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -07001060 type = i;
1061 break;
1062 }
1063 }
1064
1065 if (type < 0) {
1066 return type;
1067 }
1068
Peiyong Lina52f0292018-03-14 17:26:31 -07001069 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001070 {
1071 ConditionalLock _l(mStateLock,
1072 std::this_thread::get_id() != mMainThreadId);
1073 modes = getHwComposer().getColorModes(type);
1074 }
Michael Wright28f24d02016-07-12 13:30:53 -07001075 outColorModes->clear();
1076 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1077
1078 return NO_ERROR;
1079}
1080
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001081ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1082 if (const auto display = getDisplayDevice(displayToken)) {
1083 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001084 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001085 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001086}
1087
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001088void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1089 Dataspace dataSpace, RenderIntent renderIntent) {
1090 ColorMode currentMode = display->getActiveColorMode();
1091 Dataspace currentDataSpace = display->getCompositionDataSpace();
1092 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001093
Peiyong Lin38e9a562018-04-10 16:24:20 -07001094 if (mode == currentMode && dataSpace == currentDataSpace &&
1095 renderIntent == currentRenderIntent) {
1096 return;
1097 }
1098
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001099 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001100 ALOGW("Trying to set config for virtual display");
1101 return;
1102 }
1103
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001104 display->setActiveColorMode(mode);
1105 display->setCompositionDataSpace(dataSpace);
1106 display->setActiveRenderIntent(renderIntent);
1107 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001108
1109 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001110 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1111 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001112}
1113
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001114status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001115 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001116 Vector<ColorMode> modes;
1117 getDisplayColorModes(displayToken, &modes);
1118 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1119 if (mode < ColorMode::NATIVE || !exists) {
1120 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1121 decodeColorMode(mode).c_str(), mode, displayToken.get());
1122 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001123 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001124 const auto display = getDisplayDevice(displayToken);
1125 if (!display) {
1126 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1127 decodeColorMode(mode).c_str(), mode, displayToken.get());
1128 } else if (display->isVirtual()) {
1129 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1130 decodeColorMode(mode).c_str(), mode);
1131 } else {
1132 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1133 RenderIntent::COLORIMETRIC);
1134 }
1135 }));
1136
Michael Wright28f24d02016-07-12 13:30:53 -07001137 return NO_ERROR;
1138}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001139
Svetoslavd85084b2014-03-20 10:28:31 -07001140status_t SurfaceFlinger::clearAnimationFrameStats() {
1141 Mutex::Autolock _l(mStateLock);
1142 mAnimFrameTracker.clearStats();
1143 return NO_ERROR;
1144}
1145
1146status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1147 Mutex::Autolock _l(mStateLock);
1148 mAnimFrameTracker.getStats(outStats);
1149 return NO_ERROR;
1150}
1151
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001152status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1153 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001154 Mutex::Autolock _l(mStateLock);
1155
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001156 const auto display = getDisplayDeviceLocked(displayToken);
1157 if (!display) {
1158 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001159 return BAD_VALUE;
1160 }
1161
Peiyong Linfb069302018-04-25 14:34:31 -07001162 // At this point the DisplayDeivce should already be set up,
1163 // meaning the luminance information is already queried from
1164 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001165 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001166 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1167 capabilities.getDesiredMaxLuminance(),
1168 capabilities.getDesiredMaxAverageLuminance(),
1169 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001170
1171 return NO_ERROR;
1172}
1173
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001174status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001175 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001176 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001177
Chia-I Wu90f669f2017-10-05 14:24:41 -07001178 if (mInjectVSyncs == enable) {
1179 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001180 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001181
1182 if (enable) {
1183 ALOGV("VSync Injections enabled");
1184 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001185 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001186 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001187 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001188 impl::EventThread::InterceptVSyncsCallback(),
1189 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001190 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001191 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001192 } else {
1193 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001194 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001195 }
1196
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001197 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001198 }));
1199
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001200 return NO_ERROR;
1201}
1202
1203status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001204 Mutex::Autolock _l(mStateLock);
1205
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001206 if (!mInjectVSyncs) {
1207 ALOGE("VSync Injections not enabled");
1208 return BAD_VALUE;
1209 }
1210 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1211 ALOGV("Injecting VSync inside SurfaceFlinger");
1212 mVSyncInjector->onInjectSyncEvent(when);
1213 }
1214 return NO_ERROR;
1215}
1216
Lloyd Pique755e3192018-01-31 16:46:15 -08001217status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1218 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001219 IPCThreadState* ipc = IPCThreadState::self();
1220 const int pid = ipc->getCallingPid();
1221 const int uid = ipc->getCallingUid();
1222 if ((uid != AID_SHELL) &&
1223 !PermissionCache::checkPermission(sDump, pid, uid)) {
1224 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1225 return PERMISSION_DENIED;
1226 }
1227
1228 // Try to acquire a lock for 1s, fail gracefully
1229 const status_t err = mStateLock.timedLock(s2ns(1));
1230 const bool locked = (err == NO_ERROR);
1231 if (!locked) {
1232 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1233 return TIMED_OUT;
1234 }
1235
1236 outLayers->clear();
1237 mCurrentState.traverseInZOrder([&](Layer* layer) {
1238 outLayers->push_back(layer->getLayerDebugInfo());
1239 });
1240
1241 mStateLock.unlock();
1242 return NO_ERROR;
1243}
1244
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001245// ----------------------------------------------------------------------------
1246
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001247sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1248 ISurfaceComposer::VsyncSource vsyncSource) {
1249 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1250 return mSFEventThread->createEventConnection();
1251 } else {
1252 return mEventThread->createEventConnection();
1253 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001254}
1255
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001256// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001257
1258void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001259 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001260}
1261
1262void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001263 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001264}
1265
1266void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001267 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001268}
1269
1270void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001271 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001272 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001273}
1274
1275status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001276 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001277 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001278}
1279
1280status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001281 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001282 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001283 if (res == NO_ERROR) {
1284 msg->wait();
1285 }
1286 return res;
1287}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001288
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001289void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001290 do {
1291 waitForEvent();
1292 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001293}
1294
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001295void SurfaceFlinger::enableHardwareVsync() {
1296 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001297 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001298 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001299 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001300 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001301 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001302}
1303
Jesse Hall948fe0c2013-10-14 12:56:09 -07001304void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001305 Mutex::Autolock _l(mHWVsyncLock);
1306
Jesse Hall948fe0c2013-10-14 12:56:09 -07001307 if (makeAvailable) {
1308 mHWVsyncAvailable = true;
1309 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001310 // Hardware vsync is not currently available, so abort the resync
1311 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001312 return;
1313 }
1314
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001315 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1316 if (!getHwComposer().isConnected(displayId)) {
1317 return;
1318 }
1319
1320 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001321 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001322
1323 mPrimaryDispSync.reset();
1324 mPrimaryDispSync.setPeriod(period);
1325
1326 if (!mPrimaryHWVsyncEnabled) {
1327 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001328 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001329 mPrimaryHWVsyncEnabled = true;
1330 }
1331}
1332
Jesse Hall948fe0c2013-10-14 12:56:09 -07001333void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001334 Mutex::Autolock _l(mHWVsyncLock);
1335 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001336 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001337 mPrimaryDispSync.endResync();
1338 mPrimaryHWVsyncEnabled = false;
1339 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001340 if (makeUnavailable) {
1341 mHWVsyncAvailable = false;
1342 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001343}
1344
Tim Murray4a4e4a22016-04-19 16:29:23 +00001345void SurfaceFlinger::resyncWithRateLimit() {
1346 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001347
1348 // No explicit locking is needed here since EventThread holds a lock while calling this method
1349 static nsecs_t sLastResyncAttempted = 0;
1350 const nsecs_t now = systemTime();
1351 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001352 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001353 }
Dan Stoza57164302017-05-08 14:03:54 -07001354 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001355}
1356
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001357void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1358 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001359 ATRACE_NAME("SF onVsync");
1360
Steven Thomas3cfac282017-02-06 12:29:30 -08001361 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001362 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001363 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001364 return;
1365 }
1366
1367 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001368 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001369 return;
1370 }
1371
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001372 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1373 // For now, we don't do anything with external display vsyncs.
1374 return;
1375 }
1376
Jamie Gennisd1700752013-10-14 12:22:52 -07001377 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001378
Jamie Gennisd1700752013-10-14 12:22:52 -07001379 { // Scope for the lock
1380 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001381 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001382 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001383 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001384 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001385
1386 if (needsHwVsync) {
1387 enableHardwareVsync();
1388 } else {
1389 disableHardwareVsync(false);
1390 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001391}
1392
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001393void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001394 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1395 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001396}
1397
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001398void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001399 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001400 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001401 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001402
Lloyd Piqueba04e622017-12-14 17:11:26 -08001403 // Ignore events that do not have the right sequenceId.
1404 if (sequenceId != getBE().mComposerSequenceId) {
1405 return;
1406 }
1407
Steven Thomasb02664d2017-07-26 18:48:28 -07001408 // Only lock if we're not on the main thread. This function is normally
1409 // called on a hwbinder thread, but for the primary display it's called on
1410 // the main thread with the state lock already held, so don't attempt to
1411 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001412 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001413
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001414 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001415
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001416 if (std::this_thread::get_id() == mMainThreadId) {
1417 // Process all pending hot plug events immediately if we are on the main thread.
1418 processDisplayHotplugEventsLocked();
1419 }
1420
Lloyd Piqueba04e622017-12-14 17:11:26 -08001421 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001422}
1423
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001424void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001425 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001426 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001427 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001428 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001429 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001430}
1431
Dan Stoza9e56aa02015-11-02 13:00:03 -08001432void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001433 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001434 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001435 getHwComposer().setVsyncEnabled(disp,
1436 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001437}
1438
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001439// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001440void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001441 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001442 // Clear the drawing state so that the logic inside of
1443 // handleTransactionLocked will fire. It will determine the delta between
1444 // mCurrentState and mDrawingState and re-apply all changes when we make the
1445 // transition.
1446 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001447 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001448 mDisplays.clear();
1449}
1450
Steven Thomas050b2c82017-03-06 11:45:16 -08001451void SurfaceFlinger::updateVrFlinger() {
1452 if (!mVrFlinger)
1453 return;
1454 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001455 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001456 return;
1457 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001458
David Sodman105b7dc2017-11-04 20:28:14 -07001459 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001460 ALOGE("Vr flinger is only supported for remote hardware composer"
1461 " service connections. Ignoring request to transition to vr"
1462 " flinger.");
1463 mVrFlingerRequestsDisplay = false;
1464 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001465 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001466
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001467 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001468
Steven Thomas0123ac62018-07-12 11:32:34 -07001469 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001470 LOG_ALWAYS_FATAL_IF(!display);
1471 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001472 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1473 // called below. Clear the reference now so we don't accidentally use it
1474 // later.
1475 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001476
Steven Thomasb02664d2017-07-26 18:48:28 -07001477 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001478 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001479 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001480
Steven Thomasb02664d2017-07-26 18:48:28 -07001481 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001482 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001483 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1484 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001485 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001486
David Sodman105b7dc2017-11-04 20:28:14 -07001487 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1488 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001489
1490 if (vrFlingerRequestsDisplay) {
1491 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001492 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001493
1494 mVisibleRegionsDirty = true;
1495 invalidateHwcGeometry();
1496
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001497 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001498 display = getDefaultDisplayDeviceLocked();
1499 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001500 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001501
Steven Thomasb02664d2017-07-26 18:48:28 -07001502 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001503 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001504 const nsecs_t period = activeConfig->getVsyncPeriod();
1505 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001506
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001507 // The present fences returned from vr_hwc are not an accurate
1508 // representation of vsync times.
1509 mPrimaryDispSync.setIgnorePresentFences(
1510 getBE().mHwc->isUsingVrComposer() || !hasSyncFramework);
1511
Steven Thomasb02664d2017-07-26 18:48:28 -07001512 // Use phase of 0 since phase is not known.
1513 // Use latency of 0, which will snap to the ideal latency.
1514 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001515
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001516 resyncToHardwareVsync(false);
1517
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001518 android_atomic_or(1, &mRepaintEverything);
1519 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001520}
1521
Mathias Agopian4fec8732012-06-29 14:12:52 -07001522void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001523 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001524 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001525 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001526 bool frameMissed = !mHadClientComposition &&
1527 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001528 (mPreviousPresentFence->getSignalTime() ==
1529 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001530 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001531 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001532 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001533 mTimeStats.incrementMissedFrames();
1534 if (mPropagateBackpressure) {
1535 signalLayerUpdate();
1536 break;
1537 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001538 }
Dan Stoza50182882016-07-08 12:02:20 -07001539
Steven Thomas050b2c82017-03-06 11:45:16 -08001540 // Now that we're going to make it to the handleMessageTransaction()
1541 // call below it's safe to call updateVrFlinger(), which will
1542 // potentially trigger a display handoff.
1543 updateVrFlinger();
1544
Dan Stoza6b9454d2014-11-07 16:00:59 -08001545 bool refreshNeeded = handleMessageTransaction();
1546 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001547 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001548 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001549 // Signal a refresh if a transaction modified the window state,
1550 // a new buffer was latched, or if HWC has requested a full
1551 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001552 signalRefresh();
1553 }
1554 break;
1555 }
1556 case MessageQueue::REFRESH: {
1557 handleMessageRefresh();
1558 break;
1559 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001560 }
1561}
1562
Dan Stoza6b9454d2014-11-07 16:00:59 -08001563bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001564 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001565 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001566 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001567 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001568 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001569 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001570}
1571
Dan Stoza6b9454d2014-11-07 16:00:59 -08001572bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001573 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001574 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001575}
1576
1577void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001578 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001579
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001580 mRefreshPending = false;
1581
Lloyd Pique074e8122018-07-26 12:57:23 -07001582 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1583
1584 preComposition(refreshStartTime);
1585 rebuildLayerStacks();
1586 setUpHWComposer();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001587 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001588 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001589 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001590 doComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001591 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001592
Dan Stozabfbffeb2016-07-21 14:49:33 -07001593 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001594 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001595 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001596 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001597 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001598 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001599
Dan Stoza9e56aa02015-11-02 13:00:03 -08001600 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001601}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001602
Mathias Agopiancd60f992012-08-16 16:28:27 -07001603void SurfaceFlinger::doDebugFlashRegions()
1604{
1605 // is debugging enabled
1606 if (CC_LIKELY(!mDebugRegion))
1607 return;
1608
1609 const bool repaintEverything = mRepaintEverything;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001610 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001611 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001612 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001613 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001614 if (!dirtyRegion.isEmpty()) {
1615 // redraw the whole screen
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001616 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001617
1618 // and draw the dirty region
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001619 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001620 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001621 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1622
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001623 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001624 }
1625 }
1626 }
1627
1628 postFramebuffer();
1629
1630 if (mDebugRegion > 1) {
1631 usleep(mDebugRegion * 1000);
1632 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001633
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001634 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001635 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001636 continue;
1637 }
1638
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001639 status_t result = display->prepareFrame(*getBE().mHwc);
1640 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001641 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001642 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001643}
1644
Adrian Roos1e1a1282017-11-01 19:05:31 +01001645void SurfaceFlinger::doTracing(const char* where) {
1646 ATRACE_CALL();
1647 ATRACE_NAME(where);
1648 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001649 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001650 }
1651}
1652
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001653void SurfaceFlinger::logLayerStats() {
1654 ATRACE_CALL();
1655 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001656 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001657 if (display->isPrimary()) {
1658 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001659 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001660 }
1661 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001662
1663 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001664 }
1665}
1666
Lloyd Pique074e8122018-07-26 12:57:23 -07001667void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001668{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001669 ATRACE_CALL();
1670 ALOGV("preComposition");
1671
Mathias Agopiancd60f992012-08-16 16:28:27 -07001672 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001673 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique074e8122018-07-26 12:57:23 -07001674 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001675 needExtraInvalidate = true;
1676 }
Robert Carr2047fae2016-11-28 14:09:09 -08001677 });
1678
Mathias Agopiancd60f992012-08-16 16:28:27 -07001679 if (needExtraInvalidate) {
1680 signalLayerUpdate();
1681 }
1682}
1683
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001684void SurfaceFlinger::updateCompositorTiming(
1685 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1686 std::shared_ptr<FenceTime>& presentFenceTime) {
1687 // Update queue of past composite+present times and determine the
1688 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001689 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001690 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001691 while (!getBE().mCompositePresentTimes.empty()) {
1692 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001693 // Cached values should have been updated before calling this method,
1694 // which helps avoid duplicate syscalls.
1695 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1696 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1697 break;
1698 }
1699 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001700 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001701 }
1702
1703 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001704 while (getBE().mCompositePresentTimes.size() > 16) {
1705 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001706 }
1707
Brian Andersond0010582017-03-07 13:20:31 -08001708 setCompositorTimingSnapped(
1709 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1710}
1711
1712void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1713 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001714 // Integer division and modulo round toward 0 not -inf, so we need to
1715 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001716 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001717 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1718 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1719
Brian Andersond0010582017-03-07 13:20:31 -08001720 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1721 if (idealLatency <= 0) {
1722 idealLatency = vsyncInterval;
1723 }
1724
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001725 // Snap the latency to a value that removes scheduling jitter from the
1726 // composition and present times, which often have >1ms of jitter.
1727 // Reducing jitter is important if an app attempts to extrapolate
1728 // something (such as user input) to an accurate diasplay time.
1729 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1730 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001731 nsecs_t bias = vsyncInterval / 2;
1732 int64_t extraVsyncs =
1733 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1734 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1735 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001736
David Sodman99974d22017-11-28 12:04:33 -08001737 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1738 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1739 getBE().mCompositorTiming.interval = vsyncInterval;
1740 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001741}
1742
Lloyd Pique074e8122018-07-26 12:57:23 -07001743void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001744{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001745 ATRACE_CALL();
1746 ALOGV("postComposition");
1747
Brian Anderson3546a3f2016-07-14 11:51:14 -07001748 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001749 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001750 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001751 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001752 }
1753
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001754 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001755 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001756
David Sodman73beded2017-11-15 11:56:06 -08001757 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001758 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001759 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001760 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001761 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001762 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001763 } else {
1764 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1765 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001766
David Sodman73beded2017-11-15 11:56:06 -08001767 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001768 mPreviousPresentFence =
1769 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1770 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001771 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001772
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001773 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1774 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1775
Lloyd Pique074e8122018-07-26 12:57:23 -07001776 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001777 // when we started doing work for this frame, but that should be okay
1778 // since updateCompositorTiming has snapping logic.
1779 updateCompositorTiming(
Lloyd Pique074e8122018-07-26 12:57:23 -07001780 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001781 CompositorTiming compositorTiming;
1782 {
David Sodman99974d22017-11-28 12:04:33 -08001783 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1784 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001785 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001786
Robert Carr2047fae2016-11-28 14:09:09 -08001787 mDrawingState.traverseInZOrder([&](Layer* layer) {
1788 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001789 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001790 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001791 recordBufferingStats(layer->getName().string(),
1792 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001793 }
Robert Carr2047fae2016-11-28 14:09:09 -08001794 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001795
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001796 if (presentFenceTime->isValid()) {
1797 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001798 enableHardwareVsync();
1799 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001800 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001801 }
1802 }
1803
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001804 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001805 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001806 enableHardwareVsync();
1807 }
1808 }
1809
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001810 if (mAnimCompositionPending) {
1811 mAnimCompositionPending = false;
1812
Brian Anderson4e606e32017-03-16 15:34:57 -07001813 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001814 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001815 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001816 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001817 // The HWC doesn't support present fences, so use the refresh
1818 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001819 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001820 mAnimFrameTracker.setActualPresentTime(presentTime);
1821 }
1822 mAnimFrameTracker.advanceFrame();
1823 }
Dan Stozab90cf072015-03-05 11:05:59 -08001824
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001825 mTimeStats.incrementTotalFrames();
1826 if (mHadClientComposition) {
1827 mTimeStats.incrementClientCompositionFrames();
1828 }
1829
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001830 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001831 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001832 return;
1833 }
1834
1835 nsecs_t currentTime = systemTime();
1836 if (mHasPoweredOff) {
1837 mHasPoweredOff = false;
1838 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001839 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001840 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001841 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1842 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001843 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001844 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001845 }
David Sodman4a36e932017-11-07 14:29:47 -08001846 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001847 }
David Sodman4a36e932017-11-07 14:29:47 -08001848 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001849
1850 {
1851 std::lock_guard lock(mTexturePoolMutex);
1852 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1853 if (refillCount > 0) {
1854 const size_t offset = mTexturePool.size();
1855 mTexturePool.resize(mTexturePoolSize);
1856 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1857 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1858 }
1859 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001860}
1861
1862void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001863 ATRACE_CALL();
1864 ALOGV("rebuildLayerStacks");
1865
Mathias Agopiancd60f992012-08-16 16:28:27 -07001866 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001867 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001868 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001869 mVisibleRegionsDirty = false;
1870 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001871
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001872 for (const auto& pair : mDisplays) {
1873 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001874 Region opaqueRegion;
1875 Region dirtyRegion;
1876 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001877 Vector<sp<Layer>> layersNeedingFences;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001878 const Transform& tr = display->getTransform();
1879 const Rect bounds = display->getBounds();
1880 if (display->isPoweredOn()) {
1881 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001882
Jeff Sharkey76488112017-02-27 14:15:18 -07001883 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001884 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001885 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001886 Region drawRegion(tr.transform(
1887 layer->visibleNonTransparentRegion));
1888 drawRegion.andSelf(bounds);
1889 if (!drawRegion.isEmpty()) {
1890 layersSortedByZ.add(layer);
1891 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001892 // Clear out the HWC layer if this layer was
1893 // previously visible, but no longer is
1894 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001895 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001896 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001897 // WM changes display->layerStack upon sleep/awake.
1898 // Here we make sure we delete the HWC layers even if
1899 // WM changed their layer stack.
1900 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001901 }
1902
1903 // If a layer is not going to get a release fence because
1904 // it is invisible, but it is also going to release its
1905 // old buffer, add it to the list of layers needing
1906 // fences.
1907 if (hwcLayerDestroyed) {
1908 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1909 mLayersWithQueuedFrames.cend(), layer);
1910 if (found != mLayersWithQueuedFrames.cend()) {
1911 layersNeedingFences.add(layer);
1912 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001913 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001914 });
1915 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001916 display->setVisibleLayersSortedByZ(layersSortedByZ);
1917 display->setLayersNeedingFences(layersNeedingFences);
1918 display->undefinedRegion.set(bounds);
1919 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1920 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001921 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001922 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001923}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001924
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001925// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001926// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001927// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001928// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001929// The returned HDR data space is one of
1930// - Dataspace::UNKNOWN
1931// - Dataspace::BT2020_HLG
1932// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001933Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1934 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001935 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001936 *outHdrDataSpace = Dataspace::UNKNOWN;
1937
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001938 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001939 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001940 case Dataspace::V0_SCRGB:
1941 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001942 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001943 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001944 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001945 case Dataspace::BT2020_PQ:
1946 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001947 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001948 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001949 case Dataspace::BT2020_HLG:
1950 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001951 // When there's mixed PQ content and HLG content, we set the HDR
1952 // data space to be BT2020_PQ and convert HLG to PQ.
1953 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1954 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001955 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001956 break;
1957 default:
1958 break;
1959 }
Romain Guy54f154a2017-10-24 21:40:32 +01001960 }
1961
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001962 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001963}
1964
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001965// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001966void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1967 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001968 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1969 *outMode = ColorMode::NATIVE;
1970 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001971 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001972 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001973 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001974
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001975 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001976 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001977
Peiyong Lindfde5112018-06-05 10:58:41 -07001978 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001979 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001980 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001981 if (isHdr) {
1982 bestDataSpace = hdrDataSpace;
1983 }
1984
Chia-I Wu0d711262018-05-21 15:19:35 -07001985 RenderIntent intent;
1986 switch (mDisplayColorSetting) {
1987 case DisplayColorSetting::MANAGED:
1988 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001989 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001990 break;
1991 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001992 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001993 break;
1994 default: // vendor display color setting
1995 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1996 break;
1997 }
Chia-I Wube02ec02018-05-18 10:59:36 -07001998
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001999 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002000}
2001
Lloyd Pique074e8122018-07-26 12:57:23 -07002002void SurfaceFlinger::setUpHWComposer() {
2003 ATRACE_CALL();
2004 ALOGV("setUpHWComposer");
Lloyd Piqueb7d12302018-07-26 12:56:47 -07002005
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002006 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002007 bool dirty = !display->getDirtyRegion(mRepaintEverything).isEmpty();
2008 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2009 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
Jesse Hallb7a05492014-08-14 15:45:06 -07002010
2011 // If nothing has changed (!dirty), don't recompose.
2012 // If something changed, but we don't currently have any visible layers,
2013 // and didn't when we last did a composition, then skip it this time.
2014 // The second rule does two things:
2015 // - When all layers are removed from a display, we'll emit one black
2016 // frame, then nothing more until we get new layers.
2017 // - When a display is created with a private layer stack, we won't
2018 // emit any black frames until a layer is added to the layer stack.
2019 bool mustRecompose = dirty && !(empty && wasEmpty);
2020
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002021 ALOGV_IF(display->isVirtual(), "Display %d: %s composition (%sdirty %sempty %swasEmpty)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002022 display->getId(), mustRecompose ? "doing" : "skipping", dirty ? "+" : "-",
2023 empty ? "+" : "-", wasEmpty ? "+" : "-");
Jesse Hallb7a05492014-08-14 15:45:06 -07002024
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002025 display->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07002026
2027 if (mustRecompose) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002028 display->lastCompositionHadVisibleLayers = !empty;
Jesse Hallb7a05492014-08-14 15:45:06 -07002029 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07002030 }
2031
Lloyd Pique074e8122018-07-26 12:57:23 -07002032 // build the h/w work list
2033 if (CC_UNLIKELY(mGeometryInvalid)) {
2034 mGeometryInvalid = false;
2035 for (const auto& [token, display] : mDisplays) {
2036 const auto displayId = display->getId();
2037 if (displayId >= 0) {
2038 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
2039 for (size_t i = 0; i < currentLayers.size(); i++) {
2040 const auto& layer = currentLayers[i];
2041 if (!layer->hasHwcLayer(displayId)) {
2042 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
2043 layer->forceClientComposition(displayId);
2044 continue;
2045 }
2046 }
2047
2048 layer->setGeometry(display, i);
2049 if (mDebugDisableHWC || mDebugRegion) {
2050 layer->forceClientComposition(displayId);
2051 }
2052 }
2053 }
2054 }
2055 }
2056
2057 // Set the per-frame data
2058 for (const auto& [token, display] : mDisplays) {
2059 const auto displayId = display->getId();
2060 if (displayId < 0) {
2061 continue;
2062 }
2063
2064 if (mDrawingState.colorMatrixChanged) {
2065 display->setColorTransform(mDrawingState.colorMatrix);
2066 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
2067 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %d: %d",
2068 displayId, result);
2069 }
2070 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2071 if (layer->isHdrY410()) {
2072 layer->forceClientComposition(displayId);
2073 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2074 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
2075 !display->hasHDR10Support()) {
2076 layer->forceClientComposition(displayId);
2077 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2078 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
2079 !display->hasHLGSupport()) {
2080 layer->forceClientComposition(displayId);
2081 }
2082
2083 if (layer->getForceClientComposition(displayId)) {
2084 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2085 layer->setCompositionType(displayId, HWC2::Composition::Client);
2086 continue;
2087 }
2088
2089 layer->setPerFrameData(display);
2090 }
2091
2092 if (hasWideColorDisplay) {
2093 ColorMode colorMode;
2094 Dataspace dataSpace;
2095 RenderIntent renderIntent;
2096 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
2097 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
2098 }
2099 }
2100
2101 mDrawingState.colorMatrixChanged = false;
2102
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002103 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002104 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002105 continue;
2106 }
2107
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002108 status_t result = display->prepareFrame(*getBE().mHwc);
2109 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002110 display->getId(), result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002111 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002112}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002113
Mathias Agopiancd60f992012-08-16 16:28:27 -07002114void SurfaceFlinger::doComposition() {
2115 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002116 ALOGV("doComposition");
2117
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002118 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002119 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002120 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002121 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002122 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002123
2124 // repaint the framebuffer (if needed)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002125 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002126
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002127 display->dirtyRegion.clear();
2128 display->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002129 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002130 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002131 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002132}
2133
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002134void SurfaceFlinger::postFramebuffer()
2135{
Mathias Agopian841cde52012-03-01 15:44:37 -08002136 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002137 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002138
Mathias Agopiana44b0412011-10-16 18:46:35 -07002139 const nsecs_t now = systemTime();
2140 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002141
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002142 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002143 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002144 continue;
2145 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07002146 const auto displayId = display->getId();
2147 if (displayId >= 0) {
2148 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002149 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002150 display->onSwapBuffersCompleted();
2151 display->makeCurrent();
2152 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002153 sp<Fence> releaseFence = Fence::NO_FENCE;
2154
Chia-I Wu7b549592017-11-15 09:14:57 -08002155 // The layer buffer from the previous frame (if any) is released
2156 // by HWC only when the release fence from this frame (if any) is
2157 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002158 auto hwcLayer = layer->getHwcLayer(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002159 if (displayId >= 0) {
2160 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
2161 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002162
2163 // If the layer was client composited in the previous frame, we
2164 // need to merge with the previous client target acquire fence.
2165 // Since we do not track that, always merge with the current
2166 // client target acquire fence when it is available, even though
2167 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002168 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002169 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002170 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002171 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002172
David Sodmanb8af7922017-12-21 15:17:55 -08002173 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002174 }
Chia-I Wu83806892017-11-16 10:50:20 -08002175
2176 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002177 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002178 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002179 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002180 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002181 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002182 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002183 }
2184 }
2185
Dominik Laskowski7e045462018-05-30 13:02:02 -07002186 if (displayId >= 0) {
2187 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002188 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002189 }
2190
Mathias Agopiana44b0412011-10-16 18:46:35 -07002191 mLastSwapBufferTime = systemTime() - now;
2192 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002193
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002194 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002195 const auto display = getDefaultDisplayDeviceLocked();
2196 if (display && getHwComposer().isConnected(display->getId())) {
2197 const uint32_t flipCount = display->getPageFlipCount();
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002198 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2199 logFrameStats();
2200 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002201 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002202}
2203
Mathias Agopian87baae12012-07-31 12:38:26 -07002204void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002205{
Mathias Agopian841cde52012-03-01 15:44:37 -08002206 ATRACE_CALL();
2207
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002208 // here we keep a copy of the drawing state (that is the state that's
2209 // going to be overwritten by handleTransactionLocked()) outside of
2210 // mStateLock so that the side-effects of the State assignment
2211 // don't happen with mStateLock held (which can cause deadlocks).
2212 State drawingState(mDrawingState);
2213
Mathias Agopianca4d3602011-05-19 15:38:14 -07002214 Mutex::Autolock _l(mStateLock);
2215 const nsecs_t now = systemTime();
2216 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002217
Mathias Agopianca4d3602011-05-19 15:38:14 -07002218 // Here we're guaranteed that some transaction flags are set
2219 // so we can call handleTransactionLocked() unconditionally.
2220 // We call getTransactionFlags(), which will also clear the flags,
2221 // with mStateLock held to guarantee that mCurrentState won't change
2222 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002223
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002224 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002225 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002226 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002227
Mathias Agopianca4d3602011-05-19 15:38:14 -07002228 mLastTransactionTime = systemTime() - now;
2229 mDebugInTransaction = 0;
2230 invalidateHwcGeometry();
2231 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002232}
2233
Dominik Laskowski7e045462018-05-30 13:02:02 -07002234DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002235 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002236 // Figure out whether the event is for the primary display or an
2237 // external display by matching the Hwc display id against one for a
2238 // connected display. If we did not find a match, we then check what
2239 // displays are not already connected to determine the type. If we don't
2240 // have a connected primary display, we assume the new display is meant to
2241 // be the primary display, and then if we don't have an external display,
2242 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002243 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2244 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002245 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002246 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002247 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002248 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002249 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002250 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002251 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002252 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002253 return DisplayDevice::DISPLAY_EXTERNAL;
2254 }
2255
2256 return DisplayDevice::DISPLAY_ID_INVALID;
2257}
2258
Lloyd Piqueba04e622017-12-14 17:11:26 -08002259void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2260 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002261 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002262 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002263 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002264 continue;
2265 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002266
2267 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2268 ALOGE("External displays are not supported by the vr hardware composer.");
2269 continue;
2270 }
2271
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002272 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002273 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002274 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002275 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002276 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002277
2278 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002279 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002280 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002281 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002282 DisplayDeviceState info;
2283 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002284 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2285 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002286 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002287 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002288 mInterceptor->saveDisplayCreation(info);
2289 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002290 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002291 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002292
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002293 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002294 if (idx >= 0) {
2295 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002296 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002297 mCurrentState.displays.removeItemsAt(idx);
2298 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002299 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002300 }
2301
2302 processDisplayChangesLocked();
2303 }
2304
2305 mPendingHotplugEvents.clear();
2306}
2307
Lloyd Pique99d3da52018-01-22 17:48:03 -08002308sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002309 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002310 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002311 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002312 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002313 HdrCapabilities hdrCapabilities;
2314 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002315
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002316 if (hasWideColorDisplay && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002317 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002318 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002319 if (isWideColorMode(colorMode)) {
2320 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002321 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002322
Dominik Laskowski7e045462018-05-30 13:02:02 -07002323 std::vector<RenderIntent> renderIntents =
2324 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002325 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002326 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002327
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002328 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2329 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2330 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002331
2332 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2333 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2334
2335 /*
2336 * Create our display's surface
2337 */
2338 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2339 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002340 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002341 renderSurface->setNativeWindow(nativeWindow.get());
2342 const int displayWidth = renderSurface->queryWidth();
2343 const int displayHeight = renderSurface->queryHeight();
2344
2345 // Make sure that composition can never be stalled by a virtual display
2346 // consumer that isn't processing buffers fast enough. We have to do this
2347 // in two places:
2348 // * Here, in case the display is composed entirely by HWC.
2349 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2350 // window's swap interval in eglMakeCurrent, so they'll override the
2351 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002352 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002353 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2354 }
2355
2356 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002357 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002358
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002359 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002360 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2361 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2362 displayHeight, hasWideColorGamut, hdrCapabilities,
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002363 supportedPerFrameMetadata, hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002364
2365 if (maxFrameBufferAcquiredBuffers >= 3) {
2366 nativeWindowSurface->preallocateBuffers();
2367 }
2368
2369 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002370 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2371 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002372 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002373 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002374 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002375 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002376 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002377 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002378 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002379 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002380 display->setLayerStack(state.layerStack);
2381 display->setProjection(state.orientation, state.viewport, state.frame);
2382 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002383
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002384 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002385}
2386
Lloyd Pique347200f2017-12-14 17:00:15 -08002387void SurfaceFlinger::processDisplayChangesLocked() {
2388 // here we take advantage of Vector's copy-on-write semantics to
2389 // improve performance by skipping the transaction entirely when
2390 // know that the lists are identical
2391 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2392 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2393 if (!curr.isIdenticalTo(draw)) {
2394 mVisibleRegionsDirty = true;
2395 const size_t cc = curr.size();
2396 size_t dc = draw.size();
2397
2398 // find the displays that were removed
2399 // (ie: in drawing state but not in current state)
2400 // also handle displays that changed
2401 // (ie: displays that are in both lists)
2402 for (size_t i = 0; i < dc;) {
2403 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2404 if (j < 0) {
2405 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002406 // Call makeCurrent() on the primary display so we can
2407 // be sure that nothing associated with this display
2408 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002409 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2410 defaultDisplay->makeCurrent();
2411 }
2412 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2413 display->disconnect(getHwComposer());
2414 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002415 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2416 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2417 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2418 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2419 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002420 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002421 } else {
2422 // this display is in both lists. see if something changed.
2423 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002424 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002425 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2426 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2427 if (state_binder != draw_binder) {
2428 // changing the surface is like destroying and
2429 // recreating the DisplayDevice, so we just remove it
2430 // from the drawing state, so that it get re-added
2431 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002432 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2433 display->disconnect(getHwComposer());
2434 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002435 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002436 mDrawingState.displays.removeItemsAt(i);
2437 dc--;
2438 // at this point we must loop to the next item
2439 continue;
2440 }
2441
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002442 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002443 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002444 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002445 }
2446 if ((state.orientation != draw[i].orientation) ||
2447 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002448 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002449 }
2450 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002451 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002452 }
2453 }
2454 }
2455 ++i;
2456 }
2457
2458 // find displays that were added
2459 // (ie: in current state but not in drawing state)
2460 for (size_t i = 0; i < cc; i++) {
2461 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2462 const DisplayDeviceState& state(curr[i]);
2463
2464 sp<DisplaySurface> dispSurface;
2465 sp<IGraphicBufferProducer> producer;
2466 sp<IGraphicBufferProducer> bqProducer;
2467 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002468 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002469
Dominik Laskowski7e045462018-05-30 13:02:02 -07002470 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002471 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002472 // Virtual displays without a surface are dormant:
2473 // they have external state (layer stack, projection,
2474 // etc.) but no internal state (i.e. a DisplayDevice).
2475 if (state.surface != nullptr) {
2476 // Allow VR composer to use virtual displays.
2477 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2478 int width = 0;
2479 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2480 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2481 int height = 0;
2482 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2483 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2484 int intFormat = 0;
2485 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2486 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002487 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002488
Dominik Laskowski7e045462018-05-30 13:02:02 -07002489 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2490 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002491 }
2492
2493 // TODO: Plumb requested format back up to consumer
2494
2495 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002496 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002497 bqProducer, bqConsumer,
2498 state.displayName);
2499
2500 dispSurface = vds;
2501 producer = vds;
2502 }
2503 } else {
2504 ALOGE_IF(state.surface != nullptr,
2505 "adding a supported display, but rendering "
2506 "surface is provided (%p), ignoring it",
2507 state.surface.get());
2508
Dominik Laskowski7e045462018-05-30 13:02:02 -07002509 displayId = state.type;
2510 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002511 producer = bqProducer;
2512 }
2513
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002514 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002515 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002516 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002517 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002518 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002519 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002520 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2521 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2522 true);
2523 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2524 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2525 true);
2526 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002527 }
2528 }
2529 }
2530 }
2531 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002532
2533 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002534}
2535
Mathias Agopian87baae12012-07-31 12:38:26 -07002536void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002537{
Dan Stoza7dde5992015-05-22 09:51:44 -07002538 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002539 mCurrentState.traverseInZOrder([](Layer* layer) {
2540 layer->notifyAvailableFrames();
2541 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002542
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002543 /*
2544 * Traversal of the children
2545 * (perform the transaction for each of them if needed)
2546 */
2547
Mathias Agopian3559b072012-08-15 13:46:03 -07002548 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002549 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002550 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002551 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002552
2553 const uint32_t flags = layer->doTransaction(0);
2554 if (flags & Layer::eVisibleRegion)
2555 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002556 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002557 }
2558
2559 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002560 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002561 */
2562
Mathias Agopiane57f2922012-08-09 16:29:12 -07002563 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002564 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002565 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002566 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002567
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002568 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002569 // The transform hint might have changed for some layers
2570 // (either because a display has changed, or because a layer
2571 // as changed).
2572 //
2573 // Walk through all the layers in currentLayers,
2574 // and update their transform hint.
2575 //
2576 // If a layer is visible only on a single display, then that
2577 // display is used to calculate the hint, otherwise we use the
2578 // default display.
2579 //
2580 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2581 // the hint is set before we acquire a buffer from the surface texture.
2582 //
2583 // NOTE: layer transactions have taken place already, so we use their
2584 // drawing state. However, SurfaceFlinger's own transaction has not
2585 // happened yet, so we must use the current state layer list
2586 // (soon to become the drawing state list).
2587 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002588 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002589 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002590 bool first = true;
2591 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002592 // NOTE: we rely on the fact that layers are sorted by
2593 // layerStack first (so we don't have to traverse the list
2594 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002595 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002596 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002597 currentlayerStack = layerStack;
2598 // figure out if this layerstack is mirrored
2599 // (more than one display) if so, pick the default display,
2600 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002601 hintDisplay = nullptr;
2602 for (const auto& [token, display] : mDisplays) {
2603 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2604 if (hintDisplay) {
2605 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002606 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002607 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002608 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002609 }
2610 }
2611 }
2612 }
Chet Haase91d25932013-04-11 15:24:55 -07002613
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002614 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002615 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2616 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002617
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002618 // could be null when this layer is using a layerStack
2619 // that is not visible on any display. Also can occur at
2620 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002621 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002622 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002623
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002624 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002625 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002626 if (hintDisplay) {
2627 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002628 }
Robert Carr2047fae2016-11-28 14:09:09 -08002629
2630 first = false;
2631 });
Mathias Agopian84300952012-11-21 16:02:13 -08002632 }
2633
2634
Mathias Agopian3559b072012-08-15 13:46:03 -07002635 /*
2636 * Perform our own transaction if needed
2637 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002638
2639 if (mLayersAdded) {
2640 mLayersAdded = false;
2641 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002642 mVisibleRegionsDirty = true;
2643 }
2644
2645 // some layers might have been removed, so
2646 // we need to update the regions they're exposing.
2647 if (mLayersRemoved) {
2648 mLayersRemoved = false;
2649 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002650 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002651 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002652 // this layer is not visible anymore
2653 // TODO: we could traverse the tree from front to back and
2654 // compute the actual visible region
2655 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002656 Region visibleReg;
2657 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002658 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002659 }
Robert Carr2047fae2016-11-28 14:09:09 -08002660 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002661 }
2662
2663 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002664
2665 updateCursorAsync();
2666}
2667
2668void SurfaceFlinger::updateCursorAsync()
2669{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002670 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002671 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002672 continue;
2673 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002674
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002675 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2676 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002677 }
2678 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002679}
2680
2681void SurfaceFlinger::commitTransaction()
2682{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002683 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002684 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002685 for (const auto& l : mLayersPendingRemoval) {
2686 recordBufferingStats(l->getName().string(),
2687 l->getOccupancyHistory(true));
2688 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002689 }
2690 mLayersPendingRemoval.clear();
2691 }
2692
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002693 // If this transaction is part of a window animation then the next frame
2694 // we composite should be considered an animation as well.
2695 mAnimCompositionPending = mAnimTransactionPending;
2696
Mathias Agopian4fec8732012-06-29 14:12:52 -07002697 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002698 // clear the "changed" flags in current state
2699 mCurrentState.colorMatrixChanged = false;
2700
Robert Carr1f0a16a2016-10-24 16:27:39 -07002701 mDrawingState.traverseInZOrder([](Layer* layer) {
2702 layer->commitChildList();
2703 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002704 mTransactionPending = false;
2705 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002706 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002707}
2708
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002709void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2710 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002711 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002712 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002713
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002714 Region aboveOpaqueLayers;
2715 Region aboveCoveredLayers;
2716 Region dirty;
2717
Mathias Agopian87baae12012-07-31 12:38:26 -07002718 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002719
Robert Carr2047fae2016-11-28 14:09:09 -08002720 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002721 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002722 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002723
Jesse Hall01e29052013-02-19 16:13:35 -08002724 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002725 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002726 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002727 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002728
Mathias Agopianab028732010-03-16 16:41:46 -07002729 /*
2730 * opaqueRegion: area of a surface that is fully opaque.
2731 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002732 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002733
2734 /*
2735 * visibleRegion: area of a surface that is visible on screen
2736 * and not fully transparent. This is essentially the layer's
2737 * footprint minus the opaque regions above it.
2738 * Areas covered by a translucent surface are considered visible.
2739 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002740 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002741
2742 /*
2743 * coveredRegion: area of a surface that is covered by all
2744 * visible regions above it (which includes the translucent areas).
2745 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002746 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002747
Jesse Halla8026d22012-09-25 13:25:04 -07002748 /*
2749 * transparentRegion: area of a surface that is hinted to be completely
2750 * transparent. This is only used to tell when the layer has no visible
2751 * non-transparent regions and can be removed from the layer list. It
2752 * does not affect the visibleRegion of this layer or any layers
2753 * beneath it. The hint may not be correct if apps don't respect the
2754 * SurfaceView restrictions (which, sadly, some don't).
2755 */
2756 Region transparentRegion;
2757
Mathias Agopianab028732010-03-16 16:41:46 -07002758
2759 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002760 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002761 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002762 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002763 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002764 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002765 if (!visibleRegion.isEmpty()) {
2766 // Remove the transparent area from the visible region
2767 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002768 if (tr.preserveRects()) {
2769 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002770 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002771 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002772 // transformation too complex, can't do the
2773 // transparent region optimization.
2774 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002775 }
Mathias Agopianab028732010-03-16 16:41:46 -07002776 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002777
Mathias Agopianab028732010-03-16 16:41:46 -07002778 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002779 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002780 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002781 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2782 // the opaque region is the layer's footprint
2783 opaqueRegion = visibleRegion;
2784 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002785 }
2786 }
2787
Robert Carre5f4f692018-01-12 13:12:28 -08002788 if (visibleRegion.isEmpty()) {
2789 layer->clearVisibilityRegions();
2790 return;
2791 }
2792
Mathias Agopianab028732010-03-16 16:41:46 -07002793 // Clip the covered region to the visible region
2794 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2795
2796 // Update aboveCoveredLayers for next (lower) layer
2797 aboveCoveredLayers.orSelf(visibleRegion);
2798
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002799 // subtract the opaque region covered by the layers above us
2800 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002801
2802 // compute this layer's dirty region
2803 if (layer->contentDirty) {
2804 // we need to invalidate the whole region
2805 dirty = visibleRegion;
2806 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002807 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002808 layer->contentDirty = false;
2809 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002810 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002811 * the exposed region consists of two components:
2812 * 1) what's VISIBLE now and was COVERED before
2813 * 2) what's EXPOSED now less what was EXPOSED before
2814 *
2815 * note that (1) is conservative, we start with the whole
2816 * visible region but only keep what used to be covered by
2817 * something -- which mean it may have been exposed.
2818 *
2819 * (2) handles areas that were not covered by anything but got
2820 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002821 */
Mathias Agopianab028732010-03-16 16:41:46 -07002822 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002823 const Region oldVisibleRegion = layer->visibleRegion;
2824 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002825 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2826 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002827 }
2828 dirty.subtractSelf(aboveOpaqueLayers);
2829
2830 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002831 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002832
Mathias Agopianab028732010-03-16 16:41:46 -07002833 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002834 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002835
Jesse Halla8026d22012-09-25 13:25:04 -07002836 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002837 layer->setVisibleRegion(visibleRegion);
2838 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002839 layer->setVisibleNonTransparentRegion(
2840 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002841 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002842
Mathias Agopian87baae12012-07-31 12:38:26 -07002843 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002844}
2845
Chia-I Wuab0c3192017-08-01 11:29:00 -07002846void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002847 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002848 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2849 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002850 }
2851 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002852}
2853
Dan Stoza6b9454d2014-11-07 16:00:59 -08002854bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002855{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002856 ALOGV("handlePageFlip");
2857
Brian Andersond6927fb2016-07-23 23:37:30 -07002858 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002859
Mathias Agopian4fec8732012-06-29 14:12:52 -07002860 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002861 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002862 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002863
2864 // Store the set of layers that need updates. This set must not change as
2865 // buffers are being latched, as this could result in a deadlock.
2866 // Example: Two producers share the same command stream and:
2867 // 1.) Layer 0 is latched
2868 // 2.) Layer 0 gets a new frame
2869 // 2.) Layer 1 gets a new frame
2870 // 3.) Layer 1 is latched.
2871 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2872 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002873 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002874 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002875 frameQueued = true;
2876 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002877 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002878 } else {
2879 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002880 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002881 } else {
2882 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002883 }
Robert Carr2047fae2016-11-28 14:09:09 -08002884 });
2885
Dan Stoza9e56aa02015-11-02 13:00:03 -08002886 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002887 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002888 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002889 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002890 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002891 newDataLatched = true;
2892 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002893 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002894
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002895 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002896
2897 // If we will need to wake up at some time in the future to deal with a
2898 // queued frame that shouldn't be displayed during this vsync period, wake
2899 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002900 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002901 signalLayerUpdate();
2902 }
2903
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002904 // enter boot animation on first buffer latch
2905 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2906 ALOGI("Enter boot animation");
2907 mBootStage = BootStage::BOOTANIMATION;
2908 }
2909
Dan Stoza6b9454d2014-11-07 16:00:59 -08002910 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002911 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002912}
2913
Mathias Agopianad456f92011-01-13 17:53:01 -08002914void SurfaceFlinger::invalidateHwcGeometry()
2915{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002916 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002917}
2918
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002919void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2920 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002921 // We only need to actually compose the display if:
2922 // 1) It is being handled by hardware composer, which may need this to
2923 // keep its virtual display state machine in sync, or
2924 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002925 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002926 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002927 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002928 return;
2929 }
2930
Dan Stoza9e56aa02015-11-02 13:00:03 -08002931 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002932 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002933
2934 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002935 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002936}
2937
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002938bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002939 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002940
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002941 const Region bounds(display->bounds());
2942 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002943 const auto displayId = display->getId();
2944 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002945 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002946
Chia-I Wu8e50e692018-05-04 10:12:37 -07002947 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002948 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002949
Dan Stoza9e56aa02015-11-02 13:00:03 -08002950 if (hasClientComposition) {
2951 ALOGV("hasClientComposition");
2952
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002953 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002954 if (display->hasWideColorGamut()) {
2955 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002956 }
2957 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002958 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002959 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002960
Dominik Laskowski7e045462018-05-30 13:02:02 -07002961 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002962 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2963 HWC2::Capability::SkipClientColorTransform);
2964
Chia-I Wud49d6692018-06-27 07:17:41 +08002965 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002966 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2967 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08002968 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002969 }
2970
Chia-I Wud49d6692018-06-27 07:17:41 +08002971 // The current enhanced saturation matrix is designed to enhance Display P3,
2972 // thus we only apply this matrix when the render intent is not colorimetric
2973 // and the output color space is Display P3.
2974 needsEnhancedColorMatrix =
2975 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2976 outputDataspace == Dataspace::DISPLAY_P3);
2977 if (needsEnhancedColorMatrix) {
2978 colorMatrix *= mEnhancedSaturationMatrix;
2979 }
2980
2981 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002982
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002983 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002984 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002985 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002986 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002987
2988 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002989 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
2990 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
2991 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07002992 }
2993 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002994 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002995
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002996 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002997 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002998 // when using overlays, we assume a fully transparent framebuffer
2999 // NOTE: we could reduce how much we need to clear, for instance
3000 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003001 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003002 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003003 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003004 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003005 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003006 // we're left with the letterbox region
3007 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003008 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003009
3010 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003011 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003012
Mathias Agopianb9494d52012-04-18 02:28:45 -07003013 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003014 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003015 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003016 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003017 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003018 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003019
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003020 if (!display->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07003021 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07003022 // scissor on the main display. It should never be needed
3023 // anyways (though in theory it could since the API allows it).
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003024 const Rect& bounds = display->getBounds();
3025 const Rect& scissor = display->getScissor();
Mathias Agopianf45c5102012-10-24 16:29:17 -07003026 if (scissor != bounds) {
3027 // scissor doesn't match the screen's dimensions, so we
3028 // need to clear everything outside of it and enable
3029 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003030
Mathias Agopianf45c5102012-10-24 16:29:17 -07003031 // enable scissor for this frame
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003032 const uint32_t height = display->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08003033 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07003034 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003035 }
3036 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003037 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003038
Mathias Agopian85d751c2012-08-29 16:59:24 -07003039 /*
3040 * and then, render the layers targeted at the framebuffer
3041 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003042
Dan Stoza9e56aa02015-11-02 13:00:03 -08003043 ALOGV("Rendering client layers");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003044 const Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003045 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003046 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003047 const Region clip(bounds.intersect(
3048 displayTransform.transform(layer->visibleRegion)));
3049 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07003050 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003051 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003052 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003053 case HWC2::Composition::Cursor:
3054 case HWC2::Composition::Device:
3055 case HWC2::Composition::Sideband:
3056 case HWC2::Composition::SolidColor: {
3057 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07003058 if (layer->getClearClientTarget(displayId) && !firstLayer &&
Rajavenu Kyatham2eae6d32018-04-10 12:34:05 +05303059 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3060 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003061 // never clear the very first layer since we're
3062 // guaranteed the FB is already cleared
3063 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003064 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003065 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003066 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003067 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003068 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003069 break;
3070 }
3071 default:
3072 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003073 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003074 } else {
3075 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003076 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003077 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003078 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003079
Chia-I Wud49d6692018-06-27 07:17:41 +08003080 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003081 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003082 }
3083
Mathias Agopianf45c5102012-10-24 16:29:17 -07003084 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003085 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003086 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003087}
3088
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003089void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
3090 const Region& region) const {
3091 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003092 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003093 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003094}
3095
Dan Stoza7d89d062015-04-30 13:29:25 -07003096status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003097 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003098 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003099 const sp<Layer>& lbc,
3100 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003101{
Dan Stoza7d89d062015-04-30 13:29:25 -07003102 // add this layer to the current state list
3103 {
3104 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003105 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003106 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3107 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003108 return NO_MEMORY;
3109 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003110 if (parent == nullptr) {
3111 mCurrentState.layersSortedByZ.add(lbc);
3112 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003113 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003114 ALOGE("addClientLayer called with a removed parent");
3115 return NAME_NOT_FOUND;
3116 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003117 parent->addChild(lbc);
3118 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003119
Yiwei Zhang243b3782018-05-15 17:40:04 -07003120 if (gbc != nullptr) {
3121 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3122 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3123 mMaxGraphicBufferProducerListSize,
3124 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3125 mGraphicBufferProducerList.size(),
3126 mMaxGraphicBufferProducerListSize, mNumLayers);
3127 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003128 mLayersAdded = true;
3129 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003130 }
3131
Mathias Agopian96f08192010-06-02 23:28:45 -07003132 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003133 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003134
Dan Stoza7d89d062015-04-30 13:29:25 -07003135 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003136}
3137
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003138status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003139 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003140 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3141}
Robert Carr7f9b8992017-03-10 11:08:39 -08003142
chaviwca27f252018-02-06 16:46:39 -08003143status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3144 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003145 if (layer->isPendingRemoval()) {
3146 return NO_ERROR;
3147 }
3148
Robert Carr1f0a16a2016-10-24 16:27:39 -07003149 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003150 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003151 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003152 if (topLevelOnly) {
3153 return NO_ERROR;
3154 }
3155
Chia-I Wu98f1c102017-05-30 14:54:08 -07003156 sp<Layer> ancestor = p;
3157 while (ancestor->getParent() != nullptr) {
3158 ancestor = ancestor->getParent();
3159 }
3160 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3161 ALOGE("removeLayer called with a layer whose parent has been removed");
3162 return NAME_NOT_FOUND;
3163 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003164
3165 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003166 } else {
3167 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003168 }
3169
Robert Carr136e2f62017-02-08 17:54:29 -08003170 // As a matter of normal operation, the LayerCleaner will produce a second
3171 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3172 // so we will succeed in promoting it, but it's already been removed
3173 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3174 // otherwise something has gone wrong and we are leaking the layer.
3175 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003176 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3177 layer->getName().string(),
3178 (p != nullptr) ? p->getName().string() : "no-parent");
3179 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003180 } else if (index < 0) {
3181 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003182 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003183
Chia-I Wuc6657022017-08-15 11:18:17 -07003184 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003185 mLayersPendingRemoval.add(layer);
3186 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003187 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003188 setTransactionFlags(eTransactionNeeded);
3189 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003190}
3191
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003192uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003193 return android_atomic_release_load(&mTransactionFlags);
3194}
3195
Mathias Agopian3f844832013-08-07 21:24:32 -07003196uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003197 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3198}
3199
Mathias Agopian3f844832013-08-07 21:24:32 -07003200uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003201 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3202}
3203
3204uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3205 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003206 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003207 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003208 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003209 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003210 }
3211 return old;
3212}
3213
chaviwca27f252018-02-06 16:46:39 -08003214bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3215 for (const ComposerState& state : states) {
3216 // Here we need to check that the interface we're given is indeed
3217 // one of our own. A malicious client could give us a nullptr
3218 // IInterface, or one of its own or even one of our own but a
3219 // different type. All these situations would cause us to crash.
3220 if (state.client == nullptr) {
3221 return true;
3222 }
3223
3224 sp<IBinder> binder = IInterface::asBinder(state.client);
3225 if (binder == nullptr) {
3226 return true;
3227 }
3228
3229 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3230 return true;
3231 }
3232 }
3233 return false;
3234}
3235
Mathias Agopian8b33f032012-07-24 20:43:54 -07003236void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003237 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003238 const Vector<DisplayState>& displays,
3239 uint32_t flags)
3240{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003241 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003242 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003243 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003244
chaviwca27f252018-02-06 16:46:39 -08003245 if (containsAnyInvalidClientState(states)) {
3246 return;
3247 }
3248
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003249 if (flags & eAnimation) {
3250 // For window updates that are part of an animation we must wait for
3251 // previous animation "frames" to be handled.
3252 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003253 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003254 if (CC_UNLIKELY(err != NO_ERROR)) {
3255 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003256 // caller after a few seconds.
3257 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3258 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003259 mAnimTransactionPending = false;
3260 break;
3261 }
3262 }
3263 }
3264
chaviwca27f252018-02-06 16:46:39 -08003265 for (const DisplayState& display : displays) {
3266 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003267 }
3268
chaviwca27f252018-02-06 16:46:39 -08003269 for (const ComposerState& state : states) {
3270 transactionFlags |= setClientStateLocked(state);
3271 }
3272
3273 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3274 // as destroyed should only occur after setting all other states. This is to allow for a
3275 // child re-parent to happen before marking its original parent as destroyed (which would
3276 // then mark the child as destroyed).
3277 for (const ComposerState& state : states) {
3278 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003279 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003280
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003281 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3282 // anyway. This can be used as a flush mechanism for previous async transactions.
3283 // Empty animation transaction can be used to simulate back-pressure, so also force a
3284 // transaction for empty animation transactions.
3285 if (transactionFlags == 0 &&
3286 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003287 transactionFlags = eTransactionNeeded;
3288 }
3289
Mathias Agopian386aa982011-11-07 21:58:03 -08003290 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003291 if (mInterceptor->isEnabled()) {
3292 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003293 }
Irvel468051e2016-06-13 16:44:44 -07003294
Mathias Agopian386aa982011-11-07 21:58:03 -08003295 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003296 const auto start = (flags & eEarlyWakeup)
3297 ? VSyncModulator::TransactionStart::EARLY
3298 : VSyncModulator::TransactionStart::NORMAL;
3299 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003300
3301 // if this is a synchronous transaction, wait for it to take effect
3302 // before returning.
3303 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003304 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003305 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003306 if (flags & eAnimation) {
3307 mAnimTransactionPending = true;
3308 }
3309 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003310 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3311 if (CC_UNLIKELY(err != NO_ERROR)) {
3312 // just in case something goes wrong in SF, return to the
3313 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003314 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3315 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003316 break;
3317 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003318 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003319 }
3320}
3321
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003322uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3323 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3324 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003325
Mathias Agopiane57f2922012-08-09 16:29:12 -07003326 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003327 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3328
3329 const uint32_t what = s.what;
3330 if (what & DisplayState::eSurfaceChanged) {
3331 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3332 state.surface = s.surface;
3333 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003334 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003335 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003336 if (what & DisplayState::eLayerStackChanged) {
3337 if (state.layerStack != s.layerStack) {
3338 state.layerStack = s.layerStack;
3339 flags |= eDisplayTransactionNeeded;
3340 }
3341 }
3342 if (what & DisplayState::eDisplayProjectionChanged) {
3343 if (state.orientation != s.orientation) {
3344 state.orientation = s.orientation;
3345 flags |= eDisplayTransactionNeeded;
3346 }
3347 if (state.frame != s.frame) {
3348 state.frame = s.frame;
3349 flags |= eDisplayTransactionNeeded;
3350 }
3351 if (state.viewport != s.viewport) {
3352 state.viewport = s.viewport;
3353 flags |= eDisplayTransactionNeeded;
3354 }
3355 }
3356 if (what & DisplayState::eDisplaySizeChanged) {
3357 if (state.width != s.width) {
3358 state.width = s.width;
3359 flags |= eDisplayTransactionNeeded;
3360 }
3361 if (state.height != s.height) {
3362 state.height = s.height;
3363 flags |= eDisplayTransactionNeeded;
3364 }
3365 }
3366
Mathias Agopiane57f2922012-08-09 16:29:12 -07003367 return flags;
3368}
3369
Robert Carrd4ae7f32018-06-07 16:10:57 -07003370bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3371 IPCThreadState* ipc = IPCThreadState::self();
3372 const int pid = ipc->getCallingPid();
3373 const int uid = ipc->getCallingUid();
3374
3375 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3376 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3377 return false;
3378 }
3379 return true;
3380}
3381
chaviwca27f252018-02-06 16:46:39 -08003382uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3383 const layer_state_t& s = composerState.state;
3384 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3385
Mathias Agopian13127d82013-03-05 17:47:11 -08003386 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003387 if (layer == nullptr) {
3388 return 0;
3389 }
3390
3391 if (layer->isPendingRemoval()) {
3392 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3393 return 0;
3394 }
3395
3396 uint32_t flags = 0;
3397
3398 const uint32_t what = s.what;
3399 bool geometryAppliesWithResize =
3400 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003401
3402 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3403 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003404 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003405 layer->pushPendingState();
3406 }
3407
chaviw8b3871a2017-11-01 17:41:01 -07003408 if (what & layer_state_t::ePositionChanged) {
3409 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3410 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003411 }
chaviw8b3871a2017-11-01 17:41:01 -07003412 }
3413 if (what & layer_state_t::eLayerChanged) {
3414 // NOTE: index needs to be calculated before we update the state
3415 const auto& p = layer->getParent();
3416 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003417 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003418 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003419 mCurrentState.layersSortedByZ.removeAt(idx);
3420 mCurrentState.layersSortedByZ.add(layer);
3421 // we need traversal (state changed)
3422 // AND transaction (list changed)
3423 flags |= eTransactionNeeded|eTraversalNeeded;
3424 }
chaviw8b3871a2017-11-01 17:41:01 -07003425 } else {
3426 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003427 flags |= eTransactionNeeded|eTraversalNeeded;
3428 }
3429 }
chaviw8b3871a2017-11-01 17:41:01 -07003430 }
3431 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003432 // NOTE: index needs to be calculated before we update the state
3433 const auto& p = layer->getParent();
3434 if (p == nullptr) {
3435 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3436 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3437 mCurrentState.layersSortedByZ.removeAt(idx);
3438 mCurrentState.layersSortedByZ.add(layer);
3439 // we need traversal (state changed)
3440 // AND transaction (list changed)
3441 flags |= eTransactionNeeded|eTraversalNeeded;
3442 }
3443 } else {
3444 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3445 flags |= eTransactionNeeded|eTraversalNeeded;
3446 }
chaviw8b3871a2017-11-01 17:41:01 -07003447 }
3448 }
3449 if (what & layer_state_t::eSizeChanged) {
3450 if (layer->setSize(s.w, s.h)) {
3451 flags |= eTraversalNeeded;
3452 }
3453 }
3454 if (what & layer_state_t::eAlphaChanged) {
3455 if (layer->setAlpha(s.alpha))
3456 flags |= eTraversalNeeded;
3457 }
3458 if (what & layer_state_t::eColorChanged) {
3459 if (layer->setColor(s.color))
3460 flags |= eTraversalNeeded;
3461 }
3462 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003463 // TODO: b/109894387
3464 //
3465 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3466 // rotation. To see the problem observe that if we have a square parent, and a child
3467 // of the same size, then we rotate the child 45 degrees around it's center, the child
3468 // must now be cropped to a non rectangular 8 sided region.
3469 //
3470 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3471 // private API, and the WindowManager only uses rotation in one case, which is on a top
3472 // level layer in which cropping is not an issue.
3473 //
3474 // However given that abuse of rotation matrices could lead to surfaces extending outside
3475 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3476 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3477 // transformations.
3478 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003479 flags |= eTraversalNeeded;
3480 }
3481 if (what & layer_state_t::eTransparentRegionChanged) {
3482 if (layer->setTransparentRegionHint(s.transparentRegion))
3483 flags |= eTraversalNeeded;
3484 }
3485 if (what & layer_state_t::eFlagsChanged) {
3486 if (layer->setFlags(s.flags, s.mask))
3487 flags |= eTraversalNeeded;
3488 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003489 if (what & layer_state_t::eCropChanged_legacy) {
3490 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003491 flags |= eTraversalNeeded;
3492 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003493 if (what & layer_state_t::eFinalCropChanged_legacy) {
3494 if (layer->setFinalCrop_legacy(s.finalCrop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003495 flags |= eTraversalNeeded;
3496 }
3497 if (what & layer_state_t::eLayerStackChanged) {
3498 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3499 // We only allow setting layer stacks for top level layers,
3500 // everything else inherits layer stack from its parent.
3501 if (layer->hasParent()) {
3502 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3503 layer->getName().string());
3504 } else if (idx < 0) {
3505 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3506 "that also does not appear in the top level layer list. Something"
3507 " has gone wrong.", layer->getName().string());
3508 } else if (layer->setLayerStack(s.layerStack)) {
3509 mCurrentState.layersSortedByZ.removeAt(idx);
3510 mCurrentState.layersSortedByZ.add(layer);
3511 // we need traversal (state changed)
3512 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003513 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003514 }
3515 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003516 if (what & layer_state_t::eDeferTransaction_legacy) {
3517 if (s.barrierHandle_legacy != nullptr) {
3518 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3519 } else if (s.barrierGbp_legacy != nullptr) {
3520 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003521 if (authenticateSurfaceTextureLocked(gbp)) {
3522 const auto& otherLayer =
3523 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003524 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003525 } else {
3526 ALOGE("Attempt to defer transaction to to an"
3527 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003528 }
3529 }
chaviw8b3871a2017-11-01 17:41:01 -07003530 // We don't trigger a traversal here because if no other state is
3531 // changed, we don't want this to cause any more work
3532 }
3533 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003534 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003535 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003536 if (!hadParent) {
3537 mCurrentState.layersSortedByZ.remove(layer);
3538 }
chaviw8b3871a2017-11-01 17:41:01 -07003539 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003540 }
chaviw8b3871a2017-11-01 17:41:01 -07003541 }
3542 if (what & layer_state_t::eReparentChildren) {
3543 if (layer->reparentChildren(s.reparentHandle)) {
3544 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003545 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003546 }
chaviw8b3871a2017-11-01 17:41:01 -07003547 if (what & layer_state_t::eDetachChildren) {
3548 layer->detachChildren();
3549 }
3550 if (what & layer_state_t::eOverrideScalingModeChanged) {
3551 layer->setOverrideScalingMode(s.overrideScalingMode);
3552 // We don't trigger a traversal here because if no other state is
3553 // changed, we don't want this to cause any more work
3554 }
Marissa Wall61c58622018-07-18 10:12:20 -07003555 if (what & layer_state_t::eTransformChanged) {
3556 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3557 }
3558 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3559 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3560 flags |= eTraversalNeeded;
3561 }
3562 if (what & layer_state_t::eCropChanged) {
3563 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3564 }
3565 if (what & layer_state_t::eBufferChanged) {
3566 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3567 }
3568 if (what & layer_state_t::eAcquireFenceChanged) {
3569 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3570 }
3571 if (what & layer_state_t::eDataspaceChanged) {
3572 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3573 }
3574 if (what & layer_state_t::eHdrMetadataChanged) {
3575 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3576 }
3577 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3578 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3579 }
3580 if (what & layer_state_t::eApiChanged) {
3581 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3582 }
3583 if (what & layer_state_t::eSidebandStreamChanged) {
3584 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3585 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003586 return flags;
3587}
3588
chaviwca27f252018-02-06 16:46:39 -08003589void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3590 const layer_state_t& state = composerState.state;
3591 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3592
3593 sp<Layer> layer(client->getLayerUser(state.surface));
3594 if (layer == nullptr) {
3595 return;
3596 }
3597
3598 if (layer->isPendingRemoval()) {
3599 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3600 return;
3601 }
3602
3603 if (state.what & layer_state_t::eDestroySurface) {
3604 removeLayerLocked(mStateLock, layer);
3605 }
3606}
3607
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003608status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003609 const String8& name,
3610 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003611 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003612 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003613 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003614{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003615 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003616 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003617 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003618 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003619 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003620
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003621 status_t result = NO_ERROR;
3622
3623 sp<Layer> layer;
3624
Cody Northropbc755282017-03-31 12:00:08 -06003625 String8 uniqueName = getUniqueLayerName(name);
3626
Mathias Agopian3165cc22012-08-08 19:42:09 -07003627 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003628 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003629 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3630 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003631
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003632 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003633 case ISurfaceComposerClient::eFXSurfaceBufferState:
3634 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3635 break;
chaviw13fdc492017-06-27 12:40:18 -07003636 case ISurfaceComposerClient::eFXSurfaceColor:
3637 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003638 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003639 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003640 break;
3641 default:
3642 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003643 break;
3644 }
3645
Dan Stoza7d89d062015-04-30 13:29:25 -07003646 if (result != NO_ERROR) {
3647 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003648 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003649
Chia-I Wuab0c3192017-08-01 11:29:00 -07003650 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3651 // TODO b/64227542
3652 if (windowType == 441731) {
3653 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3654 layer->setPrimaryDisplayOnly();
3655 }
3656
Albert Chaulk479c60c2017-01-27 14:21:34 -05003657 layer->setInfo(windowType, ownerUid);
3658
Robert Carr1f0a16a2016-10-24 16:27:39 -07003659 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003660 if (result != NO_ERROR) {
3661 return result;
3662 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003663 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003664
3665 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003666 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003667}
3668
Cody Northropbc755282017-03-31 12:00:08 -06003669String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3670{
3671 bool matchFound = true;
3672 uint32_t dupeCounter = 0;
3673
3674 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3675 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3676
Dan Stoza436ccf32018-06-21 12:10:12 -07003677 // Grab the state lock since we're accessing mCurrentState
3678 Mutex::Autolock lock(mStateLock);
3679
Cody Northropbc755282017-03-31 12:00:08 -06003680 // Loop over layers until we're sure there is no matching name
3681 while (matchFound) {
3682 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003683 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003684 if (layer->getName() == uniqueName) {
3685 matchFound = true;
3686 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3687 }
3688 });
3689 }
3690
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003691 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3692 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003693
3694 return uniqueName;
3695}
3696
Marissa Wallfd668622018-05-10 10:21:13 -07003697status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3698 uint32_t w, uint32_t h, uint32_t flags,
3699 PixelFormat& format, sp<IBinder>* handle,
3700 sp<IGraphicBufferProducer>* gbp,
3701 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003702 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003703 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003704 case PIXEL_FORMAT_TRANSPARENT:
3705 case PIXEL_FORMAT_TRANSLUCENT:
3706 format = PIXEL_FORMAT_RGBA_8888;
3707 break;
3708 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003709 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003710 break;
3711 }
3712
Marissa Wallfd668622018-05-10 10:21:13 -07003713 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3714 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003715 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003716 *handle = layer->getHandle();
3717 *gbp = layer->getProducer();
3718 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003719 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003720
Marissa Wallfd668622018-05-10 10:21:13 -07003721 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003722 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003723}
3724
Marissa Wall61c58622018-07-18 10:12:20 -07003725status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3726 uint32_t w, uint32_t h, uint32_t flags,
3727 sp<IBinder>* handle, sp<Layer>* outLayer) {
3728 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3729 *handle = layer->getHandle();
3730 *outLayer = layer;
3731
3732 return NO_ERROR;
3733}
3734
chaviw13fdc492017-06-27 12:40:18 -07003735status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003736 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003737 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003738{
chaviw13fdc492017-06-27 12:40:18 -07003739 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003740 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003741 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003742}
3743
Mathias Agopianac9fa422013-02-11 16:40:36 -08003744status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003745{
Robert Carr9524cb32017-02-13 11:32:32 -08003746 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003747 status_t err = NO_ERROR;
3748 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003749 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003750 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003751 err = removeLayer(l);
3752 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3753 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003754 }
3755 return err;
3756}
3757
Mathias Agopian13127d82013-03-05 17:47:11 -08003758status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003759{
Mathias Agopian67106042013-03-14 19:18:13 -07003760 // called by ~LayerCleaner() when all references to the IBinder (handle)
3761 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003762 sp<Layer> l = layer.promote();
3763 if (l == nullptr) {
3764 // The layer has already been removed, carry on
3765 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003766 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003767 // If we have a parent, then we can continue to live as long as it does.
3768 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003769}
3770
Mathias Agopianb60314a2012-04-10 22:09:54 -07003771// ---------------------------------------------------------------------------
3772
Andy McFadden13a082e2012-08-24 10:16:42 -07003773void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003774 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3775 if (!displayToken) return;
3776
Jesse Hall01e29052013-02-19 16:13:35 -08003777 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003778 Vector<ComposerState> state;
3779 Vector<DisplayState> displays;
3780 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003781 d.what = DisplayState::eDisplayProjectionChanged |
3782 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003783 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003784 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003785 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003786 d.frame.makeInvalid();
3787 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003788 d.width = 0;
3789 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003790 displays.add(d);
3791 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003792
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003793 const auto display = getDisplayDevice(displayToken);
3794 if (!display) return;
3795
3796 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3797
3798 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003799 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003800 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003801
Brian Andersond0010582017-03-07 13:20:31 -08003802 // Use phase of 0 since phase is not known.
3803 // Use latency of 0, which will snap to the ideal latency.
3804 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003805}
3806
3807void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003808 // Async since we may be called from the main thread.
3809 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003810}
3811
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003812void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3813 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003814 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003815 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003816
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003817 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003818 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003819 return;
3820 }
3821
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003822 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003823 ALOGW("Trying to set power mode for virtual display");
3824 return;
3825 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003826
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003827 display->setPowerMode(mode);
3828
Lloyd Pique4dccc412018-01-22 17:21:36 -08003829 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003830 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003831 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003832 if (idx < 0) {
3833 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3834 return;
3835 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003836 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003837 }
3838
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003839 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003840 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003841 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003842 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003843 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003844 // FIXME: eventthread only knows about the main display right now
3845 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003846 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003847 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003848
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003849 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003850 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003851 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003852
3853 struct sched_param param = {0};
3854 param.sched_priority = 1;
3855 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3856 ALOGW("Couldn't set SCHED_FIFO on display on");
3857 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003858 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003859 // Turn off the display
3860 struct sched_param param = {0};
3861 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3862 ALOGW("Couldn't set SCHED_OTHER on display off");
3863 }
3864
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003865 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003866 disableHardwareVsync(true); // also cancels any in-progress resync
3867
Mathias Agopiancde87a32012-09-13 14:09:01 -07003868 // FIXME: eventthread only knows about the main display right now
3869 mEventThread->onScreenReleased();
3870 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003871
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003872 getHwComposer().setPowerMode(type, mode);
3873 mVisibleRegionsDirty = true;
3874 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003875 } else if (mode == HWC_POWER_MODE_DOZE ||
3876 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003877 // Update display while dozing
3878 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003879 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003880 // FIXME: eventthread only knows about the main display right now
3881 mEventThread->onScreenAcquired();
3882 resyncToHardwareVsync(true);
3883 }
3884 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3885 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003886 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003887 disableHardwareVsync(true); // also cancels any in-progress resync
3888 // FIXME: eventthread only knows about the main display right now
3889 mEventThread->onScreenReleased();
3890 }
3891 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003892 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003893 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003894 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003895 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003896
3897 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003898}
3899
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003900void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003901 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003902 const auto display = getDisplayDevice(displayToken);
3903 if (!display) {
3904 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3905 displayToken.get());
3906 } else if (display->isVirtual()) {
3907 ALOGW("Attempt to set power mode %d for virtual display", mode);
3908 } else {
3909 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003910 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003911 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003912}
3913
3914// ---------------------------------------------------------------------------
3915
Lloyd Pique755e3192018-01-31 16:46:15 -08003916status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3917 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003918 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003919
Mathias Agopianbd115332013-04-18 16:41:04 -07003920 IPCThreadState* ipc = IPCThreadState::self();
3921 const int pid = ipc->getCallingPid();
3922 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003923
Mathias Agopianbd115332013-04-18 16:41:04 -07003924 if ((uid != AID_SHELL) &&
3925 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003926 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003927 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003928 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003929 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003930 // (this would indicate SF is stuck, but we want to be able to
3931 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003932 status_t err = mStateLock.timedLock(s2ns(1));
3933 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003934 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003935 result.appendFormat(
3936 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3937 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003938 }
3939
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003940 bool dumpAll = true;
3941 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003942 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003943
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003944 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003945 if ((index < numArgs) &&
3946 (args[index] == String16("--list"))) {
3947 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003948 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003949 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003950 }
3951
3952 if ((index < numArgs) &&
3953 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003954 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003955 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003956 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003957 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003958
3959 if ((index < numArgs) &&
3960 (args[index] == String16("--latency-clear"))) {
3961 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003962 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003963 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003964 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003965
3966 if ((index < numArgs) &&
3967 (args[index] == String16("--dispsync"))) {
3968 index++;
3969 mPrimaryDispSync.dump(result);
3970 dumpAll = false;
3971 }
Dan Stozab90cf072015-03-05 11:05:59 -08003972
3973 if ((index < numArgs) &&
3974 (args[index] == String16("--static-screen"))) {
3975 index++;
3976 dumpStaticScreenStats(result);
3977 dumpAll = false;
3978 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003979
3980 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003981 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003982 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003983 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003984 dumpAll = false;
3985 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003986
3987 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3988 index++;
3989 dumpWideColorInfo(result);
3990 dumpAll = false;
3991 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003992
3993 if ((index < numArgs) &&
3994 (args[index] == String16("--enable-layer-stats"))) {
3995 index++;
3996 mLayerStats.enable();
3997 dumpAll = false;
3998 }
3999
4000 if ((index < numArgs) &&
4001 (args[index] == String16("--disable-layer-stats"))) {
4002 index++;
4003 mLayerStats.disable();
4004 dumpAll = false;
4005 }
4006
4007 if ((index < numArgs) &&
4008 (args[index] == String16("--clear-layer-stats"))) {
4009 index++;
4010 mLayerStats.clear();
4011 dumpAll = false;
4012 }
4013
4014 if ((index < numArgs) &&
4015 (args[index] == String16("--dump-layer-stats"))) {
4016 index++;
4017 mLayerStats.dump(result);
4018 dumpAll = false;
4019 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004020
4021 if ((index < numArgs) &&
4022 (args[index] == String16("--display-identification"))) {
4023 index++;
4024 dumpDisplayIdentificationData(result);
4025 dumpAll = false;
4026 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004027
4028 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4029 index++;
4030 mTimeStats.parseArgs(asProto, args, index, result);
4031 dumpAll = false;
4032 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004033 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004034
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004035 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004036 if (asProto) {
4037 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4038 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4039 } else {
4040 dumpAllLocked(args, index, result);
4041 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004042 }
4043
Mathias Agopian9795c422009-08-26 16:36:26 -07004044 if (locked) {
4045 mStateLock.unlock();
4046 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004047 }
4048 write(fd, result.string(), result.size());
4049 return NO_ERROR;
4050}
4051
Dan Stozac7014012014-02-14 15:03:43 -08004052void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4053 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004054{
Robert Carr2047fae2016-11-28 14:09:09 -08004055 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004056 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004057 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004058}
4059
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004060void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004061 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004062{
4063 String8 name;
4064 if (index < args.size()) {
4065 name = String8(args[index]);
4066 index++;
4067 }
4068
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004069 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4070 getHwComposer().isConnected(displayId)) {
4071 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4072 const nsecs_t period = activeConfig->getVsyncPeriod();
4073 result.appendFormat("%" PRId64 "\n", period);
4074 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004075
4076 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004077 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004078 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004079 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004080 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004081 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004082 }
Robert Carr2047fae2016-11-28 14:09:09 -08004083 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004084 }
4085}
4086
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004087void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004088 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004089{
4090 String8 name;
4091 if (index < args.size()) {
4092 name = String8(args[index]);
4093 index++;
4094 }
4095
Robert Carr2047fae2016-11-28 14:09:09 -08004096 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004097 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004098 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004099 }
Robert Carr2047fae2016-11-28 14:09:09 -08004100 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004101
Svetoslavd85084b2014-03-20 10:28:31 -07004102 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004103}
4104
Jamie Gennis6547ff42013-07-16 20:12:42 -07004105// This should only be called from the main thread. Otherwise it would need
4106// the lock and should use mCurrentState rather than mDrawingState.
4107void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004108 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004109 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004110 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004111
4112 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4113}
4114
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004115void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004116{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004117 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004118
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004119 if (isLayerTripleBufferingDisabled())
4120 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004121
4122 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004123 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004124 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004125 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004126 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4127 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004128 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004129}
4130
Dan Stozab90cf072015-03-05 11:05:59 -08004131void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4132{
4133 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004134 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4135 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004136 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004137 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004138 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4139 b + 1, bucketTimeSec, percent);
4140 }
David Sodman4a36e932017-11-07 14:29:47 -08004141 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004142 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004143 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004144 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004145 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004146}
4147
Dan Stozae77c7662016-05-13 11:37:28 -07004148void SurfaceFlinger::recordBufferingStats(const char* layerName,
4149 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004150 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4151 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004152 for (const auto& segment : history) {
4153 if (!segment.usedThirdBuffer) {
4154 stats.twoBufferTime += segment.totalTime;
4155 }
4156 if (segment.occupancyAverage < 1.0f) {
4157 stats.doubleBufferedTime += segment.totalTime;
4158 } else if (segment.occupancyAverage < 2.0f) {
4159 stats.tripleBufferedTime += segment.totalTime;
4160 }
4161 ++stats.numSegments;
4162 stats.totalTime += segment.totalTime;
4163 }
4164}
4165
Brian Andersond6927fb2016-07-23 23:37:30 -07004166void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4167 result.appendFormat("Layer frame timestamps:\n");
4168
4169 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4170 const size_t count = currentLayers.size();
4171 for (size_t i=0 ; i<count ; i++) {
4172 currentLayers[i]->dumpFrameEvents(result);
4173 }
4174}
4175
Dan Stozae77c7662016-05-13 11:37:28 -07004176void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4177 result.append("Buffering stats:\n");
4178 result.append(" [Layer name] <Active time> <Two buffer> "
4179 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004180 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004181 typedef std::tuple<std::string, float, float, float> BufferTuple;
4182 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004183 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004184 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004185 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004186 if (stats.numSegments == 0) {
4187 continue;
4188 }
4189 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4190 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4191 stats.totalTime;
4192 float doubleBufferRatio = static_cast<float>(
4193 stats.doubleBufferedTime) / stats.totalTime;
4194 float tripleBufferRatio = static_cast<float>(
4195 stats.tripleBufferedTime) / stats.totalTime;
4196 sorted.insert({activeTime, {name, twoBufferRatio,
4197 doubleBufferRatio, tripleBufferRatio}});
4198 }
4199 for (const auto& sortedPair : sorted) {
4200 float activeTime = sortedPair.first;
4201 const BufferTuple& values = sortedPair.second;
4202 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4203 std::get<0>(values).c_str(), activeTime,
4204 std::get<1>(values), std::get<2>(values),
4205 std::get<3>(values));
4206 }
4207 result.append("\n");
4208}
4209
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004210void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004211 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004212 const int32_t displayId = display->getId();
4213 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4214 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004215 continue;
4216 }
4217
Dominik Laskowski7e045462018-05-30 13:02:02 -07004218 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004219 uint8_t port;
4220 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004221 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004222 result.append("no identification data\n");
4223 continue;
4224 }
4225
4226 if (!isEdid(data)) {
4227 result.append("unknown identification data: ");
4228 for (uint8_t byte : data) {
4229 result.appendFormat("%x ", byte);
4230 }
4231 result.append("\n");
4232 continue;
4233 }
4234
4235 const auto edid = parseEdid(data);
4236 if (!edid) {
4237 result.append("invalid EDID: ");
4238 for (uint8_t byte : data) {
4239 result.appendFormat("%x ", byte);
4240 }
4241 result.append("\n");
4242 continue;
4243 }
4244
4245 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4246 result.append(edid->displayName.data(), edid->displayName.length());
4247 result.append("\"\n");
4248 }
4249 result.append("\n");
4250}
4251
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004252void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4253 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004254 result.appendFormat("DisplayColorSetting: %s\n",
4255 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004256
4257 // TODO: print out if wide-color mode is active or not
4258
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004259 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004260 const int32_t displayId = display->getId();
4261 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004262 continue;
4263 }
4264
Dominik Laskowski7e045462018-05-30 13:02:02 -07004265 result.appendFormat("Display %d color modes:\n", displayId);
4266 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004267 for (auto&& mode : modes) {
4268 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4269 }
4270
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004271 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004272 result.appendFormat(" Current color mode: %s (%d)\n",
4273 decodeColorMode(currentMode).c_str(), currentMode);
4274 }
4275 result.append("\n");
4276}
4277
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004278LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004279 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004280 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4281 const State& state = useDrawing ? mDrawingState : mCurrentState;
4282 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004283 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004284 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004285 });
4286
4287 return layersProto;
4288}
4289
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004290LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004291 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004292
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004293 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004294 resolution->set_w(display.getWidth());
4295 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004296
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004297 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4298 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4299 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004300
Dominik Laskowski7e045462018-05-30 13:02:02 -07004301 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004302 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004303 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004304 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004305 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004306 }
4307 });
4308
4309 return layersProto;
4310}
4311
Mathias Agopian74d211a2013-04-22 16:55:35 +02004312void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4313 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004314{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004315 bool colorize = false;
4316 if (index < args.size()
4317 && (args[index] == String16("--color"))) {
4318 colorize = true;
4319 index++;
4320 }
4321
4322 Colorizer colorizer(colorize);
4323
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004324 // figure out if we're stuck somewhere
4325 const nsecs_t now = systemTime();
4326 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4327 const nsecs_t inTransaction(mDebugInTransaction);
4328 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4329 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4330
4331 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004332 * Dump library configuration.
4333 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004334
4335 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004336 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004337 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004338 appendSfConfigString(result);
4339 appendUiConfigString(result);
4340 appendGuiConfigString(result);
4341 result.append("\n");
4342
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004343 result.append("\nDisplay identification data:\n");
4344 dumpDisplayIdentificationData(result);
4345
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004346 result.append("\nWide-Color information:\n");
4347 dumpWideColorInfo(result);
4348
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004349 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004350 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004351 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004352 result.append(SyncFeatures::getInstance().toString());
4353 result.append("\n");
4354
Andy McFadden41d67d72014-04-25 16:58:34 -07004355 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004356 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004357 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004358
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004359 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4360 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004361 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4362 getHwComposer().isConnected(displayId)) {
4363 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004364 result.appendFormat("Display %d: "
4365 "app phase %" PRId64 " ns, "
4366 "sf phase %" PRId64 " ns, "
4367 "early app phase %" PRId64 " ns, "
4368 "early sf phase %" PRId64 " ns, "
4369 "early app gl phase %" PRId64 " ns, "
4370 "early sf gl phase %" PRId64 " ns, "
4371 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4372 displayId,
4373 vsyncPhaseOffsetNs,
4374 sfVsyncPhaseOffsetNs,
4375 appEarlyOffset,
4376 sfEarlyOffset,
4377 appEarlyGlOffset,
4378 sfEarlyOffset,
4379 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004380 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004381 result.append("\n");
4382
Dan Stozab90cf072015-03-05 11:05:59 -08004383 // Dump static screen stats
4384 result.append("\n");
4385 dumpStaticScreenStats(result);
4386 result.append("\n");
4387
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004388 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4389
Dan Stozae77c7662016-05-13 11:37:28 -07004390 dumpBufferingStats(result);
4391
Andy McFadden4803b742012-09-24 19:07:20 -07004392 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004393 * Dump the visible layer list
4394 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004395 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004396 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004397 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4398 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004399 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004400
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004401 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004402 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004403 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004404 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004405
4406 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004407 * Dump Display state
4408 */
4409
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004410 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004411 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004412 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004413 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004414 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004415 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004416 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004417
4418 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004419 * Dump SurfaceFlinger global state
4420 */
4421
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004422 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004423 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004424 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004425
Mathias Agopian888c8222012-08-04 21:10:38 -07004426 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004427 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004428
David Sodmanbc815282017-11-05 18:57:52 -08004429 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004430
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004431 if (display) {
4432 display->undefinedRegion.dump(result, "undefinedRegion");
4433 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4434 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004435 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004436 result.appendFormat(" last eglSwapBuffers() time: %f us\n"
4437 " last transaction time : %f us\n"
4438 " transaction-flags : %08x\n"
4439 " gpu_to_cpu_unsupported : %d\n",
4440 mLastSwapBufferTime / 1000.0, mLastTransactionTime / 1000.0,
4441 mTransactionFlags, !mGpuToCpuSupported);
4442
4443 if (display) {
4444 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4445 result.appendFormat(" refresh-rate : %f fps\n"
4446 " x-dpi : %f\n"
4447 " y-dpi : %f\n",
4448 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4449 activeConfig->getDpiY());
4450 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004451
Mathias Agopian74d211a2013-04-22 16:55:35 +02004452 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004453 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004454
Mathias Agopian74d211a2013-04-22 16:55:35 +02004455 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004456 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004457
4458 /*
4459 * VSYNC state
4460 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004461 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004462 result.append("\n");
4463
4464 /*
4465 * HWC layer minidump
4466 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004467 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004468 const int32_t displayId = display->getId();
4469 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004470 continue;
4471 }
4472
Dominik Laskowski7e045462018-05-30 13:02:02 -07004473 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004474 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004475 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004476 result.append("\n");
4477 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004478
4479 /*
4480 * Dump HWComposer state
4481 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004482 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004483 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004484 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004485 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004486 result.appendFormat(" h/w composer %s\n",
4487 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004488 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004489
4490 /*
4491 * Dump gralloc state
4492 */
4493 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4494 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004495
4496 /*
4497 * Dump VrFlinger state if in use.
4498 */
4499 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4500 result.append("VrFlinger state:\n");
4501 result.append(mVrFlinger->Dump().c_str());
4502 result.append("\n");
4503 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004504}
4505
Dominik Laskowski7e045462018-05-30 13:02:02 -07004506const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004507 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004508 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004509 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004510 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004511 }
4512 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004513
4514 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4515 static const Vector<sp<Layer>> empty;
4516 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004517}
4518
Keun young Park63f165f2012-08-31 10:53:36 -07004519bool SurfaceFlinger::startDdmConnection()
4520{
4521 void* libddmconnection_dso =
4522 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4523 if (!libddmconnection_dso) {
4524 return false;
4525 }
4526 void (*DdmConnection_start)(const char* name);
4527 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004528 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004529 if (!DdmConnection_start) {
4530 dlclose(libddmconnection_dso);
4531 return false;
4532 }
4533 (*DdmConnection_start)(getServiceName());
4534 return true;
4535}
4536
Chia-I Wu28f320b2018-05-03 11:02:56 -07004537void SurfaceFlinger::updateColorMatrixLocked() {
4538 mat4 colorMatrix;
4539 if (mGlobalSaturationFactor != 1.0f) {
4540 // Rec.709 luma coefficients
4541 float3 luminance{0.213f, 0.715f, 0.072f};
4542 luminance *= 1.0f - mGlobalSaturationFactor;
4543 mat4 saturationMatrix = mat4(
4544 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4545 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4546 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4547 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4548 );
4549 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4550 } else {
4551 colorMatrix = mClientColorMatrix * mDaltonizer();
4552 }
4553
4554 if (mCurrentState.colorMatrix != colorMatrix) {
4555 mCurrentState.colorMatrix = colorMatrix;
4556 mCurrentState.colorMatrixChanged = true;
4557 setTransactionFlags(eTransactionNeeded);
4558 }
4559}
4560
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004561status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004562 switch (code) {
4563 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004564 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004565 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004566 case CLEAR_ANIMATION_FRAME_STATS:
4567 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004568 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004569 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004570 case ENABLE_VSYNC_INJECTIONS:
4571 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004572 {
4573 // codes that require permission check
Robert Carrd4ae7f32018-06-07 16:10:57 -07004574 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4575 IPCThreadState* ipc = IPCThreadState::self();
4576 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4577 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004578 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004579 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004580 break;
4581 }
Robert Carr1db73f62016-12-21 12:58:51 -08004582 /*
4583 * Calling setTransactionState is safe, because you need to have been
4584 * granted a reference to Client* and Handle* to do anything with it.
4585 *
4586 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4587 */
4588 case SET_TRANSACTION_STATE:
4589 case CREATE_SCOPED_CONNECTION:
4590 {
4591 return OK;
4592 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004593 case CAPTURE_SCREEN:
4594 {
4595 // codes that require permission check
4596 IPCThreadState* ipc = IPCThreadState::self();
4597 const int pid = ipc->getCallingPid();
4598 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004599 if ((uid != AID_GRAPHICS) &&
4600 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004601 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004602 return PERMISSION_DENIED;
4603 }
4604 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004605 }
chaviwa76b2712017-09-20 12:02:26 -07004606 case CAPTURE_LAYERS: {
4607 IPCThreadState* ipc = IPCThreadState::self();
4608 const int pid = ipc->getCallingPid();
4609 const int uid = ipc->getCallingUid();
4610 if ((uid != AID_GRAPHICS) &&
4611 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4612 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4613 return PERMISSION_DENIED;
4614 }
4615 break;
4616 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004617 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004618 return OK;
4619}
4620
4621status_t SurfaceFlinger::onTransact(
4622 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4623{
4624 status_t credentialCheck = CheckTransactCodeCredentials(code);
4625 if (credentialCheck != OK) {
4626 return credentialCheck;
4627 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004628
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004629 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4630 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004631 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004632 IPCThreadState* ipc = IPCThreadState::self();
4633 const int uid = ipc->getCallingUid();
4634 if (CC_UNLIKELY(uid != AID_SYSTEM
4635 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004636 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004637 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004638 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004639 return PERMISSION_DENIED;
4640 }
4641 int n;
4642 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004643 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004644 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004645 return NO_ERROR;
4646 case 1002: // SHOW_UPDATES
4647 n = data.readInt32();
4648 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004649 invalidateHwcGeometry();
4650 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004651 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004652 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004653 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004654 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004655 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004656 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004657 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004658 setTransactionFlags(
4659 eTransactionNeeded|
4660 eDisplayTransactionNeeded|
4661 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004662 return NO_ERROR;
4663 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004664 case 1006:{ // send empty update
4665 signalRefresh();
4666 return NO_ERROR;
4667 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004668 case 1008: // toggle use of hw composer
4669 n = data.readInt32();
4670 mDebugDisableHWC = n ? 1 : 0;
4671 invalidateHwcGeometry();
4672 repaintEverything();
4673 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004674 case 1009: // toggle use of transform hint
4675 n = data.readInt32();
4676 mDebugDisableTransformHint = n ? 1 : 0;
4677 invalidateHwcGeometry();
4678 repaintEverything();
4679 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004680 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004681 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004682 reply->writeInt32(0);
4683 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004684 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004685 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004686 return NO_ERROR;
4687 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004688 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004689 if (!display) {
4690 return NAME_NOT_FOUND;
4691 }
4692
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004693 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004694 return NO_ERROR;
4695 }
4696 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004697 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004698 // daltonize
4699 n = data.readInt32();
4700 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004701 case 1:
4702 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4703 break;
4704 case 2:
4705 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4706 break;
4707 case 3:
4708 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4709 break;
4710 default:
4711 mDaltonizer.setType(ColorBlindnessType::None);
4712 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004713 }
4714 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004715 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004716 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004717 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004718 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004719
4720 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004721 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004722 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004723 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004724 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004725 // apply a color matrix
4726 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004727 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004728 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004729 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004730 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004731 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004732 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004733 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004734 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004735 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004736 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004737
4738 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4739 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004740 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004741 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4742 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4743 }
4744
Chia-I Wu28f320b2018-05-03 11:02:56 -07004745 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004746 return NO_ERROR;
4747 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004748 // This is an experimental interface
4749 // Needs to be shifted to proper binder interface when we productize
4750 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004751 n = data.readInt32();
4752 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004753 return NO_ERROR;
4754 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004755 case 1017: {
4756 n = data.readInt32();
4757 mForceFullDamage = static_cast<bool>(n);
4758 return NO_ERROR;
4759 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004760 case 1018: { // Modify Choreographer's phase offset
4761 n = data.readInt32();
4762 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4763 return NO_ERROR;
4764 }
4765 case 1019: { // Modify SurfaceFlinger's phase offset
4766 n = data.readInt32();
4767 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4768 return NO_ERROR;
4769 }
Irvel468051e2016-06-13 16:44:44 -07004770 case 1020: { // Layer updates interceptor
4771 n = data.readInt32();
4772 if (n) {
4773 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004774 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004775 }
4776 else{
4777 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004778 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004779 }
4780 return NO_ERROR;
4781 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004782 case 1021: { // Disable HWC virtual displays
4783 n = data.readInt32();
4784 mUseHwcVirtualDisplays = !n;
4785 return NO_ERROR;
4786 }
Romain Guy0147a172017-06-01 13:53:56 -07004787 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004788 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004789 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004790
Chia-I Wu28f320b2018-05-03 11:02:56 -07004791 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004792 return NO_ERROR;
4793 }
Romain Guy54f154a2017-10-24 21:40:32 +01004794 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004795 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004796 invalidateHwcGeometry();
4797 repaintEverything();
4798 return NO_ERROR;
4799 }
4800 case 1024: { // Is wide color gamut rendering/color management supported?
4801 reply->writeBool(hasWideColorDisplay);
4802 return NO_ERROR;
4803 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004804 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004805 n = data.readInt32();
4806 if (n) {
4807 ALOGV("LayerTracing enabled");
4808 mTracing.enable();
4809 doTracing("tracing.enable");
4810 reply->writeInt32(NO_ERROR);
4811 } else {
4812 ALOGV("LayerTracing disabled");
4813 status_t err = mTracing.disable();
4814 reply->writeInt32(err);
4815 }
4816 return NO_ERROR;
4817 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004818 case 1026: { // Get layer tracing status
4819 reply->writeBool(mTracing.isEnabled());
4820 return NO_ERROR;
4821 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004822 // Is a DisplayColorSetting supported?
4823 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004824 const auto display = getDefaultDisplayDevice();
4825 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004826 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004827 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004828
4829 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4830 switch (setting) {
4831 case DisplayColorSetting::MANAGED:
4832 reply->writeBool(hasWideColorDisplay);
4833 break;
4834 case DisplayColorSetting::UNMANAGED:
4835 reply->writeBool(true);
4836 break;
4837 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004838 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004839 break;
4840 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004841 reply->writeBool(
4842 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004843 break;
4844 }
4845 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004846 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004847 // Is VrFlinger active?
4848 case 1028: {
4849 Mutex::Autolock _l(mStateLock);
4850 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4851 return NO_ERROR;
4852 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004853 }
4854 }
4855 return err;
4856}
4857
Steven Thomas6d8110b2017-08-31 18:24:21 -07004858void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004859 android_atomic_or(1, &mRepaintEverything);
4860 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004861}
4862
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004863// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4864class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004865public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004866 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4867 ~WindowDisconnector() {
4868 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004869 }
4870
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004871private:
4872 ANativeWindow* mWindow;
4873 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004874};
4875
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004876status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4877 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4878 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4879 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004880 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004881 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004882
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004883 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004884
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004885 const auto display = getDisplayDeviceLocked(displayToken);
4886 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004887
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004888 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004889
4890 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004891 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004892 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004893}
4894
4895status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004896 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004897 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004898 ATRACE_CALL();
4899
4900 class LayerRenderArea : public RenderArea {
4901 public:
Robert Carr578038f2018-03-09 12:25:24 -08004902 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4903 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004904 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004905 mLayer(layer),
4906 mCrop(crop),
4907 mFlinger(flinger),
4908 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004909 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004910 Rect getBounds() const override {
4911 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07004912 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07004913 }
Marissa Wall61c58622018-07-18 10:12:20 -07004914 int getHeight() const override {
4915 return mLayer->getActiveHeight(mLayer->getDrawingState());
4916 }
4917 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07004918 bool isSecure() const override { return false; }
4919 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004920 Rect getSourceCrop() const override {
4921 if (mCrop.isEmpty()) {
4922 return getBounds();
4923 } else {
4924 return mCrop;
4925 }
4926 }
Robert Carr578038f2018-03-09 12:25:24 -08004927 class ReparentForDrawing {
4928 public:
4929 const sp<Layer>& oldParent;
4930 const sp<Layer>& newParent;
4931
4932 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4933 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004934 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004935 }
Robert Carr15eae092018-03-23 13:43:53 -07004936 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004937 };
4938
4939 void render(std::function<void()> drawLayers) override {
4940 if (!mChildrenOnly) {
4941 mTransform = mLayer->getTransform().inverse();
4942 drawLayers();
4943 } else {
4944 Rect bounds = getBounds();
4945 screenshotParentLayer =
4946 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4947 bounds.getWidth(), bounds.getHeight(), 0);
4948
4949 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4950 drawLayers();
4951 }
4952 }
chaviwa76b2712017-09-20 12:02:26 -07004953
chaviwa76b2712017-09-20 12:02:26 -07004954 private:
chaviw7206d492017-11-10 16:16:12 -08004955 const sp<Layer> mLayer;
4956 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004957
4958 // In the "childrenOnly" case we reparent the children to a screenshot
4959 // layer which has no properties set and which does not draw.
4960 sp<ContainerLayer> screenshotParentLayer;
4961 Transform mTransform;
4962
4963 SurfaceFlinger* mFlinger;
4964 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004965 };
4966
4967 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4968 auto parent = layerHandle->owner.promote();
4969
chaviw7206d492017-11-10 16:16:12 -08004970 if (parent == nullptr || parent->isPendingRemoval()) {
4971 ALOGE("captureLayers called with a removed parent");
4972 return NAME_NOT_FOUND;
4973 }
4974
Robert Carr578038f2018-03-09 12:25:24 -08004975 const int uid = IPCThreadState::self()->getCallingUid();
4976 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4977 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4978 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4979 return PERMISSION_DENIED;
4980 }
4981
chaviw7206d492017-11-10 16:16:12 -08004982 Rect crop(sourceCrop);
4983 if (sourceCrop.width() <= 0) {
4984 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07004985 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08004986 }
4987
4988 if (sourceCrop.height() <= 0) {
4989 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07004990 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08004991 }
4992
4993 int32_t reqWidth = crop.width() * frameScale;
4994 int32_t reqHeight = crop.height() * frameScale;
4995
Robert Carr578038f2018-03-09 12:25:24 -08004996 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004997
Robert Carr578038f2018-03-09 12:25:24 -08004998 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004999 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5000 if (!layer->isVisible()) {
5001 return;
Robert Carr578038f2018-03-09 12:25:24 -08005002 } else if (childrenOnly && layer == parent.get()) {
5003 return;
chaviwa76b2712017-09-20 12:02:26 -07005004 }
5005 visitor(layer);
5006 });
5007 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005008 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005009}
5010
5011status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5012 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005013 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005014 bool useIdentityTransform) {
5015 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005016
Iris Chang7501ed62018-04-30 14:45:42 +08005017 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07005018
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005019 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5020 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5021 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5022 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005023
5024 // This mutex protects syncFd and captureResult for communication of the return values from the
5025 // main thread back to this Binder thread
5026 std::mutex captureMutex;
5027 std::condition_variable captureCondition;
5028 std::unique_lock<std::mutex> captureLock(captureMutex);
5029 int syncFd = -1;
5030 std::optional<status_t> captureResult;
5031
Robert Carr03480e22018-01-04 16:02:06 -08005032 const int uid = IPCThreadState::self()->getCallingUid();
5033 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5034
Dominik Laskowski8c001672018-05-30 16:52:06 -07005035 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005036 // If there is a refresh pending, bug out early and tell the binder thread to try again
5037 // after the refresh.
5038 if (mRefreshPending) {
5039 ATRACE_NAME("Skipping screenshot for now");
5040 std::unique_lock<std::mutex> captureLock(captureMutex);
5041 captureResult = std::make_optional<status_t>(EAGAIN);
5042 captureCondition.notify_one();
5043 return;
5044 }
5045
5046 status_t result = NO_ERROR;
5047 int fd = -1;
5048 {
5049 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005050 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005051 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5052 useIdentityTransform, forSystem, &fd);
5053 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005054 }
5055
5056 {
5057 std::unique_lock<std::mutex> captureLock(captureMutex);
5058 syncFd = fd;
5059 captureResult = std::make_optional<status_t>(result);
5060 captureCondition.notify_one();
5061 }
5062 });
5063
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005064 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005065 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005066 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005067 while (*captureResult == EAGAIN) {
5068 captureResult.reset();
5069 result = postMessageAsync(message);
5070 if (result != NO_ERROR) {
5071 return result;
5072 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005073 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005074 }
5075 result = *captureResult;
5076 }
5077
5078 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005079 sync_wait(syncFd, -1);
5080 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005081 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005082
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005083 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005084}
5085
chaviwa76b2712017-09-20 12:02:26 -07005086void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5087 TraverseLayersFunction traverseLayers, bool yswap,
5088 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005089 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005090
Lloyd Pique144e1162017-12-20 16:44:52 -08005091 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005092
5093 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005094 const auto raWidth = renderArea.getWidth();
5095 const auto raHeight = renderArea.getHeight();
5096
5097 const auto reqWidth = renderArea.getReqWidth();
5098 const auto reqHeight = renderArea.getReqHeight();
5099 Rect sourceCrop = renderArea.getSourceCrop();
5100
Iris Chang7501ed62018-04-30 14:45:42 +08005101 bool filtering = false;
5102 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5103 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5104 static_cast<int32_t>(reqHeight) != raWidth;
5105 } else {
5106 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5107 static_cast<int32_t>(reqHeight) != raHeight;
5108 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005109
Dan Stozac1879002014-05-22 15:59:05 -07005110 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005111 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005112 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005113 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005114 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5115 Transform tr;
5116 uint32_t flags = 0x00;
5117 switch (mPrimaryDisplayOrientation) {
5118 case DisplayState::eOrientation90:
5119 flags = Transform::ROT_90;
5120 break;
5121 case DisplayState::eOrientation180:
5122 flags = Transform::ROT_180;
5123 break;
5124 case DisplayState::eOrientation270:
5125 flags = Transform::ROT_270;
5126 break;
5127 }
5128 tr.set(flags, raWidth, raHeight);
5129 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005130 }
5131
5132 // ensure that sourceCrop is inside screen
5133 if (sourceCrop.left < 0) {
5134 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5135 }
chaviwa76b2712017-09-20 12:02:26 -07005136 if (sourceCrop.right > raWidth) {
5137 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005138 }
5139 if (sourceCrop.top < 0) {
5140 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5141 }
chaviwa76b2712017-09-20 12:02:26 -07005142 if (sourceCrop.bottom > raHeight) {
5143 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005144 }
5145
Chia-I Wu36574d92018-05-16 10:54:36 -07005146 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5147 engine.setOutputDataSpace(Dataspace::SRGB);
5148 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005149
Mathias Agopian180f10d2013-04-10 22:55:41 -07005150 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005151 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005152
Iris Chang7501ed62018-04-30 14:45:42 +08005153 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5154 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5155 // convert hw orientation into flag presentation
5156 // here inverse transform needed
5157 uint8_t hw_rot_90 = 0x00;
5158 uint8_t hw_flip_hv = 0x00;
5159 switch (mPrimaryDisplayOrientation) {
5160 case DisplayState::eOrientation90:
5161 hw_rot_90 = Transform::ROT_90;
5162 hw_flip_hv = Transform::ROT_180;
5163 break;
5164 case DisplayState::eOrientation180:
5165 hw_flip_hv = Transform::ROT_180;
5166 break;
5167 case DisplayState::eOrientation270:
5168 hw_rot_90 = Transform::ROT_90;
5169 break;
5170 }
5171
5172 // transform flags operation
5173 // 1) flip H V if both have ROT_90 flag
5174 // 2) XOR these flags
5175 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5176 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5177 if (rotation_rot_90 & hw_rot_90) {
5178 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5179 }
5180 rotation = static_cast<Transform::orientation_flags>
5181 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5182 }
5183
Mathias Agopian180f10d2013-04-10 22:55:41 -07005184 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005185 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005186 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005187 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005188
chaviw50da5042018-04-09 13:49:37 -07005189 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005190 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005191 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005192
chaviwa76b2712017-09-20 12:02:26 -07005193 traverseLayers([&](Layer* layer) {
5194 if (filtering) layer->setFiltering(true);
David Sodmanca10ed22018-04-16 14:10:25 -07005195 layer->drawNow(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005196 if (filtering) layer->setFiltering(false);
5197 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005198}
5199
chaviwa76b2712017-09-20 12:02:26 -07005200status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5201 TraverseLayersFunction traverseLayers,
5202 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005203 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005204 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005205 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005206 ATRACE_CALL();
5207
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005208 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005209
5210 traverseLayers([&](Layer* layer) {
5211 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5212 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005213
Robert Carr03480e22018-01-04 16:02:06 -08005214 // We allow the system server to take screenshots of secure layers for
5215 // use in situations like the Screen-rotation animation and place
5216 // the impetus on WindowManager to not persist them.
5217 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005218 ALOGW("FB is protected: PERMISSION_DENIED");
5219 return PERMISSION_DENIED;
5220 }
5221
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005222 // this binds the given EGLImage as a framebuffer for the
5223 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005224 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005225 if (bufferBond.getStatus() != NO_ERROR) {
5226 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005227 return INVALID_OPERATION;
5228 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005229
Dan Stozaabcda352017-06-01 14:37:39 -07005230 // this will in fact render into our dequeued buffer
5231 // via an FBO, which means we didn't have to create
5232 // an EGLSurface and therefore we're not
5233 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005234 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005235
Dan Stozaabcda352017-06-01 14:37:39 -07005236 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005237 getRenderEngine().finish();
5238 *outSyncFd = -1;
5239
chaviwa76b2712017-09-20 12:02:26 -07005240 const auto reqWidth = renderArea.getReqWidth();
5241 const auto reqHeight = renderArea.getReqHeight();
5242
Dan Stozaabcda352017-06-01 14:37:39 -07005243 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5244 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005245 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005246 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005247 } else {
5248 base::unique_fd syncFd = getRenderEngine().flush();
5249 if (syncFd < 0) {
5250 getRenderEngine().finish();
5251 }
5252 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005253 }
5254
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005255 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005256}
5257
Mathias Agopiand5556842013-09-19 17:08:37 -07005258void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005259 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005260 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005261 for (size_t y = 0; y < h; y++) {
5262 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5263 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005264 if (p[x] != 0xFF000000) return;
5265 }
5266 }
chaviwa76b2712017-09-20 12:02:26 -07005267 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005268
Robert Carr2047fae2016-11-28 14:09:09 -08005269 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005270 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005271 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005272 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5273 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5274 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5275 static_cast<float>(state.color.a));
5276 i++;
5277 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005278 }
5279}
5280
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005281// ---------------------------------------------------------------------------
5282
Dan Stoza412903f2017-04-27 13:42:17 -07005283void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5284 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005285}
5286
Dan Stoza412903f2017-04-27 13:42:17 -07005287void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5288 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005289}
5290
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005291void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5292 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005293 const LayerVector::Visitor& visitor) {
5294 // We loop through the first level of layers without traversing,
5295 // as we need to interpret min/max layer Z in the top level Z space.
5296 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005297 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005298 continue;
5299 }
5300 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005301 // relative layers are traversed in Layer::traverseInZOrder
5302 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005303 continue;
5304 }
5305 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005306 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005307 return;
5308 }
chaviwa76b2712017-09-20 12:02:26 -07005309 if (!layer->isVisible()) {
5310 return;
5311 }
5312 visitor(layer);
5313 });
5314 }
5315}
5316
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005317}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005318
Lloyd Pique074e8122018-07-26 12:57:23 -07005319
Mathias Agopian3f844832013-08-07 21:24:32 -07005320#if defined(__gl_h_)
5321#error "don't include gl/gl.h in this file"
5322#endif
5323
5324#if defined(__gl2_h_)
5325#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005326#endif