blob: d87df59dfad411ca25334ada2faec351338a5f73 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Chia-I Wud49d6692018-06-27 07:17:41 +080040#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060041#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070043#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080048#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070050
51#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Robert Carr578038f2018-03-09 12:25:24 -080065#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070066#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070067#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020070#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080072#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080073#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070081#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070082#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070083#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070084#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
Mathias Agopian875d8e12013-06-07 15:35:48 -070086#include "RenderEngine/RenderEngine.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070087#include "Scheduler/DispSync.h"
88#include "Scheduler/EventControlThread.h"
89#include "Scheduler/EventThread.h"
90
Mathias Agopianff2ed702013-09-01 21:36:12 -070091#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070092
Jiyong Park4b20c2e2017-01-14 19:45:11 +090093#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080094#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
95#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090096#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090097
chaviw1d044282017-09-27 12:19:28 -070098#include <layerproto/LayerProtoParser.h>
99
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800100#define DISPLAY_COUNT 1
101
Mathias Agopianfee2b462013-07-03 12:34:01 -0700102/*
103 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
104 * black pixels.
105 */
106#define DEBUG_SCREENSHOTS false
107
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800108namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700109
Jaesoo Lee43518572017-01-23 19:03:16 +0900110using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900111using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700112using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700113using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700114using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700115using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900116
Steven Thomasb02664d2017-07-26 18:48:28 -0700117namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700118
119#pragma clang diagnostic push
120#pragma clang diagnostic error "-Wswitch-enum"
121
122bool isWideColorMode(const ColorMode colorMode) {
123 switch (colorMode) {
124 case ColorMode::DISPLAY_P3:
125 case ColorMode::ADOBE_RGB:
126 case ColorMode::DCI_P3:
127 case ColorMode::BT2020:
128 case ColorMode::BT2100_PQ:
129 case ColorMode::BT2100_HLG:
130 return true;
131 case ColorMode::NATIVE:
132 case ColorMode::STANDARD_BT601_625:
133 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
134 case ColorMode::STANDARD_BT601_525:
135 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
136 case ColorMode::STANDARD_BT709:
137 case ColorMode::SRGB:
138 return false;
139 }
140 return false;
141}
142
143#pragma clang diagnostic pop
144
Steven Thomasb02664d2017-07-26 18:48:28 -0700145class ConditionalLock {
146public:
147 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
148 if (lock) {
149 mMutex.lock();
150 }
151 }
152 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
153private:
154 Mutex& mMutex;
155 bool mLocked;
156};
Peiyong Linfca547f2018-07-09 13:03:33 -0700157
Steven Thomasb02664d2017-07-26 18:48:28 -0700158} // namespace anonymous
159
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800160// ---------------------------------------------------------------------------
161
Mathias Agopian99b49842011-06-27 16:05:52 -0700162const String16 sHardwareTest("android.permission.HARDWARE_TEST");
163const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
164const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
165const String16 sDump("android.permission.DUMP");
166
167// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800168int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
169int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700170int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700171bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800172uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800173bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800174bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800175int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800176// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600177bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700178
Kalle Raitaa099a242017-01-11 11:17:29 -0800179
180std::string getHwcServiceName() {
181 char value[PROPERTY_VALUE_MAX] = {};
182 property_get("debug.sf.hwc_service_name", value, "default");
183 ALOGI("Using HWComposer service: '%s'", value);
184 return std::string(value);
185}
186
187bool useTrebleTestingOverride() {
188 char value[PROPERTY_VALUE_MAX] = {};
189 property_get("debug.sf.treble_testing_override", value, "false");
190 ALOGI("Treble testing override: '%s'", value);
191 return std::string(value) == "true";
192}
193
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800194std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
195 switch(displayColorSetting) {
196 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700197 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800198 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700199 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800200 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700201 return std::string("Enhanced");
202 default:
203 return std::string("Unknown ") +
204 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800205 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800206}
207
Lloyd Pique99d3da52018-01-22 17:48:03 -0800208NativeWindowSurface::~NativeWindowSurface() = default;
209
210namespace impl {
211
212class NativeWindowSurface final : public android::NativeWindowSurface {
213public:
214 static std::unique_ptr<android::NativeWindowSurface> create(
215 const sp<IGraphicBufferProducer>& producer) {
216 return std::make_unique<NativeWindowSurface>(producer);
217 }
218
219 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
220 : surface(new Surface(producer, false)) {}
221
222 ~NativeWindowSurface() override = default;
223
224private:
225 sp<ANativeWindow> getNativeWindow() const override { return surface; }
226
227 void preallocateBuffers() override { surface->allocateBuffers(); }
228
229 sp<Surface> surface;
230};
231
232} // namespace impl
233
David Sodmanbc815282017-11-05 18:57:52 -0800234SurfaceFlingerBE::SurfaceFlingerBE()
235 : mHwcServiceName(getHwcServiceName()),
236 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800237 mFrameBuckets(),
238 mTotalTime(0),
239 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800240 mComposerSequenceId(0) {
241}
242
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800243SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800244 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800245 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700246 mTransactionPending(false),
247 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700248 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700249 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700250 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800251 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700252 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800253 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800254 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800255 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800256 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700258 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700259 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700260 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700261 mDebugInSwapBuffers(0),
262 mLastSwapBufferTime(0),
263 mDebugInTransaction(0),
264 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700265 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700266 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700267 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800268 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800269 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700270 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800271 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800272 mCreateBufferQueue(&BufferQueue::createBufferQueue),
273 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800274
275SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800276 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800277
278 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
279 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
280
281 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
282 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
283
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800284 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
285 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800286
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700287 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
288 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
289
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700290 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
291 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
292
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800293 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
294 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
295
Steven Thomas050b2c82017-03-06 11:45:16 -0800296 // Vr flinger is only enabled on Daydream ready devices.
297 useVrFlinger = getBool< ISurfaceFlingerConfigs,
298 &ISurfaceFlingerConfigs::useVrFlinger>(false);
299
Fabien Sanglard1971b632017-03-10 14:50:03 -0800300 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
301 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
302
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600303 hasWideColorDisplay =
304 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
305
Iris Chang7501ed62018-04-30 14:45:42 +0800306 V1_1::DisplayOrientation primaryDisplayOrientation =
307 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
308 V1_1::DisplayOrientation::ORIENTATION_0);
309
310 switch (primaryDisplayOrientation) {
311 case V1_1::DisplayOrientation::ORIENTATION_90:
312 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
313 break;
314 case V1_1::DisplayOrientation::ORIENTATION_180:
315 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
316 break;
317 case V1_1::DisplayOrientation::ORIENTATION_270:
318 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
319 break;
320 default:
321 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
322 break;
323 }
324 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
325
Lloyd Pique41be5d22018-06-21 13:11:48 -0700326 // Note: We create a local temporary with the real DispSync implementation
327 // type temporarily so we can initialize it with the configured values,
328 // before storing it for more generic use using the interface type.
329 auto primaryDispSync = std::make_unique<impl::DispSync>("PrimaryDispSync");
330 primaryDispSync->init(SurfaceFlinger::hasSyncFramework,
331 SurfaceFlinger::dispSyncPresentTimeOffset);
332 mPrimaryDispSync = std::move(primaryDispSync);
Saurabh Shahf4174532017-07-13 10:45:07 -0700333
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800334 // debugging stuff...
335 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700336
Mathias Agopianb4b17302013-03-20 18:36:41 -0700337 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700338 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700339
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800340 property_get("debug.sf.showupdates", value, "0");
341 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700342
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700343 property_get("debug.sf.ddms", value, "0");
344 mDebugDDMS = atoi(value);
345 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700346 if (!startDdmConnection()) {
347 // start failed, and DDMS debugging not enabled
348 mDebugDDMS = 0;
349 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700350 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700351 ALOGI_IF(mDebugRegion, "showupdates enabled");
352 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700353
354 property_get("debug.sf.disable_backpressure", value, "0");
355 mPropagateBackpressure = !atoi(value);
356 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700357
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800358 property_get("debug.sf.enable_hwc_vds", value, "0");
359 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800360 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800361
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800362 property_get("ro.sf.disable_triple_buffer", value, "1");
363 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800364 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700365
Yiwei Zhang243b3782018-05-15 17:40:04 -0700366 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700367 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
368 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
369
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200370 property_get("debug.sf.early_phase_offset_ns", value, "-1");
371 const int earlySfOffsetNs = atoi(value);
372
373 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
374 const int earlyGlSfOffsetNs = atoi(value);
375
376 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
377 const int earlyAppOffsetNs = atoi(value);
378
379 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
380 const int earlyGlAppOffsetNs = atoi(value);
381
382 const VSyncModulator::Offsets earlyOffsets =
383 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
384 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
385 const VSyncModulator::Offsets earlyGlOffsets =
386 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
387 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
388 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
389 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700390
Romain Guy11d63f42017-07-20 12:47:14 -0700391 // We should be reading 'persist.sys.sf.color_saturation' here
392 // but since /data may be encrypted, we need to wait until after vold
393 // comes online to attempt to read the property. The property is
394 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800395
396 if (useTrebleTestingOverride()) {
397 // Without the override SurfaceFlinger cannot connect to HIDL
398 // services that are not listed in the manifests. Considered
399 // deriving the setting from the set service name, but it
400 // would be brittle if the name that's not 'default' is used
401 // for production purposes later on.
402 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
403 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800404}
405
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800406void SurfaceFlinger::onFirstRef()
407{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800408 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800409}
410
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800411SurfaceFlinger::~SurfaceFlinger()
412{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800413}
414
Dan Stozac7014012014-02-14 15:03:43 -0800415void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800416{
417 // the window manager died on us. prepare its eulogy.
418
Andy McFadden13a082e2012-08-24 10:16:42 -0700419 // restore initial conditions (default device unblank, etc)
420 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800421
422 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700423 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800424}
425
Robert Carr1db73f62016-12-21 12:58:51 -0800426static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700427 status_t err = client->initCheck();
428 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800429 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800430 }
Robert Carr1db73f62016-12-21 12:58:51 -0800431 return nullptr;
432}
433
434sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
435 return initClient(new Client(this));
436}
437
438sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
439 const sp<IGraphicBufferProducer>& gbp) {
440 if (authenticateSurfaceTexture(gbp) == false) {
441 return nullptr;
442 }
443 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
444 if (layer == nullptr) {
445 return nullptr;
446 }
447
448 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800449}
450
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700451sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
452 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700453{
454 class DisplayToken : public BBinder {
455 sp<SurfaceFlinger> flinger;
456 virtual ~DisplayToken() {
457 // no more references, this display must be terminated
458 Mutex::Autolock _l(flinger->mStateLock);
459 flinger->mCurrentState.displays.removeItem(this);
460 flinger->setTransactionFlags(eDisplayTransactionNeeded);
461 }
462 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700463 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700464 : flinger(flinger) {
465 }
466 };
467
468 sp<BBinder> token = new DisplayToken(this);
469
470 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700471 DisplayDeviceState info;
472 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700473 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700474 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700475 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800476 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700477 return token;
478}
479
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700480void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700481 Mutex::Autolock _l(mStateLock);
482
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700483 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700484 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700485 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700486 return;
487 }
488
489 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700490 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700491 ALOGE("destroyDisplay called for non-virtual display");
492 return;
493 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700494 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700495 mCurrentState.displays.removeItemsAt(idx);
496 setTransactionFlags(eDisplayTransactionNeeded);
497}
498
Mathias Agopiane57f2922012-08-09 16:29:12 -0700499sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700500 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700501 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800502 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700503 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700504 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700505}
506
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800507void SurfaceFlinger::bootFinished()
508{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700509 if (mStartPropertySetThread->join() != NO_ERROR) {
510 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800511 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800512 const nsecs_t now = systemTime();
513 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000514 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700515
516 // wait patiently for the window manager death
517 const String16 name("window");
518 sp<IBinder> window(defaultServiceManager()->getService(name));
519 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700520 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700521 }
522
Steven Thomas050b2c82017-03-06 11:45:16 -0800523 if (mVrFlinger) {
524 mVrFlinger->OnBootFinished();
525 }
526
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700527 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700528 // formerly we would just kill the process, but we now ask it to exit so it
529 // can choose where to stop the animation.
530 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700531
532 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
533 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
534 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700535
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800536 postMessageAsync(new LambdaMessage([this] {
537 readPersistentProperties();
538 mBootStage = BootStage::FINISHED;
539 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800540}
541
Dan Stoza436ccf32018-06-21 12:10:12 -0700542uint32_t SurfaceFlinger::getNewTexture() {
543 {
544 std::lock_guard lock(mTexturePoolMutex);
545 if (!mTexturePool.empty()) {
546 uint32_t name = mTexturePool.back();
547 mTexturePool.pop_back();
548 ATRACE_INT("TexturePoolSize", mTexturePool.size());
549 return name;
550 }
551
552 // The pool was too small, so increase it for the future
553 ++mTexturePoolSize;
554 }
555
556 // The pool was empty, so we need to get a new texture name directly using a
557 // blocking call to the main thread
558 uint32_t name = 0;
559 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
560 return name;
561}
562
Mathias Agopian3f844832013-08-07 21:24:32 -0700563void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700564 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700565}
566
Lloyd Piquee83f9312018-02-01 12:53:17 -0800567class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700568public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700569 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000570 const char* name) :
571 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700572 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700573 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000574 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
575 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700576 mDispSync(dispSync),
577 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700578 mVsyncMutex(),
579 mPhaseOffset(phaseOffset),
580 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700581
Lloyd Piquee83f9312018-02-01 12:53:17 -0800582 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700583
Lloyd Piquee83f9312018-02-01 12:53:17 -0800584 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700585 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700586 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000587 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700588 static_cast<DispSync::Callback*>(this));
589 if (err != NO_ERROR) {
590 ALOGE("error registering vsync callback: %s (%d)",
591 strerror(-err), err);
592 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700593 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700594 } else {
595 status_t err = mDispSync->removeEventListener(
596 static_cast<DispSync::Callback*>(this));
597 if (err != NO_ERROR) {
598 ALOGE("error unregistering vsync callback: %s (%d)",
599 strerror(-err), err);
600 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700601 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700602 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700603 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700604 }
605
Lloyd Piquee83f9312018-02-01 12:53:17 -0800606 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700607 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700608 mCallback = callback;
609 }
610
Lloyd Piquee83f9312018-02-01 12:53:17 -0800611 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700612 Mutex::Autolock lock(mVsyncMutex);
613
614 // Normalize phaseOffset to [0, period)
615 auto period = mDispSync->getPeriod();
616 phaseOffset %= period;
617 if (phaseOffset < 0) {
618 // If we're here, then phaseOffset is in (-period, 0). After this
619 // operation, it will be in (0, period)
620 phaseOffset += period;
621 }
622 mPhaseOffset = phaseOffset;
623
624 // If we're not enabled, we don't need to mess with the listeners
625 if (!mEnabled) {
626 return;
627 }
628
Dan Stoza84d619e2018-03-28 17:07:36 -0700629 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
630 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700631 if (err != NO_ERROR) {
Dan Stoza84d619e2018-03-28 17:07:36 -0700632 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700633 strerror(-err), err);
634 }
635 }
636
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700637private:
638 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800639 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700640 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700641 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700642 callback = mCallback;
643
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700644 if (mTraceVsync) {
645 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700646 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700647 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700648 }
649
Peiyong Lin566a3b42018-01-09 18:22:43 -0800650 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700651 callback->onVSyncEvent(when);
652 }
653 }
654
Tim Murray4a4e4a22016-04-19 16:29:23 +0000655 const char* const mName;
656
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700657 int mValue;
658
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700659 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700660 const String8 mVsyncOnLabel;
661 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700662
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700663 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700664
665 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800666 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700667
668 Mutex mVsyncMutex; // Protects the following
669 nsecs_t mPhaseOffset;
670 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700671};
672
Lloyd Piquee83f9312018-02-01 12:53:17 -0800673class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700674public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800675 InjectVSyncSource() = default;
676 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700677
Lloyd Piquee83f9312018-02-01 12:53:17 -0800678 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700679 std::lock_guard<std::mutex> lock(mCallbackMutex);
680 mCallback = callback;
681 }
682
Lloyd Piquee83f9312018-02-01 12:53:17 -0800683 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700684 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700685 if (mCallback) {
686 mCallback->onVSyncEvent(when);
687 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700688 }
689
Lloyd Piquee83f9312018-02-01 12:53:17 -0800690 void setVSyncEnabled(bool) override {}
691 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700692
693private:
694 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800695 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700696};
697
Wei Wangf9b05ee2017-07-19 20:59:39 -0700698// Do not call property_set on main thread which will be blocked by init
699// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700700void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700701 ALOGI( "SurfaceFlinger's main thread ready to run. "
702 "Initializing graphics H/W...");
703
Thierry Strudel2924d012017-08-14 15:19:37 -0700704 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900705
Steven Thomasb02664d2017-07-26 18:48:28 -0700706 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800707
Steven Thomasb02664d2017-07-26 18:48:28 -0700708 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800709 mEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700710 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
711 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800712 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700713 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800714 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800715 "appEventThread");
716 mSfEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700717 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800718 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800719
Lloyd Pique24b0a482018-03-09 18:52:26 -0800720 mSFEventThread =
721 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700722 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800723 [this](nsecs_t timestamp) {
724 mInterceptor->saveVSyncEvent(timestamp);
725 },
726 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800727 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200728 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800729
Steven Thomasb02664d2017-07-26 18:48:28 -0700730 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800731 getBE().mRenderEngine =
732 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
733 hasWideColorDisplay
734 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
735 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800736 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700737
738 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
739 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800740 getBE().mHwc.reset(
741 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700742 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800743 // Process any initial hotplug and resulting display changes.
744 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700745 const auto display = getDefaultDisplayDeviceLocked();
746 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
747 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
748 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800749
Lloyd Piquefcd86612017-12-14 17:15:36 -0800750 // make the default display GLContext current so that we can create textures
751 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700752 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800753
Steven Thomas050b2c82017-03-06 11:45:16 -0800754 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700755 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700756 // This callback is called from the vr flinger dispatch thread. We
757 // need to call signalTransaction(), which requires holding
758 // mStateLock when we're not on the main thread. Acquiring
759 // mStateLock from the vr flinger dispatch thread might trigger a
760 // deadlock in surface flinger (see b/66916578), so post a message
761 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700762 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700763 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
764 mVrFlingerRequestsDisplay = requestDisplay;
765 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700766 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800767 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700768 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
769 getHwComposer()
770 .getHwcDisplayId(display->getId())
771 .value_or(0),
772 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800773 if (!mVrFlinger) {
774 ALOGE("Failed to start vrflinger");
775 }
776 }
777
Lloyd Pique379adc12018-01-22 17:31:47 -0800778 mEventControlThread = std::make_unique<impl::EventControlThread>(
779 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700780
Mathias Agopian92a979a2012-08-02 18:32:23 -0700781 // initialize our drawing state
782 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700783
Andy McFadden13a082e2012-08-24 10:16:42 -0700784 // set initial conditions (e.g. unblank default device)
785 initializeDisplays();
786
David Sodmanbc815282017-11-05 18:57:52 -0800787 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700788
Wei Wangf9b05ee2017-07-19 20:59:39 -0700789 // Inform native graphics APIs whether the present timestamp is supported:
790 if (getHwComposer().hasCapability(
791 HWC2::Capability::PresentFenceIsNotReliable)) {
792 mStartPropertySetThread = new StartPropertySetThread(false);
793 } else {
794 mStartPropertySetThread = new StartPropertySetThread(true);
795 }
796
797 if (mStartPropertySetThread->Start() != NO_ERROR) {
798 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800799 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800800
Chia-I Wud49d6692018-06-27 07:17:41 +0800801 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
802 // is used to saturate legacy sRGB content. However, to make sure the same color under
803 // Display P3 will be saturated to the same color, we intentionally break the API spec
804 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
805 // such saturation matrix on Display P3 is understood fully, the API should always return
806 // identify matrix.
807 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
808 Dataspace::SRGB_LINEAR);
809
810 // we will apply this on Display P3.
811 if (mEnhancedSaturationMatrix != mat4()) {
812 ColorSpace srgb(ColorSpace::sRGB());
813 ColorSpace displayP3(ColorSpace::DisplayP3());
814 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
815 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
816 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
817 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800818
Dan Stoza9e56aa02015-11-02 13:00:03 -0800819 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700820}
821
Romain Guy11d63f42017-07-20 12:47:14 -0700822void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700823 Mutex::Autolock _l(mStateLock);
824
Romain Guy11d63f42017-07-20 12:47:14 -0700825 char value[PROPERTY_VALUE_MAX];
826
827 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800828 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700829 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800830 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100831
832 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700833 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700834}
835
Mathias Agopiana67e4182012-06-19 17:26:12 -0700836void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800837 // Start boot animation service by setting a property mailbox
838 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700839 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800840 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700841 if (mStartPropertySetThread->join() != NO_ERROR) {
842 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800843 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700844}
845
Mathias Agopian875d8e12013-06-07 15:35:48 -0700846size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800847 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700848}
849
Mathias Agopian875d8e12013-06-07 15:35:48 -0700850size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800851 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700852}
853
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800854// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800855
Jamie Gennis582270d2011-08-17 18:19:00 -0700856bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800857 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800858 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800859 return authenticateSurfaceTextureLocked(bufferProducer);
860}
861
862bool SurfaceFlinger::authenticateSurfaceTextureLocked(
863 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800864 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800865 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800866}
867
Brian Anderson6b376712017-04-04 10:51:39 -0700868status_t SurfaceFlinger::getSupportedFrameTimestamps(
869 std::vector<FrameEvent>* outSupported) const {
870 *outSupported = {
871 FrameEvent::REQUESTED_PRESENT,
872 FrameEvent::ACQUIRE,
873 FrameEvent::LATCH,
874 FrameEvent::FIRST_REFRESH_START,
875 FrameEvent::LAST_REFRESH_START,
876 FrameEvent::GPU_COMPOSITION_DONE,
877 FrameEvent::DEQUEUE_READY,
878 FrameEvent::RELEASE,
879 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700880 ConditionalLock _l(mStateLock,
881 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700882 if (!getHwComposer().hasCapability(
883 HWC2::Capability::PresentFenceIsNotReliable)) {
884 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
885 }
886 return NO_ERROR;
887}
888
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700889status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
890 Vector<DisplayInfo>* configs) {
891 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700892 return BAD_VALUE;
893 }
894
Jesse Hall692c7232012-11-08 15:41:56 -0800895 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700896 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
897 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700898 type = i;
899 break;
900 }
901 }
902
903 if (type < 0) {
904 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700905 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700906
Mathias Agopian8b736f12012-08-13 17:54:26 -0700907 // TODO: Not sure if display density should handled by SF any longer
908 class Density {
909 static int getDensityFromProperty(char const* propName) {
910 char property[PROPERTY_VALUE_MAX];
911 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800912 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700913 density = atoi(property);
914 }
915 return density;
916 }
917 public:
918 static int getEmuDensity() {
919 return getDensityFromProperty("qemu.sf.lcd_density"); }
920 static int getBuildDensity() {
921 return getDensityFromProperty("ro.sf.lcd_density"); }
922 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700923
Dan Stoza7f7da322014-05-02 15:26:25 -0700924 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700925
Steven Thomas6d8110b2017-08-31 18:24:21 -0700926 ConditionalLock _l(mStateLock,
927 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800928 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700929 DisplayInfo info = DisplayInfo();
930
Dan Stoza9e56aa02015-11-02 13:00:03 -0800931 float xdpi = hwConfig->getDpiX();
932 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700933
934 if (type == DisplayDevice::DISPLAY_PRIMARY) {
935 // The density of the device is provided by a build property
936 float density = Density::getBuildDensity() / 160.0f;
937 if (density == 0) {
938 // the build doesn't provide a density -- this is wrong!
939 // use xdpi instead
940 ALOGE("ro.sf.lcd_density must be defined as a build property");
941 density = xdpi / 160.0f;
942 }
943 if (Density::getEmuDensity()) {
944 // if "qemu.sf.lcd_density" is specified, it overrides everything
945 xdpi = ydpi = density = Density::getEmuDensity();
946 density /= 160.0f;
947 }
948 info.density = density;
949
950 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700951 const auto display = getDefaultDisplayDeviceLocked();
952 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700953 } else {
954 // TODO: where should this value come from?
955 static const int TV_DENSITY = 213;
956 info.density = TV_DENSITY / 160.0f;
957 info.orientation = 0;
958 }
959
Dan Stoza9e56aa02015-11-02 13:00:03 -0800960 info.w = hwConfig->getWidth();
961 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700962 info.xdpi = xdpi;
963 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800964 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900965 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800966
Andy McFadden91b2ca82014-06-13 14:04:23 -0700967 // This is how far in advance a buffer must be queued for
968 // presentation at a given time. If you want a buffer to appear
969 // on the screen at time N, you must submit the buffer before
970 // (N - presentationDeadline).
971 //
972 // Normally it's one full refresh period (to give SF a chance to
973 // latch the buffer), but this can be reduced by configuring a
974 // DispSync offset. Any additional delays introduced by the hardware
975 // composer or panel must be accounted for here.
976 //
977 // We add an additional 1ms to allow for processing time and
978 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800979 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800980 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700981
982 // All non-virtual displays are currently considered secure.
983 info.secure = true;
984
Iris Chang7501ed62018-04-30 14:45:42 +0800985 if (type == DisplayDevice::DISPLAY_PRIMARY &&
986 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
987 std::swap(info.w, info.h);
988 }
989
Michael Wright28f24d02016-07-12 13:30:53 -0700990 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700991 }
992
Dan Stoza7f7da322014-05-02 15:26:25 -0700993 return NO_ERROR;
994}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700995
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700996status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
997 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700998 return BAD_VALUE;
999 }
1000
1001 // FIXME for now we always return stats for the primary display
1002 memset(stats, 0, sizeof(*stats));
Lloyd Pique41be5d22018-06-21 13:11:48 -07001003 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1004 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001005 return NO_ERROR;
1006}
1007
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001008int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
1009 const auto display = getDisplayDevice(displayToken);
1010 if (!display) {
1011 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +08001012 return BAD_VALUE;
1013 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001014
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001015 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -07001016}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001017
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001018void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
1019 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001020 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001021 return;
1022 }
1023
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001024 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001025 ALOGW("Trying to set config for virtual display");
1026 return;
1027 }
1028
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001029 display->setActiveConfig(mode);
1030 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001031}
1032
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001033status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001034 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001035 Vector<DisplayInfo> configs;
1036 getDisplayConfigs(displayToken, &configs);
1037 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
1038 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
1039 configs.size());
1040 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001041 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001042 const auto display = getDisplayDevice(displayToken);
1043 if (!display) {
1044 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
1045 displayToken.get());
1046 } else if (display->isVirtual()) {
1047 ALOGW("Attempt to set active config %d for virtual display", mode);
1048 } else {
1049 setActiveConfigInternal(display, mode);
1050 }
1051 }));
1052
Mathias Agopian888c8222012-08-04 21:10:38 -07001053 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001054}
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001055status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1056 Vector<ColorMode>* outColorModes) {
1057 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001058 return BAD_VALUE;
1059 }
1060
Michael Wright28f24d02016-07-12 13:30:53 -07001061 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001062 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
1063 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -07001064 type = i;
1065 break;
1066 }
1067 }
1068
1069 if (type < 0) {
1070 return type;
1071 }
1072
Peiyong Lina52f0292018-03-14 17:26:31 -07001073 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001074 {
1075 ConditionalLock _l(mStateLock,
1076 std::this_thread::get_id() != mMainThreadId);
1077 modes = getHwComposer().getColorModes(type);
1078 }
Michael Wright28f24d02016-07-12 13:30:53 -07001079 outColorModes->clear();
1080 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1081
1082 return NO_ERROR;
1083}
1084
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001085ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1086 if (const auto display = getDisplayDevice(displayToken)) {
1087 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001088 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001089 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001090}
1091
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001092void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1093 Dataspace dataSpace, RenderIntent renderIntent) {
1094 ColorMode currentMode = display->getActiveColorMode();
1095 Dataspace currentDataSpace = display->getCompositionDataSpace();
1096 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001097
Peiyong Lin38e9a562018-04-10 16:24:20 -07001098 if (mode == currentMode && dataSpace == currentDataSpace &&
1099 renderIntent == currentRenderIntent) {
1100 return;
1101 }
1102
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001103 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001104 ALOGW("Trying to set config for virtual display");
1105 return;
1106 }
1107
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001108 display->setActiveColorMode(mode);
1109 display->setCompositionDataSpace(dataSpace);
1110 display->setActiveRenderIntent(renderIntent);
1111 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001112
1113 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001114 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1115 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001116}
1117
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001118status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001119 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001120 Vector<ColorMode> modes;
1121 getDisplayColorModes(displayToken, &modes);
1122 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1123 if (mode < ColorMode::NATIVE || !exists) {
1124 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1125 decodeColorMode(mode).c_str(), mode, displayToken.get());
1126 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001127 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001128 const auto display = getDisplayDevice(displayToken);
1129 if (!display) {
1130 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1131 decodeColorMode(mode).c_str(), mode, displayToken.get());
1132 } else if (display->isVirtual()) {
1133 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1134 decodeColorMode(mode).c_str(), mode);
1135 } else {
1136 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1137 RenderIntent::COLORIMETRIC);
1138 }
1139 }));
1140
Michael Wright28f24d02016-07-12 13:30:53 -07001141 return NO_ERROR;
1142}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001143
Svetoslavd85084b2014-03-20 10:28:31 -07001144status_t SurfaceFlinger::clearAnimationFrameStats() {
1145 Mutex::Autolock _l(mStateLock);
1146 mAnimFrameTracker.clearStats();
1147 return NO_ERROR;
1148}
1149
1150status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1151 Mutex::Autolock _l(mStateLock);
1152 mAnimFrameTracker.getStats(outStats);
1153 return NO_ERROR;
1154}
1155
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001156status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1157 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001158 Mutex::Autolock _l(mStateLock);
1159
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001160 const auto display = getDisplayDeviceLocked(displayToken);
1161 if (!display) {
1162 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001163 return BAD_VALUE;
1164 }
1165
Peiyong Linfb069302018-04-25 14:34:31 -07001166 // At this point the DisplayDeivce should already be set up,
1167 // meaning the luminance information is already queried from
1168 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001169 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001170 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1171 capabilities.getDesiredMaxLuminance(),
1172 capabilities.getDesiredMaxAverageLuminance(),
1173 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001174
1175 return NO_ERROR;
1176}
1177
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001178status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001179 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001180 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001181
Chia-I Wu90f669f2017-10-05 14:24:41 -07001182 if (mInjectVSyncs == enable) {
1183 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001184 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001185
1186 if (enable) {
1187 ALOGV("VSync Injections enabled");
1188 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001189 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001190 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001191 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001192 impl::EventThread::InterceptVSyncsCallback(),
1193 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001194 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001195 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001196 } else {
1197 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001198 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001199 }
1200
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001201 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001202 }));
1203
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001204 return NO_ERROR;
1205}
1206
1207status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001208 Mutex::Autolock _l(mStateLock);
1209
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001210 if (!mInjectVSyncs) {
1211 ALOGE("VSync Injections not enabled");
1212 return BAD_VALUE;
1213 }
1214 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1215 ALOGV("Injecting VSync inside SurfaceFlinger");
1216 mVSyncInjector->onInjectSyncEvent(when);
1217 }
1218 return NO_ERROR;
1219}
1220
Lloyd Pique755e3192018-01-31 16:46:15 -08001221status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1222 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001223 // Try to acquire a lock for 1s, fail gracefully
1224 const status_t err = mStateLock.timedLock(s2ns(1));
1225 const bool locked = (err == NO_ERROR);
1226 if (!locked) {
1227 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1228 return TIMED_OUT;
1229 }
1230
1231 outLayers->clear();
1232 mCurrentState.traverseInZOrder([&](Layer* layer) {
1233 outLayers->push_back(layer->getLayerDebugInfo());
1234 });
1235
1236 mStateLock.unlock();
1237 return NO_ERROR;
1238}
1239
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001240// ----------------------------------------------------------------------------
1241
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001242sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1243 ISurfaceComposer::VsyncSource vsyncSource) {
1244 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1245 return mSFEventThread->createEventConnection();
1246 } else {
1247 return mEventThread->createEventConnection();
1248 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001249}
1250
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001251// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001252
1253void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001254 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001255}
1256
1257void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001258 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001259}
1260
1261void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001262 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001263}
1264
1265void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001266 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001267 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001268}
1269
1270status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001271 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001272 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001273}
1274
1275status_t SurfaceFlinger::postMessageSync(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 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001278 if (res == NO_ERROR) {
1279 msg->wait();
1280 }
1281 return res;
1282}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001283
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001284void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001285 do {
1286 waitForEvent();
1287 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001288}
1289
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001290void SurfaceFlinger::enableHardwareVsync() {
1291 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001292 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001293 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001294 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001295 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001296 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001297}
1298
Jesse Hall948fe0c2013-10-14 12:56:09 -07001299void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001300 Mutex::Autolock _l(mHWVsyncLock);
1301
Jesse Hall948fe0c2013-10-14 12:56:09 -07001302 if (makeAvailable) {
1303 mHWVsyncAvailable = true;
1304 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001305 // Hardware vsync is not currently available, so abort the resync
1306 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001307 return;
1308 }
1309
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001310 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1311 if (!getHwComposer().isConnected(displayId)) {
1312 return;
1313 }
1314
1315 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001316 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001317
Lloyd Pique41be5d22018-06-21 13:11:48 -07001318 mPrimaryDispSync->reset();
1319 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001320
1321 if (!mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001322 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001323 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001324 mPrimaryHWVsyncEnabled = true;
1325 }
1326}
1327
Jesse Hall948fe0c2013-10-14 12:56:09 -07001328void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001329 Mutex::Autolock _l(mHWVsyncLock);
1330 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001331 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001332 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001333 mPrimaryHWVsyncEnabled = false;
1334 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001335 if (makeUnavailable) {
1336 mHWVsyncAvailable = false;
1337 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001338}
1339
Tim Murray4a4e4a22016-04-19 16:29:23 +00001340void SurfaceFlinger::resyncWithRateLimit() {
1341 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001342
1343 // No explicit locking is needed here since EventThread holds a lock while calling this method
1344 static nsecs_t sLastResyncAttempted = 0;
1345 const nsecs_t now = systemTime();
1346 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001347 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001348 }
Dan Stoza57164302017-05-08 14:03:54 -07001349 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001350}
1351
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001352void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1353 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001354 ATRACE_NAME("SF onVsync");
1355
Steven Thomas3cfac282017-02-06 12:29:30 -08001356 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001357 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001358 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001359 return;
1360 }
1361
1362 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001363 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001364 return;
1365 }
1366
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001367 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1368 // For now, we don't do anything with external display vsyncs.
1369 return;
1370 }
1371
Jamie Gennisd1700752013-10-14 12:22:52 -07001372 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001373
Jamie Gennisd1700752013-10-14 12:22:52 -07001374 { // Scope for the lock
1375 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001376 if (mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001377 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001378 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001379 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001380
1381 if (needsHwVsync) {
1382 enableHardwareVsync();
1383 } else {
1384 disableHardwareVsync(false);
1385 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001386}
1387
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001388void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001389 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1390 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001391}
1392
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001393void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001394 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001395 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001396 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001397
Lloyd Piqueba04e622017-12-14 17:11:26 -08001398 // Ignore events that do not have the right sequenceId.
1399 if (sequenceId != getBE().mComposerSequenceId) {
1400 return;
1401 }
1402
Steven Thomasb02664d2017-07-26 18:48:28 -07001403 // Only lock if we're not on the main thread. This function is normally
1404 // called on a hwbinder thread, but for the primary display it's called on
1405 // the main thread with the state lock already held, so don't attempt to
1406 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001407 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001408
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001409 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001410
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001411 if (std::this_thread::get_id() == mMainThreadId) {
1412 // Process all pending hot plug events immediately if we are on the main thread.
1413 processDisplayHotplugEventsLocked();
1414 }
1415
Lloyd Piqueba04e622017-12-14 17:11:26 -08001416 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001417}
1418
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001419void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001420 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001421 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001422 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001423 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001424 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001425}
1426
Dan Stoza9e56aa02015-11-02 13:00:03 -08001427void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001428 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001429 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001430 getHwComposer().setVsyncEnabled(disp,
1431 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001432}
1433
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001434// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001435void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001436 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001437 // Clear the drawing state so that the logic inside of
1438 // handleTransactionLocked will fire. It will determine the delta between
1439 // mCurrentState and mDrawingState and re-apply all changes when we make the
1440 // transition.
1441 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001442 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001443 mDisplays.clear();
1444}
1445
Steven Thomas050b2c82017-03-06 11:45:16 -08001446void SurfaceFlinger::updateVrFlinger() {
1447 if (!mVrFlinger)
1448 return;
1449 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001450 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001451 return;
1452 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001453
David Sodman105b7dc2017-11-04 20:28:14 -07001454 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001455 ALOGE("Vr flinger is only supported for remote hardware composer"
1456 " service connections. Ignoring request to transition to vr"
1457 " flinger.");
1458 mVrFlingerRequestsDisplay = false;
1459 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001460 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001461
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001462 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001463
Steven Thomas0123ac62018-07-12 11:32:34 -07001464 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001465 LOG_ALWAYS_FATAL_IF(!display);
1466 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001467 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1468 // called below. Clear the reference now so we don't accidentally use it
1469 // later.
1470 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001471
Steven Thomasb02664d2017-07-26 18:48:28 -07001472 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001473 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001474 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001475
Steven Thomasb02664d2017-07-26 18:48:28 -07001476 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001477 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001478 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1479 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001480 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001481
David Sodman105b7dc2017-11-04 20:28:14 -07001482 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1483 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001484
1485 if (vrFlingerRequestsDisplay) {
1486 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001487 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001488
1489 mVisibleRegionsDirty = true;
1490 invalidateHwcGeometry();
1491
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001492 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001493 display = getDefaultDisplayDeviceLocked();
1494 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001495 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001496
Steven Thomasb02664d2017-07-26 18:48:28 -07001497 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001498 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001499 const nsecs_t period = activeConfig->getVsyncPeriod();
1500 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001501
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001502 // The present fences returned from vr_hwc are not an accurate
1503 // representation of vsync times.
Lloyd Pique41be5d22018-06-21 13:11:48 -07001504 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1505 !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001506
Steven Thomasb02664d2017-07-26 18:48:28 -07001507 // Use phase of 0 since phase is not known.
1508 // Use latency of 0, which will snap to the ideal latency.
1509 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001510
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001511 resyncToHardwareVsync(false);
1512
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001513 android_atomic_or(1, &mRepaintEverything);
1514 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001515}
1516
Mathias Agopian4fec8732012-06-29 14:12:52 -07001517void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001518 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001519 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001520 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001521 bool frameMissed = !mHadClientComposition &&
1522 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001523 (mPreviousPresentFence->getSignalTime() ==
1524 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001525 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001526 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001527 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001528 mTimeStats.incrementMissedFrames();
1529 if (mPropagateBackpressure) {
1530 signalLayerUpdate();
1531 break;
1532 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001533 }
Dan Stoza50182882016-07-08 12:02:20 -07001534
Steven Thomas050b2c82017-03-06 11:45:16 -08001535 // Now that we're going to make it to the handleMessageTransaction()
1536 // call below it's safe to call updateVrFlinger(), which will
1537 // potentially trigger a display handoff.
1538 updateVrFlinger();
1539
Dan Stoza6b9454d2014-11-07 16:00:59 -08001540 bool refreshNeeded = handleMessageTransaction();
1541 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001542 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001543 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001544 // Signal a refresh if a transaction modified the window state,
1545 // a new buffer was latched, or if HWC has requested a full
1546 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001547 signalRefresh();
1548 }
1549 break;
1550 }
1551 case MessageQueue::REFRESH: {
1552 handleMessageRefresh();
1553 break;
1554 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001555 }
1556}
1557
Dan Stoza6b9454d2014-11-07 16:00:59 -08001558bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001559 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001560 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001561 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001562 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001563 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001564 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001565}
1566
Dan Stoza6b9454d2014-11-07 16:00:59 -08001567bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001568 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001569 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001570}
1571
1572void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001573 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001574
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001575 mRefreshPending = false;
1576
Lloyd Pique074e8122018-07-26 12:57:23 -07001577 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1578
1579 preComposition(refreshStartTime);
1580 rebuildLayerStacks();
1581 setUpHWComposer();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001582 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001583 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001584 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001585 doComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001586 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001587
Dan Stozabfbffeb2016-07-21 14:49:33 -07001588 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001589 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001590 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001591 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001592 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001593 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001594
Dan Stoza9e56aa02015-11-02 13:00:03 -08001595 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001596}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001597
Mathias Agopiancd60f992012-08-16 16:28:27 -07001598void SurfaceFlinger::doDebugFlashRegions()
1599{
1600 // is debugging enabled
1601 if (CC_LIKELY(!mDebugRegion))
1602 return;
1603
1604 const bool repaintEverything = mRepaintEverything;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001605 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001606 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001607 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001608 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001609 if (!dirtyRegion.isEmpty()) {
1610 // redraw the whole screen
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001611 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001612
1613 // and draw the dirty region
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001614 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001615 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001616 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1617
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001618 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001619 }
1620 }
1621 }
1622
1623 postFramebuffer();
1624
1625 if (mDebugRegion > 1) {
1626 usleep(mDebugRegion * 1000);
1627 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001628
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001629 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001630 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001631 continue;
1632 }
1633
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001634 status_t result = display->prepareFrame(*getBE().mHwc);
1635 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001636 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001637 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001638}
1639
Adrian Roos1e1a1282017-11-01 19:05:31 +01001640void SurfaceFlinger::doTracing(const char* where) {
1641 ATRACE_CALL();
1642 ATRACE_NAME(where);
1643 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001644 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001645 }
1646}
1647
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001648void SurfaceFlinger::logLayerStats() {
1649 ATRACE_CALL();
1650 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001651 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001652 if (display->isPrimary()) {
1653 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001654 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001655 }
1656 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001657
1658 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001659 }
1660}
1661
Lloyd Pique074e8122018-07-26 12:57:23 -07001662void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001663{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001664 ATRACE_CALL();
1665 ALOGV("preComposition");
1666
Mathias Agopiancd60f992012-08-16 16:28:27 -07001667 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001668 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique074e8122018-07-26 12:57:23 -07001669 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001670 needExtraInvalidate = true;
1671 }
Robert Carr2047fae2016-11-28 14:09:09 -08001672 });
1673
Mathias Agopiancd60f992012-08-16 16:28:27 -07001674 if (needExtraInvalidate) {
1675 signalLayerUpdate();
1676 }
1677}
1678
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001679void SurfaceFlinger::updateCompositorTiming(
1680 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1681 std::shared_ptr<FenceTime>& presentFenceTime) {
1682 // Update queue of past composite+present times and determine the
1683 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001684 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001685 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001686 while (!getBE().mCompositePresentTimes.empty()) {
1687 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001688 // Cached values should have been updated before calling this method,
1689 // which helps avoid duplicate syscalls.
1690 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1691 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1692 break;
1693 }
1694 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001695 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001696 }
1697
1698 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001699 while (getBE().mCompositePresentTimes.size() > 16) {
1700 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001701 }
1702
Brian Andersond0010582017-03-07 13:20:31 -08001703 setCompositorTimingSnapped(
1704 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1705}
1706
1707void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1708 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001709 // Integer division and modulo round toward 0 not -inf, so we need to
1710 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001711 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001712 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1713 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1714
Brian Andersond0010582017-03-07 13:20:31 -08001715 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1716 if (idealLatency <= 0) {
1717 idealLatency = vsyncInterval;
1718 }
1719
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001720 // Snap the latency to a value that removes scheduling jitter from the
1721 // composition and present times, which often have >1ms of jitter.
1722 // Reducing jitter is important if an app attempts to extrapolate
1723 // something (such as user input) to an accurate diasplay time.
1724 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1725 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001726 nsecs_t bias = vsyncInterval / 2;
1727 int64_t extraVsyncs =
1728 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1729 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1730 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001731
David Sodman99974d22017-11-28 12:04:33 -08001732 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1733 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1734 getBE().mCompositorTiming.interval = vsyncInterval;
1735 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001736}
1737
Lloyd Pique074e8122018-07-26 12:57:23 -07001738void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001739{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001740 ATRACE_CALL();
1741 ALOGV("postComposition");
1742
Brian Anderson3546a3f2016-07-14 11:51:14 -07001743 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001744 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001745 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001746 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001747 }
1748
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001749 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001750 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001751
David Sodman73beded2017-11-15 11:56:06 -08001752 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001753 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001754 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001755 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001756 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001757 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001758 } else {
1759 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1760 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001761
David Sodman73beded2017-11-15 11:56:06 -08001762 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001763 mPreviousPresentFence =
1764 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1765 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001766 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001767
Lloyd Pique41be5d22018-06-21 13:11:48 -07001768 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1769 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001770
Lloyd Pique074e8122018-07-26 12:57:23 -07001771 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001772 // when we started doing work for this frame, but that should be okay
1773 // since updateCompositorTiming has snapping logic.
1774 updateCompositorTiming(
Lloyd Pique074e8122018-07-26 12:57:23 -07001775 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001776 CompositorTiming compositorTiming;
1777 {
David Sodman99974d22017-11-28 12:04:33 -08001778 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1779 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001780 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001781
Robert Carr2047fae2016-11-28 14:09:09 -08001782 mDrawingState.traverseInZOrder([&](Layer* layer) {
1783 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001784 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001785 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001786 recordBufferingStats(layer->getName().string(),
1787 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001788 }
Robert Carr2047fae2016-11-28 14:09:09 -08001789 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001790
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001791 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001792 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001793 enableHardwareVsync();
1794 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001795 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001796 }
1797 }
1798
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001799 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001800 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001801 enableHardwareVsync();
1802 }
1803 }
1804
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001805 if (mAnimCompositionPending) {
1806 mAnimCompositionPending = false;
1807
Brian Anderson4e606e32017-03-16 15:34:57 -07001808 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001809 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001810 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001811 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001812 // The HWC doesn't support present fences, so use the refresh
1813 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001814 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001815 mAnimFrameTracker.setActualPresentTime(presentTime);
1816 }
1817 mAnimFrameTracker.advanceFrame();
1818 }
Dan Stozab90cf072015-03-05 11:05:59 -08001819
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001820 mTimeStats.incrementTotalFrames();
1821 if (mHadClientComposition) {
1822 mTimeStats.incrementClientCompositionFrames();
1823 }
1824
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001825 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001826 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001827 return;
1828 }
1829
1830 nsecs_t currentTime = systemTime();
1831 if (mHasPoweredOff) {
1832 mHasPoweredOff = false;
1833 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001834 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001835 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001836 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1837 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001838 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001839 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001840 }
David Sodman4a36e932017-11-07 14:29:47 -08001841 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001842 }
David Sodman4a36e932017-11-07 14:29:47 -08001843 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001844
1845 {
1846 std::lock_guard lock(mTexturePoolMutex);
1847 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1848 if (refillCount > 0) {
1849 const size_t offset = mTexturePool.size();
1850 mTexturePool.resize(mTexturePoolSize);
1851 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1852 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1853 }
1854 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001855}
1856
1857void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001858 ATRACE_CALL();
1859 ALOGV("rebuildLayerStacks");
1860
Mathias Agopiancd60f992012-08-16 16:28:27 -07001861 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001862 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001863 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001864 mVisibleRegionsDirty = false;
1865 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001866
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001867 for (const auto& pair : mDisplays) {
1868 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001869 Region opaqueRegion;
1870 Region dirtyRegion;
1871 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001872 Vector<sp<Layer>> layersNeedingFences;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001873 const Transform& tr = display->getTransform();
1874 const Rect bounds = display->getBounds();
1875 if (display->isPoweredOn()) {
1876 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001877
Jeff Sharkey76488112017-02-27 14:15:18 -07001878 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001879 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001880 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001881 Region drawRegion(tr.transform(
1882 layer->visibleNonTransparentRegion));
1883 drawRegion.andSelf(bounds);
1884 if (!drawRegion.isEmpty()) {
1885 layersSortedByZ.add(layer);
1886 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001887 // Clear out the HWC layer if this layer was
1888 // previously visible, but no longer is
1889 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001890 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001891 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001892 // WM changes display->layerStack upon sleep/awake.
1893 // Here we make sure we delete the HWC layers even if
1894 // WM changed their layer stack.
1895 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001896 }
1897
1898 // If a layer is not going to get a release fence because
1899 // it is invisible, but it is also going to release its
1900 // old buffer, add it to the list of layers needing
1901 // fences.
1902 if (hwcLayerDestroyed) {
1903 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1904 mLayersWithQueuedFrames.cend(), layer);
1905 if (found != mLayersWithQueuedFrames.cend()) {
1906 layersNeedingFences.add(layer);
1907 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001908 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001909 });
1910 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001911 display->setVisibleLayersSortedByZ(layersSortedByZ);
1912 display->setLayersNeedingFences(layersNeedingFences);
1913 display->undefinedRegion.set(bounds);
1914 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1915 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001916 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001917 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001918}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001919
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001920// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001921// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001922// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001923// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001924// The returned HDR data space is one of
1925// - Dataspace::UNKNOWN
1926// - Dataspace::BT2020_HLG
1927// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001928Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1929 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001930 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001931 *outHdrDataSpace = Dataspace::UNKNOWN;
1932
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001933 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001934 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001935 case Dataspace::V0_SCRGB:
1936 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001937 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001938 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001939 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001940 case Dataspace::BT2020_PQ:
1941 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001942 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001943 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001944 case Dataspace::BT2020_HLG:
1945 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001946 // When there's mixed PQ content and HLG content, we set the HDR
1947 // data space to be BT2020_PQ and convert HLG to PQ.
1948 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1949 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001950 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001951 break;
1952 default:
1953 break;
1954 }
Romain Guy54f154a2017-10-24 21:40:32 +01001955 }
1956
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001957 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001958}
1959
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001960// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001961void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1962 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001963 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1964 *outMode = ColorMode::NATIVE;
1965 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001966 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001967 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001968 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001969
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001970 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001971 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001972
Peiyong Lindfde5112018-06-05 10:58:41 -07001973 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001974 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001975 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001976 if (isHdr) {
1977 bestDataSpace = hdrDataSpace;
1978 }
1979
Chia-I Wu0d711262018-05-21 15:19:35 -07001980 RenderIntent intent;
1981 switch (mDisplayColorSetting) {
1982 case DisplayColorSetting::MANAGED:
1983 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001984 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001985 break;
1986 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001987 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001988 break;
1989 default: // vendor display color setting
1990 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1991 break;
1992 }
Chia-I Wube02ec02018-05-18 10:59:36 -07001993
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001994 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001995}
1996
Lloyd Pique074e8122018-07-26 12:57:23 -07001997void SurfaceFlinger::setUpHWComposer() {
1998 ATRACE_CALL();
1999 ALOGV("setUpHWComposer");
Lloyd Piqueb7d12302018-07-26 12:56:47 -07002000
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002001 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002002 bool dirty = !display->getDirtyRegion(mRepaintEverything).isEmpty();
2003 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2004 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
Jesse Hallb7a05492014-08-14 15:45:06 -07002005
2006 // If nothing has changed (!dirty), don't recompose.
2007 // If something changed, but we don't currently have any visible layers,
2008 // and didn't when we last did a composition, then skip it this time.
2009 // The second rule does two things:
2010 // - When all layers are removed from a display, we'll emit one black
2011 // frame, then nothing more until we get new layers.
2012 // - When a display is created with a private layer stack, we won't
2013 // emit any black frames until a layer is added to the layer stack.
2014 bool mustRecompose = dirty && !(empty && wasEmpty);
2015
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002016 ALOGV_IF(display->isVirtual(), "Display %d: %s composition (%sdirty %sempty %swasEmpty)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002017 display->getId(), mustRecompose ? "doing" : "skipping", dirty ? "+" : "-",
2018 empty ? "+" : "-", wasEmpty ? "+" : "-");
Jesse Hallb7a05492014-08-14 15:45:06 -07002019
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002020 display->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07002021
2022 if (mustRecompose) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002023 display->lastCompositionHadVisibleLayers = !empty;
Jesse Hallb7a05492014-08-14 15:45:06 -07002024 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07002025 }
2026
Lloyd Pique074e8122018-07-26 12:57:23 -07002027 // build the h/w work list
2028 if (CC_UNLIKELY(mGeometryInvalid)) {
2029 mGeometryInvalid = false;
2030 for (const auto& [token, display] : mDisplays) {
2031 const auto displayId = display->getId();
2032 if (displayId >= 0) {
2033 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
2034 for (size_t i = 0; i < currentLayers.size(); i++) {
2035 const auto& layer = currentLayers[i];
2036 if (!layer->hasHwcLayer(displayId)) {
2037 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
2038 layer->forceClientComposition(displayId);
2039 continue;
2040 }
2041 }
2042
2043 layer->setGeometry(display, i);
2044 if (mDebugDisableHWC || mDebugRegion) {
2045 layer->forceClientComposition(displayId);
2046 }
2047 }
2048 }
2049 }
2050 }
2051
2052 // Set the per-frame data
2053 for (const auto& [token, display] : mDisplays) {
2054 const auto displayId = display->getId();
2055 if (displayId < 0) {
2056 continue;
2057 }
2058
2059 if (mDrawingState.colorMatrixChanged) {
2060 display->setColorTransform(mDrawingState.colorMatrix);
2061 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
2062 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %d: %d",
2063 displayId, result);
2064 }
2065 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2066 if (layer->isHdrY410()) {
2067 layer->forceClientComposition(displayId);
2068 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2069 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
2070 !display->hasHDR10Support()) {
2071 layer->forceClientComposition(displayId);
2072 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2073 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
2074 !display->hasHLGSupport()) {
2075 layer->forceClientComposition(displayId);
2076 }
2077
2078 if (layer->getForceClientComposition(displayId)) {
2079 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2080 layer->setCompositionType(displayId, HWC2::Composition::Client);
2081 continue;
2082 }
2083
2084 layer->setPerFrameData(display);
2085 }
2086
2087 if (hasWideColorDisplay) {
2088 ColorMode colorMode;
2089 Dataspace dataSpace;
2090 RenderIntent renderIntent;
2091 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
2092 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
2093 }
2094 }
2095
2096 mDrawingState.colorMatrixChanged = false;
2097
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002098 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002099 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002100 continue;
2101 }
2102
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002103 status_t result = display->prepareFrame(*getBE().mHwc);
2104 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002105 display->getId(), result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002106 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002107}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002108
Mathias Agopiancd60f992012-08-16 16:28:27 -07002109void SurfaceFlinger::doComposition() {
2110 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002111 ALOGV("doComposition");
2112
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002113 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002114 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002115 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002116 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002117 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002118
2119 // repaint the framebuffer (if needed)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002120 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002121
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002122 display->dirtyRegion.clear();
2123 display->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002124 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002125 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002126 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002127}
2128
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002129void SurfaceFlinger::postFramebuffer()
2130{
Mathias Agopian841cde52012-03-01 15:44:37 -08002131 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002132 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002133
Mathias Agopiana44b0412011-10-16 18:46:35 -07002134 const nsecs_t now = systemTime();
2135 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002136
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002137 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002138 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002139 continue;
2140 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07002141 const auto displayId = display->getId();
2142 if (displayId >= 0) {
2143 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002144 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002145 display->onSwapBuffersCompleted();
2146 display->makeCurrent();
2147 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002148 sp<Fence> releaseFence = Fence::NO_FENCE;
2149
Chia-I Wu7b549592017-11-15 09:14:57 -08002150 // The layer buffer from the previous frame (if any) is released
2151 // by HWC only when the release fence from this frame (if any) is
2152 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002153 auto hwcLayer = layer->getHwcLayer(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002154 if (displayId >= 0) {
2155 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
2156 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002157
2158 // If the layer was client composited in the previous frame, we
2159 // need to merge with the previous client target acquire fence.
2160 // Since we do not track that, always merge with the current
2161 // client target acquire fence when it is available, even though
2162 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002163 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002164 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002165 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002166 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002167
David Sodmanb8af7922017-12-21 15:17:55 -08002168 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002169 }
Chia-I Wu83806892017-11-16 10:50:20 -08002170
2171 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002172 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002173 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002174 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002175 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002176 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002177 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002178 }
2179 }
2180
Dominik Laskowski7e045462018-05-30 13:02:02 -07002181 if (displayId >= 0) {
2182 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002183 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002184 }
2185
Mathias Agopiana44b0412011-10-16 18:46:35 -07002186 mLastSwapBufferTime = systemTime() - now;
2187 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002188
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002189 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002190 const auto display = getDefaultDisplayDeviceLocked();
2191 if (display && getHwComposer().isConnected(display->getId())) {
2192 const uint32_t flipCount = display->getPageFlipCount();
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002193 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2194 logFrameStats();
2195 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002196 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002197}
2198
Mathias Agopian87baae12012-07-31 12:38:26 -07002199void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002200{
Mathias Agopian841cde52012-03-01 15:44:37 -08002201 ATRACE_CALL();
2202
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002203 // here we keep a copy of the drawing state (that is the state that's
2204 // going to be overwritten by handleTransactionLocked()) outside of
2205 // mStateLock so that the side-effects of the State assignment
2206 // don't happen with mStateLock held (which can cause deadlocks).
2207 State drawingState(mDrawingState);
2208
Mathias Agopianca4d3602011-05-19 15:38:14 -07002209 Mutex::Autolock _l(mStateLock);
2210 const nsecs_t now = systemTime();
2211 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002212
Mathias Agopianca4d3602011-05-19 15:38:14 -07002213 // Here we're guaranteed that some transaction flags are set
2214 // so we can call handleTransactionLocked() unconditionally.
2215 // We call getTransactionFlags(), which will also clear the flags,
2216 // with mStateLock held to guarantee that mCurrentState won't change
2217 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002218
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002219 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002220 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002221 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002222
Mathias Agopianca4d3602011-05-19 15:38:14 -07002223 mLastTransactionTime = systemTime() - now;
2224 mDebugInTransaction = 0;
2225 invalidateHwcGeometry();
2226 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002227}
2228
Dominik Laskowski7e045462018-05-30 13:02:02 -07002229DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002230 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002231 // Figure out whether the event is for the primary display or an
2232 // external display by matching the Hwc display id against one for a
2233 // connected display. If we did not find a match, we then check what
2234 // displays are not already connected to determine the type. If we don't
2235 // have a connected primary display, we assume the new display is meant to
2236 // be the primary display, and then if we don't have an external display,
2237 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002238 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2239 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002240 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002241 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002242 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002243 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002244 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002245 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002246 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002247 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002248 return DisplayDevice::DISPLAY_EXTERNAL;
2249 }
2250
2251 return DisplayDevice::DISPLAY_ID_INVALID;
2252}
2253
Lloyd Piqueba04e622017-12-14 17:11:26 -08002254void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2255 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002256 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002257 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002258 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002259 continue;
2260 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002261
2262 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2263 ALOGE("External displays are not supported by the vr hardware composer.");
2264 continue;
2265 }
2266
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002267 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002268 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002269 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002270 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002271 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002272
2273 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002274 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002275 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002276 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002277 DisplayDeviceState info;
2278 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002279 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2280 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002281 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002282 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002283 mInterceptor->saveDisplayCreation(info);
2284 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002285 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002286 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002287
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002288 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002289 if (idx >= 0) {
2290 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002291 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002292 mCurrentState.displays.removeItemsAt(idx);
2293 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002294 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002295 }
2296
2297 processDisplayChangesLocked();
2298 }
2299
2300 mPendingHotplugEvents.clear();
2301}
2302
Lloyd Pique99d3da52018-01-22 17:48:03 -08002303sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002304 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002305 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002306 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002307 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002308 HdrCapabilities hdrCapabilities;
2309 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002310
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002311 if (hasWideColorDisplay && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002312 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002313 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002314 if (isWideColorMode(colorMode)) {
2315 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002316 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002317
Dominik Laskowski7e045462018-05-30 13:02:02 -07002318 std::vector<RenderIntent> renderIntents =
2319 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002320 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002321 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002322
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002323 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2324 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2325 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002326
2327 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2328 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2329
2330 /*
2331 * Create our display's surface
2332 */
2333 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2334 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002335 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002336 renderSurface->setNativeWindow(nativeWindow.get());
2337 const int displayWidth = renderSurface->queryWidth();
2338 const int displayHeight = renderSurface->queryHeight();
2339
2340 // Make sure that composition can never be stalled by a virtual display
2341 // consumer that isn't processing buffers fast enough. We have to do this
2342 // in two places:
2343 // * Here, in case the display is composed entirely by HWC.
2344 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2345 // window's swap interval in eglMakeCurrent, so they'll override the
2346 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002347 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002348 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2349 }
2350
2351 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002352 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002353
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002354 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002355 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2356 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2357 displayHeight, hasWideColorGamut, hdrCapabilities,
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002358 supportedPerFrameMetadata, hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002359
2360 if (maxFrameBufferAcquiredBuffers >= 3) {
2361 nativeWindowSurface->preallocateBuffers();
2362 }
2363
2364 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002365 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2366 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002367 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002368 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002369 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002370 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002371 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002372 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002373 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002374 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002375 display->setLayerStack(state.layerStack);
2376 display->setProjection(state.orientation, state.viewport, state.frame);
2377 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002378
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002379 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002380}
2381
Lloyd Pique347200f2017-12-14 17:00:15 -08002382void SurfaceFlinger::processDisplayChangesLocked() {
2383 // here we take advantage of Vector's copy-on-write semantics to
2384 // improve performance by skipping the transaction entirely when
2385 // know that the lists are identical
2386 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2387 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2388 if (!curr.isIdenticalTo(draw)) {
2389 mVisibleRegionsDirty = true;
2390 const size_t cc = curr.size();
2391 size_t dc = draw.size();
2392
2393 // find the displays that were removed
2394 // (ie: in drawing state but not in current state)
2395 // also handle displays that changed
2396 // (ie: displays that are in both lists)
2397 for (size_t i = 0; i < dc;) {
2398 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2399 if (j < 0) {
2400 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002401 // Call makeCurrent() on the primary display so we can
2402 // be sure that nothing associated with this display
2403 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002404 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2405 defaultDisplay->makeCurrent();
2406 }
2407 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2408 display->disconnect(getHwComposer());
2409 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002410 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2411 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2412 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2413 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2414 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002415 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002416 } else {
2417 // this display is in both lists. see if something changed.
2418 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002419 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002420 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2421 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2422 if (state_binder != draw_binder) {
2423 // changing the surface is like destroying and
2424 // recreating the DisplayDevice, so we just remove it
2425 // from the drawing state, so that it get re-added
2426 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002427 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2428 display->disconnect(getHwComposer());
2429 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002430 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002431 mDrawingState.displays.removeItemsAt(i);
2432 dc--;
2433 // at this point we must loop to the next item
2434 continue;
2435 }
2436
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002437 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002438 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002439 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002440 }
2441 if ((state.orientation != draw[i].orientation) ||
2442 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002443 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002444 }
2445 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002446 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002447 }
2448 }
2449 }
2450 ++i;
2451 }
2452
2453 // find displays that were added
2454 // (ie: in current state but not in drawing state)
2455 for (size_t i = 0; i < cc; i++) {
2456 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2457 const DisplayDeviceState& state(curr[i]);
2458
2459 sp<DisplaySurface> dispSurface;
2460 sp<IGraphicBufferProducer> producer;
2461 sp<IGraphicBufferProducer> bqProducer;
2462 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002463 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002464
Dominik Laskowski7e045462018-05-30 13:02:02 -07002465 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002466 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002467 // Virtual displays without a surface are dormant:
2468 // they have external state (layer stack, projection,
2469 // etc.) but no internal state (i.e. a DisplayDevice).
2470 if (state.surface != nullptr) {
2471 // Allow VR composer to use virtual displays.
2472 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2473 int width = 0;
2474 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2475 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2476 int height = 0;
2477 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2478 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2479 int intFormat = 0;
2480 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2481 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002482 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002483
Dominik Laskowski7e045462018-05-30 13:02:02 -07002484 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2485 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002486 }
2487
2488 // TODO: Plumb requested format back up to consumer
2489
2490 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002491 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002492 bqProducer, bqConsumer,
2493 state.displayName);
2494
2495 dispSurface = vds;
2496 producer = vds;
2497 }
2498 } else {
2499 ALOGE_IF(state.surface != nullptr,
2500 "adding a supported display, but rendering "
2501 "surface is provided (%p), ignoring it",
2502 state.surface.get());
2503
Dominik Laskowski7e045462018-05-30 13:02:02 -07002504 displayId = state.type;
2505 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002506 producer = bqProducer;
2507 }
2508
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002509 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002510 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002511 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002512 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002513 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002514 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002515 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2516 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2517 true);
2518 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2519 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2520 true);
2521 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002522 }
2523 }
2524 }
2525 }
2526 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002527
2528 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002529}
2530
Mathias Agopian87baae12012-07-31 12:38:26 -07002531void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002532{
Dan Stoza7dde5992015-05-22 09:51:44 -07002533 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002534 mCurrentState.traverseInZOrder([](Layer* layer) {
2535 layer->notifyAvailableFrames();
2536 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002537
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002538 /*
2539 * Traversal of the children
2540 * (perform the transaction for each of them if needed)
2541 */
2542
Mathias Agopian3559b072012-08-15 13:46:03 -07002543 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002544 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002545 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002546 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002547
2548 const uint32_t flags = layer->doTransaction(0);
2549 if (flags & Layer::eVisibleRegion)
2550 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002551 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002552 }
2553
2554 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002555 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002556 */
2557
Mathias Agopiane57f2922012-08-09 16:29:12 -07002558 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002559 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002560 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002561 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002562
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002563 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002564 // The transform hint might have changed for some layers
2565 // (either because a display has changed, or because a layer
2566 // as changed).
2567 //
2568 // Walk through all the layers in currentLayers,
2569 // and update their transform hint.
2570 //
2571 // If a layer is visible only on a single display, then that
2572 // display is used to calculate the hint, otherwise we use the
2573 // default display.
2574 //
2575 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2576 // the hint is set before we acquire a buffer from the surface texture.
2577 //
2578 // NOTE: layer transactions have taken place already, so we use their
2579 // drawing state. However, SurfaceFlinger's own transaction has not
2580 // happened yet, so we must use the current state layer list
2581 // (soon to become the drawing state list).
2582 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002583 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002584 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002585 bool first = true;
2586 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002587 // NOTE: we rely on the fact that layers are sorted by
2588 // layerStack first (so we don't have to traverse the list
2589 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002590 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002591 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002592 currentlayerStack = layerStack;
2593 // figure out if this layerstack is mirrored
2594 // (more than one display) if so, pick the default display,
2595 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002596 hintDisplay = nullptr;
2597 for (const auto& [token, display] : mDisplays) {
2598 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2599 if (hintDisplay) {
2600 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002601 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002602 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002603 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002604 }
2605 }
2606 }
2607 }
Chet Haase91d25932013-04-11 15:24:55 -07002608
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002609 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002610 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2611 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002612
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002613 // could be null when this layer is using a layerStack
2614 // that is not visible on any display. Also can occur at
2615 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002616 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002617 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002618
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002619 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002620 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002621 if (hintDisplay) {
2622 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002623 }
Robert Carr2047fae2016-11-28 14:09:09 -08002624
2625 first = false;
2626 });
Mathias Agopian84300952012-11-21 16:02:13 -08002627 }
2628
2629
Mathias Agopian3559b072012-08-15 13:46:03 -07002630 /*
2631 * Perform our own transaction if needed
2632 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002633
2634 if (mLayersAdded) {
2635 mLayersAdded = false;
2636 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002637 mVisibleRegionsDirty = true;
2638 }
2639
2640 // some layers might have been removed, so
2641 // we need to update the regions they're exposing.
2642 if (mLayersRemoved) {
2643 mLayersRemoved = false;
2644 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002645 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002646 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002647 // this layer is not visible anymore
2648 // TODO: we could traverse the tree from front to back and
2649 // compute the actual visible region
2650 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002651 Region visibleReg;
2652 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002653 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002654 }
Robert Carr2047fae2016-11-28 14:09:09 -08002655 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002656 }
2657
2658 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002659
2660 updateCursorAsync();
2661}
2662
2663void SurfaceFlinger::updateCursorAsync()
2664{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002665 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002666 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002667 continue;
2668 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002669
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002670 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2671 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002672 }
2673 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002674}
2675
2676void SurfaceFlinger::commitTransaction()
2677{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002678 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002679 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002680 for (const auto& l : mLayersPendingRemoval) {
2681 recordBufferingStats(l->getName().string(),
2682 l->getOccupancyHistory(true));
2683 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002684 }
2685 mLayersPendingRemoval.clear();
2686 }
2687
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002688 // If this transaction is part of a window animation then the next frame
2689 // we composite should be considered an animation as well.
2690 mAnimCompositionPending = mAnimTransactionPending;
2691
Mathias Agopian4fec8732012-06-29 14:12:52 -07002692 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002693 // clear the "changed" flags in current state
2694 mCurrentState.colorMatrixChanged = false;
2695
Robert Carr1f0a16a2016-10-24 16:27:39 -07002696 mDrawingState.traverseInZOrder([](Layer* layer) {
2697 layer->commitChildList();
2698 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002699 mTransactionPending = false;
2700 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002701 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002702}
2703
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002704void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2705 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002706 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002707 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002708
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002709 Region aboveOpaqueLayers;
2710 Region aboveCoveredLayers;
2711 Region dirty;
2712
Mathias Agopian87baae12012-07-31 12:38:26 -07002713 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002714
Robert Carr2047fae2016-11-28 14:09:09 -08002715 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002716 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002717 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002718
Jesse Hall01e29052013-02-19 16:13:35 -08002719 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002720 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002721 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002722 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002723
Mathias Agopianab028732010-03-16 16:41:46 -07002724 /*
2725 * opaqueRegion: area of a surface that is fully opaque.
2726 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002727 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002728
2729 /*
2730 * visibleRegion: area of a surface that is visible on screen
2731 * and not fully transparent. This is essentially the layer's
2732 * footprint minus the opaque regions above it.
2733 * Areas covered by a translucent surface are considered visible.
2734 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002735 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002736
2737 /*
2738 * coveredRegion: area of a surface that is covered by all
2739 * visible regions above it (which includes the translucent areas).
2740 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002741 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002742
Jesse Halla8026d22012-09-25 13:25:04 -07002743 /*
2744 * transparentRegion: area of a surface that is hinted to be completely
2745 * transparent. This is only used to tell when the layer has no visible
2746 * non-transparent regions and can be removed from the layer list. It
2747 * does not affect the visibleRegion of this layer or any layers
2748 * beneath it. The hint may not be correct if apps don't respect the
2749 * SurfaceView restrictions (which, sadly, some don't).
2750 */
2751 Region transparentRegion;
2752
Mathias Agopianab028732010-03-16 16:41:46 -07002753
2754 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002755 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002756 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002757 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002758 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002759 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002760 if (!visibleRegion.isEmpty()) {
2761 // Remove the transparent area from the visible region
2762 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002763 if (tr.preserveRects()) {
2764 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002765 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002766 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002767 // transformation too complex, can't do the
2768 // transparent region optimization.
2769 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002770 }
Mathias Agopianab028732010-03-16 16:41:46 -07002771 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002772
Mathias Agopianab028732010-03-16 16:41:46 -07002773 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002774 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002775 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002776 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2777 // the opaque region is the layer's footprint
2778 opaqueRegion = visibleRegion;
2779 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002780 }
2781 }
2782
Robert Carre5f4f692018-01-12 13:12:28 -08002783 if (visibleRegion.isEmpty()) {
2784 layer->clearVisibilityRegions();
2785 return;
2786 }
2787
Mathias Agopianab028732010-03-16 16:41:46 -07002788 // Clip the covered region to the visible region
2789 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2790
2791 // Update aboveCoveredLayers for next (lower) layer
2792 aboveCoveredLayers.orSelf(visibleRegion);
2793
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002794 // subtract the opaque region covered by the layers above us
2795 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002796
2797 // compute this layer's dirty region
2798 if (layer->contentDirty) {
2799 // we need to invalidate the whole region
2800 dirty = visibleRegion;
2801 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002802 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002803 layer->contentDirty = false;
2804 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002805 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002806 * the exposed region consists of two components:
2807 * 1) what's VISIBLE now and was COVERED before
2808 * 2) what's EXPOSED now less what was EXPOSED before
2809 *
2810 * note that (1) is conservative, we start with the whole
2811 * visible region but only keep what used to be covered by
2812 * something -- which mean it may have been exposed.
2813 *
2814 * (2) handles areas that were not covered by anything but got
2815 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002816 */
Mathias Agopianab028732010-03-16 16:41:46 -07002817 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002818 const Region oldVisibleRegion = layer->visibleRegion;
2819 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002820 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2821 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002822 }
2823 dirty.subtractSelf(aboveOpaqueLayers);
2824
2825 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002826 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002827
Mathias Agopianab028732010-03-16 16:41:46 -07002828 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002829 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002830
Jesse Halla8026d22012-09-25 13:25:04 -07002831 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002832 layer->setVisibleRegion(visibleRegion);
2833 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002834 layer->setVisibleNonTransparentRegion(
2835 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002836 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002837
Mathias Agopian87baae12012-07-31 12:38:26 -07002838 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002839}
2840
Chia-I Wuab0c3192017-08-01 11:29:00 -07002841void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002842 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002843 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2844 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002845 }
2846 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002847}
2848
Dan Stoza6b9454d2014-11-07 16:00:59 -08002849bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002850{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002851 ALOGV("handlePageFlip");
2852
Brian Andersond6927fb2016-07-23 23:37:30 -07002853 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002854
Mathias Agopian4fec8732012-06-29 14:12:52 -07002855 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002856 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002857 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002858
2859 // Store the set of layers that need updates. This set must not change as
2860 // buffers are being latched, as this could result in a deadlock.
2861 // Example: Two producers share the same command stream and:
2862 // 1.) Layer 0 is latched
2863 // 2.) Layer 0 gets a new frame
2864 // 2.) Layer 1 gets a new frame
2865 // 3.) Layer 1 is latched.
2866 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2867 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002868 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002869 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002870 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07002871 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002872 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002873 } else {
2874 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002875 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002876 } else {
2877 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002878 }
Robert Carr2047fae2016-11-28 14:09:09 -08002879 });
2880
Dan Stoza9e56aa02015-11-02 13:00:03 -08002881 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002882 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002883 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002884 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002885 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002886 newDataLatched = true;
2887 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002888 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002889
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002890 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002891
2892 // If we will need to wake up at some time in the future to deal with a
2893 // queued frame that shouldn't be displayed during this vsync period, wake
2894 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002895 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002896 signalLayerUpdate();
2897 }
2898
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002899 // enter boot animation on first buffer latch
2900 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2901 ALOGI("Enter boot animation");
2902 mBootStage = BootStage::BOOTANIMATION;
2903 }
2904
Dan Stoza6b9454d2014-11-07 16:00:59 -08002905 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002906 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002907}
2908
Mathias Agopianad456f92011-01-13 17:53:01 -08002909void SurfaceFlinger::invalidateHwcGeometry()
2910{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002911 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002912}
2913
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002914void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2915 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002916 // We only need to actually compose the display if:
2917 // 1) It is being handled by hardware composer, which may need this to
2918 // keep its virtual display state machine in sync, or
2919 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002920 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002921 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002922 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002923 return;
2924 }
2925
Dan Stoza9e56aa02015-11-02 13:00:03 -08002926 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002927 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002928
2929 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002930 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002931}
2932
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002933bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002934 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002935
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002936 const Region bounds(display->bounds());
2937 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002938 const auto displayId = display->getId();
2939 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002940 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002941
Chia-I Wu8e50e692018-05-04 10:12:37 -07002942 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002943 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002944
Dan Stoza9e56aa02015-11-02 13:00:03 -08002945 if (hasClientComposition) {
2946 ALOGV("hasClientComposition");
2947
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002948 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002949 if (display->hasWideColorGamut()) {
2950 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002951 }
2952 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002953 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002954 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002955
Dominik Laskowski7e045462018-05-30 13:02:02 -07002956 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002957 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2958 HWC2::Capability::SkipClientColorTransform);
2959
Chia-I Wud49d6692018-06-27 07:17:41 +08002960 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002961 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2962 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08002963 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002964 }
2965
Chia-I Wud49d6692018-06-27 07:17:41 +08002966 // The current enhanced saturation matrix is designed to enhance Display P3,
2967 // thus we only apply this matrix when the render intent is not colorimetric
2968 // and the output color space is Display P3.
2969 needsEnhancedColorMatrix =
2970 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2971 outputDataspace == Dataspace::DISPLAY_P3);
2972 if (needsEnhancedColorMatrix) {
2973 colorMatrix *= mEnhancedSaturationMatrix;
2974 }
2975
2976 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002977
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002978 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002979 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002980 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002981 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002982
2983 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002984 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
2985 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
2986 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07002987 }
2988 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002989 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002990
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002991 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002992 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002993 // when using overlays, we assume a fully transparent framebuffer
2994 // NOTE: we could reduce how much we need to clear, for instance
2995 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002996 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002997 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002998 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002999 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003000 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003001 // we're left with the letterbox region
3002 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003003 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003004
3005 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003006 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003007
Mathias Agopianb9494d52012-04-18 02:28:45 -07003008 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003009 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003010 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003011 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003012 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003013 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003014
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003015 if (!display->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07003016 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07003017 // scissor on the main display. It should never be needed
3018 // anyways (though in theory it could since the API allows it).
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003019 const Rect& bounds = display->getBounds();
3020 const Rect& scissor = display->getScissor();
Mathias Agopianf45c5102012-10-24 16:29:17 -07003021 if (scissor != bounds) {
3022 // scissor doesn't match the screen's dimensions, so we
3023 // need to clear everything outside of it and enable
3024 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003025
Mathias Agopianf45c5102012-10-24 16:29:17 -07003026 // enable scissor for this frame
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003027 const uint32_t height = display->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08003028 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07003029 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003030 }
3031 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003032 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003033
Mathias Agopian85d751c2012-08-29 16:59:24 -07003034 /*
3035 * and then, render the layers targeted at the framebuffer
3036 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003037
Dan Stoza9e56aa02015-11-02 13:00:03 -08003038 ALOGV("Rendering client layers");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003039 const Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003040 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003041 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003042 const Region clip(bounds.intersect(
3043 displayTransform.transform(layer->visibleRegion)));
3044 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07003045 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003046 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003047 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003048 case HWC2::Composition::Cursor:
3049 case HWC2::Composition::Device:
3050 case HWC2::Composition::Sideband:
3051 case HWC2::Composition::SolidColor: {
3052 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07003053 if (layer->getClearClientTarget(displayId) && !firstLayer &&
Rajavenu Kyatham2eae6d32018-04-10 12:34:05 +05303054 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3055 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003056 // never clear the very first layer since we're
3057 // guaranteed the FB is already cleared
3058 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003059 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003060 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003061 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003062 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003063 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003064 break;
3065 }
3066 default:
3067 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003068 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003069 } else {
3070 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003071 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003072 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003073 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003074
Chia-I Wud49d6692018-06-27 07:17:41 +08003075 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003076 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003077 }
3078
Mathias Agopianf45c5102012-10-24 16:29:17 -07003079 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003080 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003081 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003082}
3083
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003084void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
3085 const Region& region) const {
3086 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003087 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003088 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003089}
3090
Dan Stoza7d89d062015-04-30 13:29:25 -07003091status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003092 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003093 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003094 const sp<Layer>& lbc,
3095 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003096{
Dan Stoza7d89d062015-04-30 13:29:25 -07003097 // add this layer to the current state list
3098 {
3099 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003100 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003101 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3102 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003103 return NO_MEMORY;
3104 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003105 if (parent == nullptr) {
3106 mCurrentState.layersSortedByZ.add(lbc);
3107 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003108 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003109 ALOGE("addClientLayer called with a removed parent");
3110 return NAME_NOT_FOUND;
3111 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003112 parent->addChild(lbc);
3113 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003114
Yiwei Zhang243b3782018-05-15 17:40:04 -07003115 if (gbc != nullptr) {
3116 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3117 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3118 mMaxGraphicBufferProducerListSize,
3119 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3120 mGraphicBufferProducerList.size(),
3121 mMaxGraphicBufferProducerListSize, mNumLayers);
3122 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003123 mLayersAdded = true;
3124 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003125 }
3126
Mathias Agopian96f08192010-06-02 23:28:45 -07003127 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003128 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003129
Dan Stoza7d89d062015-04-30 13:29:25 -07003130 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003131}
3132
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003133status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003134 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003135 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3136}
Robert Carr7f9b8992017-03-10 11:08:39 -08003137
chaviwca27f252018-02-06 16:46:39 -08003138status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3139 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003140 if (layer->isPendingRemoval()) {
3141 return NO_ERROR;
3142 }
3143
Robert Carr1f0a16a2016-10-24 16:27:39 -07003144 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003145 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003146 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003147 if (topLevelOnly) {
3148 return NO_ERROR;
3149 }
3150
Chia-I Wu98f1c102017-05-30 14:54:08 -07003151 sp<Layer> ancestor = p;
3152 while (ancestor->getParent() != nullptr) {
3153 ancestor = ancestor->getParent();
3154 }
3155 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3156 ALOGE("removeLayer called with a layer whose parent has been removed");
3157 return NAME_NOT_FOUND;
3158 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003159
3160 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003161 } else {
3162 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003163 }
3164
Robert Carr136e2f62017-02-08 17:54:29 -08003165 // As a matter of normal operation, the LayerCleaner will produce a second
3166 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3167 // so we will succeed in promoting it, but it's already been removed
3168 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3169 // otherwise something has gone wrong and we are leaking the layer.
3170 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003171 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3172 layer->getName().string(),
3173 (p != nullptr) ? p->getName().string() : "no-parent");
3174 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003175 } else if (index < 0) {
3176 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003177 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003178
Chia-I Wuc6657022017-08-15 11:18:17 -07003179 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003180 mLayersPendingRemoval.add(layer);
3181 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003182 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003183 setTransactionFlags(eTransactionNeeded);
3184 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003185}
3186
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003187uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003188 return android_atomic_release_load(&mTransactionFlags);
3189}
3190
Mathias Agopian3f844832013-08-07 21:24:32 -07003191uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003192 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3193}
3194
Mathias Agopian3f844832013-08-07 21:24:32 -07003195uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003196 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3197}
3198
3199uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3200 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003201 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003202 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003203 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003204 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003205 }
3206 return old;
3207}
3208
chaviwca27f252018-02-06 16:46:39 -08003209bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3210 for (const ComposerState& state : states) {
3211 // Here we need to check that the interface we're given is indeed
3212 // one of our own. A malicious client could give us a nullptr
3213 // IInterface, or one of its own or even one of our own but a
3214 // different type. All these situations would cause us to crash.
3215 if (state.client == nullptr) {
3216 return true;
3217 }
3218
3219 sp<IBinder> binder = IInterface::asBinder(state.client);
3220 if (binder == nullptr) {
3221 return true;
3222 }
3223
3224 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3225 return true;
3226 }
3227 }
3228 return false;
3229}
3230
Mathias Agopian8b33f032012-07-24 20:43:54 -07003231void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003232 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003233 const Vector<DisplayState>& displays,
3234 uint32_t flags)
3235{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003236 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003237 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003238 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003239
chaviwca27f252018-02-06 16:46:39 -08003240 if (containsAnyInvalidClientState(states)) {
3241 return;
3242 }
3243
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003244 if (flags & eAnimation) {
3245 // For window updates that are part of an animation we must wait for
3246 // previous animation "frames" to be handled.
3247 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003248 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003249 if (CC_UNLIKELY(err != NO_ERROR)) {
3250 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003251 // caller after a few seconds.
3252 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3253 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003254 mAnimTransactionPending = false;
3255 break;
3256 }
3257 }
3258 }
3259
chaviwca27f252018-02-06 16:46:39 -08003260 for (const DisplayState& display : displays) {
3261 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003262 }
3263
chaviwca27f252018-02-06 16:46:39 -08003264 for (const ComposerState& state : states) {
3265 transactionFlags |= setClientStateLocked(state);
3266 }
3267
3268 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3269 // as destroyed should only occur after setting all other states. This is to allow for a
3270 // child re-parent to happen before marking its original parent as destroyed (which would
3271 // then mark the child as destroyed).
3272 for (const ComposerState& state : states) {
3273 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003274 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003275
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003276 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3277 // anyway. This can be used as a flush mechanism for previous async transactions.
3278 // Empty animation transaction can be used to simulate back-pressure, so also force a
3279 // transaction for empty animation transactions.
3280 if (transactionFlags == 0 &&
3281 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003282 transactionFlags = eTransactionNeeded;
3283 }
3284
Mathias Agopian386aa982011-11-07 21:58:03 -08003285 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003286 if (mInterceptor->isEnabled()) {
3287 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003288 }
Irvel468051e2016-06-13 16:44:44 -07003289
Mathias Agopian386aa982011-11-07 21:58:03 -08003290 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003291 const auto start = (flags & eEarlyWakeup)
3292 ? VSyncModulator::TransactionStart::EARLY
3293 : VSyncModulator::TransactionStart::NORMAL;
3294 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003295
3296 // if this is a synchronous transaction, wait for it to take effect
3297 // before returning.
3298 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003299 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003300 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003301 if (flags & eAnimation) {
3302 mAnimTransactionPending = true;
3303 }
3304 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003305 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3306 if (CC_UNLIKELY(err != NO_ERROR)) {
3307 // just in case something goes wrong in SF, return to the
3308 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003309 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3310 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003311 break;
3312 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003313 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003314 }
3315}
3316
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003317uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3318 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3319 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003320
Mathias Agopiane57f2922012-08-09 16:29:12 -07003321 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003322 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3323
3324 const uint32_t what = s.what;
3325 if (what & DisplayState::eSurfaceChanged) {
3326 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3327 state.surface = s.surface;
3328 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003329 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003330 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003331 if (what & DisplayState::eLayerStackChanged) {
3332 if (state.layerStack != s.layerStack) {
3333 state.layerStack = s.layerStack;
3334 flags |= eDisplayTransactionNeeded;
3335 }
3336 }
3337 if (what & DisplayState::eDisplayProjectionChanged) {
3338 if (state.orientation != s.orientation) {
3339 state.orientation = s.orientation;
3340 flags |= eDisplayTransactionNeeded;
3341 }
3342 if (state.frame != s.frame) {
3343 state.frame = s.frame;
3344 flags |= eDisplayTransactionNeeded;
3345 }
3346 if (state.viewport != s.viewport) {
3347 state.viewport = s.viewport;
3348 flags |= eDisplayTransactionNeeded;
3349 }
3350 }
3351 if (what & DisplayState::eDisplaySizeChanged) {
3352 if (state.width != s.width) {
3353 state.width = s.width;
3354 flags |= eDisplayTransactionNeeded;
3355 }
3356 if (state.height != s.height) {
3357 state.height = s.height;
3358 flags |= eDisplayTransactionNeeded;
3359 }
3360 }
3361
Mathias Agopiane57f2922012-08-09 16:29:12 -07003362 return flags;
3363}
3364
Robert Carrd4ae7f32018-06-07 16:10:57 -07003365bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3366 IPCThreadState* ipc = IPCThreadState::self();
3367 const int pid = ipc->getCallingPid();
3368 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003369 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulece2437712018-07-19 17:01:45 -07003370 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003371 return false;
3372 }
3373 return true;
3374}
3375
chaviwca27f252018-02-06 16:46:39 -08003376uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3377 const layer_state_t& s = composerState.state;
3378 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3379
Mathias Agopian13127d82013-03-05 17:47:11 -08003380 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003381 if (layer == nullptr) {
3382 return 0;
3383 }
3384
3385 if (layer->isPendingRemoval()) {
3386 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3387 return 0;
3388 }
3389
3390 uint32_t flags = 0;
3391
3392 const uint32_t what = s.what;
3393 bool geometryAppliesWithResize =
3394 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003395
3396 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3397 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003398 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003399 layer->pushPendingState();
3400 }
3401
chaviw8b3871a2017-11-01 17:41:01 -07003402 if (what & layer_state_t::ePositionChanged) {
3403 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3404 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003405 }
chaviw8b3871a2017-11-01 17:41:01 -07003406 }
3407 if (what & layer_state_t::eLayerChanged) {
3408 // NOTE: index needs to be calculated before we update the state
3409 const auto& p = layer->getParent();
3410 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003411 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003412 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003413 mCurrentState.layersSortedByZ.removeAt(idx);
3414 mCurrentState.layersSortedByZ.add(layer);
3415 // we need traversal (state changed)
3416 // AND transaction (list changed)
3417 flags |= eTransactionNeeded|eTraversalNeeded;
3418 }
chaviw8b3871a2017-11-01 17:41:01 -07003419 } else {
3420 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003421 flags |= eTransactionNeeded|eTraversalNeeded;
3422 }
3423 }
chaviw8b3871a2017-11-01 17:41:01 -07003424 }
3425 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003426 // NOTE: index needs to be calculated before we update the state
3427 const auto& p = layer->getParent();
3428 if (p == nullptr) {
3429 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3430 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3431 mCurrentState.layersSortedByZ.removeAt(idx);
3432 mCurrentState.layersSortedByZ.add(layer);
3433 // we need traversal (state changed)
3434 // AND transaction (list changed)
3435 flags |= eTransactionNeeded|eTraversalNeeded;
3436 }
3437 } else {
3438 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3439 flags |= eTransactionNeeded|eTraversalNeeded;
3440 }
chaviw8b3871a2017-11-01 17:41:01 -07003441 }
3442 }
3443 if (what & layer_state_t::eSizeChanged) {
3444 if (layer->setSize(s.w, s.h)) {
3445 flags |= eTraversalNeeded;
3446 }
3447 }
3448 if (what & layer_state_t::eAlphaChanged) {
3449 if (layer->setAlpha(s.alpha))
3450 flags |= eTraversalNeeded;
3451 }
3452 if (what & layer_state_t::eColorChanged) {
3453 if (layer->setColor(s.color))
3454 flags |= eTraversalNeeded;
3455 }
3456 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003457 // TODO: b/109894387
3458 //
3459 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3460 // rotation. To see the problem observe that if we have a square parent, and a child
3461 // of the same size, then we rotate the child 45 degrees around it's center, the child
3462 // must now be cropped to a non rectangular 8 sided region.
3463 //
3464 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3465 // private API, and the WindowManager only uses rotation in one case, which is on a top
3466 // level layer in which cropping is not an issue.
3467 //
3468 // However given that abuse of rotation matrices could lead to surfaces extending outside
3469 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3470 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3471 // transformations.
3472 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003473 flags |= eTraversalNeeded;
3474 }
3475 if (what & layer_state_t::eTransparentRegionChanged) {
3476 if (layer->setTransparentRegionHint(s.transparentRegion))
3477 flags |= eTraversalNeeded;
3478 }
3479 if (what & layer_state_t::eFlagsChanged) {
3480 if (layer->setFlags(s.flags, s.mask))
3481 flags |= eTraversalNeeded;
3482 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003483 if (what & layer_state_t::eCropChanged_legacy) {
3484 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003485 flags |= eTraversalNeeded;
3486 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003487 if (what & layer_state_t::eFinalCropChanged_legacy) {
3488 if (layer->setFinalCrop_legacy(s.finalCrop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003489 flags |= eTraversalNeeded;
3490 }
3491 if (what & layer_state_t::eLayerStackChanged) {
3492 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3493 // We only allow setting layer stacks for top level layers,
3494 // everything else inherits layer stack from its parent.
3495 if (layer->hasParent()) {
3496 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3497 layer->getName().string());
3498 } else if (idx < 0) {
3499 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3500 "that also does not appear in the top level layer list. Something"
3501 " has gone wrong.", layer->getName().string());
3502 } else if (layer->setLayerStack(s.layerStack)) {
3503 mCurrentState.layersSortedByZ.removeAt(idx);
3504 mCurrentState.layersSortedByZ.add(layer);
3505 // we need traversal (state changed)
3506 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003507 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003508 }
3509 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003510 if (what & layer_state_t::eDeferTransaction_legacy) {
3511 if (s.barrierHandle_legacy != nullptr) {
3512 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3513 } else if (s.barrierGbp_legacy != nullptr) {
3514 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003515 if (authenticateSurfaceTextureLocked(gbp)) {
3516 const auto& otherLayer =
3517 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003518 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003519 } else {
3520 ALOGE("Attempt to defer transaction to to an"
3521 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003522 }
3523 }
chaviw8b3871a2017-11-01 17:41:01 -07003524 // We don't trigger a traversal here because if no other state is
3525 // changed, we don't want this to cause any more work
3526 }
3527 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003528 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003529 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003530 if (!hadParent) {
3531 mCurrentState.layersSortedByZ.remove(layer);
3532 }
chaviw8b3871a2017-11-01 17:41:01 -07003533 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003534 }
chaviw8b3871a2017-11-01 17:41:01 -07003535 }
3536 if (what & layer_state_t::eReparentChildren) {
3537 if (layer->reparentChildren(s.reparentHandle)) {
3538 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003539 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003540 }
chaviw8b3871a2017-11-01 17:41:01 -07003541 if (what & layer_state_t::eDetachChildren) {
3542 layer->detachChildren();
3543 }
3544 if (what & layer_state_t::eOverrideScalingModeChanged) {
3545 layer->setOverrideScalingMode(s.overrideScalingMode);
3546 // We don't trigger a traversal here because if no other state is
3547 // changed, we don't want this to cause any more work
3548 }
Marissa Wall61c58622018-07-18 10:12:20 -07003549 if (what & layer_state_t::eTransformChanged) {
3550 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3551 }
3552 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3553 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3554 flags |= eTraversalNeeded;
3555 }
3556 if (what & layer_state_t::eCropChanged) {
3557 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3558 }
3559 if (what & layer_state_t::eBufferChanged) {
3560 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3561 }
3562 if (what & layer_state_t::eAcquireFenceChanged) {
3563 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3564 }
3565 if (what & layer_state_t::eDataspaceChanged) {
3566 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3567 }
3568 if (what & layer_state_t::eHdrMetadataChanged) {
3569 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3570 }
3571 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3572 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3573 }
3574 if (what & layer_state_t::eApiChanged) {
3575 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3576 }
3577 if (what & layer_state_t::eSidebandStreamChanged) {
3578 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3579 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003580 return flags;
3581}
3582
chaviwca27f252018-02-06 16:46:39 -08003583void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3584 const layer_state_t& state = composerState.state;
3585 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3586
3587 sp<Layer> layer(client->getLayerUser(state.surface));
3588 if (layer == nullptr) {
3589 return;
3590 }
3591
3592 if (layer->isPendingRemoval()) {
3593 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3594 return;
3595 }
3596
3597 if (state.what & layer_state_t::eDestroySurface) {
3598 removeLayerLocked(mStateLock, layer);
3599 }
3600}
3601
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003602status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003603 const String8& name,
3604 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003605 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003606 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003607 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003608{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003609 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003610 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003611 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003612 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003613 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003614
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003615 status_t result = NO_ERROR;
3616
3617 sp<Layer> layer;
3618
Cody Northropbc755282017-03-31 12:00:08 -06003619 String8 uniqueName = getUniqueLayerName(name);
3620
Mathias Agopian3165cc22012-08-08 19:42:09 -07003621 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003622 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003623 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3624 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003625
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003626 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003627 case ISurfaceComposerClient::eFXSurfaceBufferState:
3628 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3629 break;
chaviw13fdc492017-06-27 12:40:18 -07003630 case ISurfaceComposerClient::eFXSurfaceColor:
3631 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003632 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003633 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003634 break;
3635 default:
3636 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003637 break;
3638 }
3639
Dan Stoza7d89d062015-04-30 13:29:25 -07003640 if (result != NO_ERROR) {
3641 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003642 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003643
Chia-I Wuab0c3192017-08-01 11:29:00 -07003644 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3645 // TODO b/64227542
3646 if (windowType == 441731) {
3647 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3648 layer->setPrimaryDisplayOnly();
3649 }
3650
Albert Chaulk479c60c2017-01-27 14:21:34 -05003651 layer->setInfo(windowType, ownerUid);
3652
Robert Carr1f0a16a2016-10-24 16:27:39 -07003653 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003654 if (result != NO_ERROR) {
3655 return result;
3656 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003657 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003658
3659 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003660 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003661}
3662
Cody Northropbc755282017-03-31 12:00:08 -06003663String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3664{
3665 bool matchFound = true;
3666 uint32_t dupeCounter = 0;
3667
3668 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3669 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3670
Dan Stoza436ccf32018-06-21 12:10:12 -07003671 // Grab the state lock since we're accessing mCurrentState
3672 Mutex::Autolock lock(mStateLock);
3673
Cody Northropbc755282017-03-31 12:00:08 -06003674 // Loop over layers until we're sure there is no matching name
3675 while (matchFound) {
3676 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003677 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003678 if (layer->getName() == uniqueName) {
3679 matchFound = true;
3680 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3681 }
3682 });
3683 }
3684
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003685 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3686 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003687
3688 return uniqueName;
3689}
3690
Marissa Wallfd668622018-05-10 10:21:13 -07003691status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3692 uint32_t w, uint32_t h, uint32_t flags,
3693 PixelFormat& format, sp<IBinder>* handle,
3694 sp<IGraphicBufferProducer>* gbp,
3695 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003696 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003697 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003698 case PIXEL_FORMAT_TRANSPARENT:
3699 case PIXEL_FORMAT_TRANSLUCENT:
3700 format = PIXEL_FORMAT_RGBA_8888;
3701 break;
3702 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003703 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003704 break;
3705 }
3706
Marissa Wallfd668622018-05-10 10:21:13 -07003707 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3708 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003709 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003710 *handle = layer->getHandle();
3711 *gbp = layer->getProducer();
3712 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003713 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003714
Marissa Wallfd668622018-05-10 10:21:13 -07003715 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003716 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003717}
3718
Marissa Wall61c58622018-07-18 10:12:20 -07003719status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3720 uint32_t w, uint32_t h, uint32_t flags,
3721 sp<IBinder>* handle, sp<Layer>* outLayer) {
3722 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3723 *handle = layer->getHandle();
3724 *outLayer = layer;
3725
3726 return NO_ERROR;
3727}
3728
chaviw13fdc492017-06-27 12:40:18 -07003729status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003730 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003731 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003732{
chaviw13fdc492017-06-27 12:40:18 -07003733 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003734 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003735 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003736}
3737
Mathias Agopianac9fa422013-02-11 16:40:36 -08003738status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003739{
Robert Carr9524cb32017-02-13 11:32:32 -08003740 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003741 status_t err = NO_ERROR;
3742 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003743 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003744 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003745 err = removeLayer(l);
3746 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3747 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003748 }
3749 return err;
3750}
3751
Mathias Agopian13127d82013-03-05 17:47:11 -08003752status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003753{
Mathias Agopian67106042013-03-14 19:18:13 -07003754 // called by ~LayerCleaner() when all references to the IBinder (handle)
3755 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003756 sp<Layer> l = layer.promote();
3757 if (l == nullptr) {
3758 // The layer has already been removed, carry on
3759 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003760 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003761 // If we have a parent, then we can continue to live as long as it does.
3762 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003763}
3764
Mathias Agopianb60314a2012-04-10 22:09:54 -07003765// ---------------------------------------------------------------------------
3766
Andy McFadden13a082e2012-08-24 10:16:42 -07003767void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003768 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3769 if (!displayToken) return;
3770
Jesse Hall01e29052013-02-19 16:13:35 -08003771 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003772 Vector<ComposerState> state;
3773 Vector<DisplayState> displays;
3774 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003775 d.what = DisplayState::eDisplayProjectionChanged |
3776 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003777 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003778 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003779 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003780 d.frame.makeInvalid();
3781 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003782 d.width = 0;
3783 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003784 displays.add(d);
3785 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003786
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003787 const auto display = getDisplayDevice(displayToken);
3788 if (!display) return;
3789
3790 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3791
3792 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003793 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003794 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003795
Brian Andersond0010582017-03-07 13:20:31 -08003796 // Use phase of 0 since phase is not known.
3797 // Use latency of 0, which will snap to the ideal latency.
3798 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003799}
3800
3801void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003802 // Async since we may be called from the main thread.
3803 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003804}
3805
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003806void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3807 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003808 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003809 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003810
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003811 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003812 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003813 return;
3814 }
3815
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003816 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003817 ALOGW("Trying to set power mode for virtual display");
3818 return;
3819 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003820
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003821 display->setPowerMode(mode);
3822
Lloyd Pique4dccc412018-01-22 17:21:36 -08003823 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003824 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003825 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003826 if (idx < 0) {
3827 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3828 return;
3829 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003830 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003831 }
3832
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003833 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003834 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003835 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003836 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003837 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003838 // FIXME: eventthread only knows about the main display right now
3839 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003840 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003841 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003842
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003843 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003844 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003845 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003846
3847 struct sched_param param = {0};
3848 param.sched_priority = 1;
3849 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3850 ALOGW("Couldn't set SCHED_FIFO on display on");
3851 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003852 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003853 // Turn off the display
3854 struct sched_param param = {0};
3855 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3856 ALOGW("Couldn't set SCHED_OTHER on display off");
3857 }
3858
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003859 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003860 disableHardwareVsync(true); // also cancels any in-progress resync
3861
Mathias Agopiancde87a32012-09-13 14:09:01 -07003862 // FIXME: eventthread only knows about the main display right now
3863 mEventThread->onScreenReleased();
3864 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003865
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003866 getHwComposer().setPowerMode(type, mode);
3867 mVisibleRegionsDirty = true;
3868 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003869 } else if (mode == HWC_POWER_MODE_DOZE ||
3870 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003871 // Update display while dozing
3872 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003873 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003874 // FIXME: eventthread only knows about the main display right now
3875 mEventThread->onScreenAcquired();
3876 resyncToHardwareVsync(true);
3877 }
3878 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3879 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003880 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003881 disableHardwareVsync(true); // also cancels any in-progress resync
3882 // FIXME: eventthread only knows about the main display right now
3883 mEventThread->onScreenReleased();
3884 }
3885 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003886 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003887 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003888 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003889 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003890
3891 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003892}
3893
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003894void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003895 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003896 const auto display = getDisplayDevice(displayToken);
3897 if (!display) {
3898 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3899 displayToken.get());
3900 } else if (display->isVirtual()) {
3901 ALOGW("Attempt to set power mode %d for virtual display", mode);
3902 } else {
3903 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003904 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003905 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003906}
3907
3908// ---------------------------------------------------------------------------
3909
Lloyd Pique755e3192018-01-31 16:46:15 -08003910status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3911 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003912 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003913
Mathias Agopianbd115332013-04-18 16:41:04 -07003914 IPCThreadState* ipc = IPCThreadState::self();
3915 const int pid = ipc->getCallingPid();
3916 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003917
Mathias Agopianbd115332013-04-18 16:41:04 -07003918 if ((uid != AID_SHELL) &&
3919 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003920 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003921 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003922 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003923 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003924 // (this would indicate SF is stuck, but we want to be able to
3925 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003926 status_t err = mStateLock.timedLock(s2ns(1));
3927 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003928 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003929 result.appendFormat(
3930 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3931 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003932 }
3933
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003934 bool dumpAll = true;
3935 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003936 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003937
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003938 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003939 if ((index < numArgs) &&
3940 (args[index] == String16("--list"))) {
3941 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003942 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003943 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003944 }
3945
3946 if ((index < numArgs) &&
3947 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003948 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003949 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003950 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003951 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003952
3953 if ((index < numArgs) &&
3954 (args[index] == String16("--latency-clear"))) {
3955 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003956 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003957 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003958 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003959
3960 if ((index < numArgs) &&
3961 (args[index] == String16("--dispsync"))) {
3962 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07003963 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07003964 dumpAll = false;
3965 }
Dan Stozab90cf072015-03-05 11:05:59 -08003966
3967 if ((index < numArgs) &&
3968 (args[index] == String16("--static-screen"))) {
3969 index++;
3970 dumpStaticScreenStats(result);
3971 dumpAll = false;
3972 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003973
3974 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003975 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003976 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003977 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003978 dumpAll = false;
3979 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003980
3981 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3982 index++;
3983 dumpWideColorInfo(result);
3984 dumpAll = false;
3985 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003986
3987 if ((index < numArgs) &&
3988 (args[index] == String16("--enable-layer-stats"))) {
3989 index++;
3990 mLayerStats.enable();
3991 dumpAll = false;
3992 }
3993
3994 if ((index < numArgs) &&
3995 (args[index] == String16("--disable-layer-stats"))) {
3996 index++;
3997 mLayerStats.disable();
3998 dumpAll = false;
3999 }
4000
4001 if ((index < numArgs) &&
4002 (args[index] == String16("--clear-layer-stats"))) {
4003 index++;
4004 mLayerStats.clear();
4005 dumpAll = false;
4006 }
4007
4008 if ((index < numArgs) &&
4009 (args[index] == String16("--dump-layer-stats"))) {
4010 index++;
4011 mLayerStats.dump(result);
4012 dumpAll = false;
4013 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004014
4015 if ((index < numArgs) &&
4016 (args[index] == String16("--display-identification"))) {
4017 index++;
4018 dumpDisplayIdentificationData(result);
4019 dumpAll = false;
4020 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004021
4022 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4023 index++;
4024 mTimeStats.parseArgs(asProto, args, index, result);
4025 dumpAll = false;
4026 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004027 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004028
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004029 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004030 if (asProto) {
4031 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4032 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4033 } else {
4034 dumpAllLocked(args, index, result);
4035 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004036 }
4037
Mathias Agopian9795c422009-08-26 16:36:26 -07004038 if (locked) {
4039 mStateLock.unlock();
4040 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004041 }
4042 write(fd, result.string(), result.size());
4043 return NO_ERROR;
4044}
4045
Dan Stozac7014012014-02-14 15:03:43 -08004046void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4047 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004048{
Robert Carr2047fae2016-11-28 14:09:09 -08004049 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004050 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004051 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004052}
4053
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004054void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004055 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004056{
4057 String8 name;
4058 if (index < args.size()) {
4059 name = String8(args[index]);
4060 index++;
4061 }
4062
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004063 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4064 getHwComposer().isConnected(displayId)) {
4065 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4066 const nsecs_t period = activeConfig->getVsyncPeriod();
4067 result.appendFormat("%" PRId64 "\n", period);
4068 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004069
4070 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004071 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004072 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004073 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004074 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004075 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004076 }
Robert Carr2047fae2016-11-28 14:09:09 -08004077 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004078 }
4079}
4080
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004081void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004082 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004083{
4084 String8 name;
4085 if (index < args.size()) {
4086 name = String8(args[index]);
4087 index++;
4088 }
4089
Robert Carr2047fae2016-11-28 14:09:09 -08004090 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004091 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004092 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004093 }
Robert Carr2047fae2016-11-28 14:09:09 -08004094 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004095
Svetoslavd85084b2014-03-20 10:28:31 -07004096 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004097}
4098
Jamie Gennis6547ff42013-07-16 20:12:42 -07004099// This should only be called from the main thread. Otherwise it would need
4100// the lock and should use mCurrentState rather than mDrawingState.
4101void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004102 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004103 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004104 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004105
4106 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4107}
4108
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004109void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004110{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004111 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004112
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004113 if (isLayerTripleBufferingDisabled())
4114 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004115
4116 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004117 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004118 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004119 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004120 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4121 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004122 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004123}
4124
Dan Stozab90cf072015-03-05 11:05:59 -08004125void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4126{
4127 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004128 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4129 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004130 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004131 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004132 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4133 b + 1, bucketTimeSec, percent);
4134 }
David Sodman4a36e932017-11-07 14:29:47 -08004135 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 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[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004138 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004139 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004140}
4141
Dan Stozae77c7662016-05-13 11:37:28 -07004142void SurfaceFlinger::recordBufferingStats(const char* layerName,
4143 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004144 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4145 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004146 for (const auto& segment : history) {
4147 if (!segment.usedThirdBuffer) {
4148 stats.twoBufferTime += segment.totalTime;
4149 }
4150 if (segment.occupancyAverage < 1.0f) {
4151 stats.doubleBufferedTime += segment.totalTime;
4152 } else if (segment.occupancyAverage < 2.0f) {
4153 stats.tripleBufferedTime += segment.totalTime;
4154 }
4155 ++stats.numSegments;
4156 stats.totalTime += segment.totalTime;
4157 }
4158}
4159
Brian Andersond6927fb2016-07-23 23:37:30 -07004160void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4161 result.appendFormat("Layer frame timestamps:\n");
4162
4163 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4164 const size_t count = currentLayers.size();
4165 for (size_t i=0 ; i<count ; i++) {
4166 currentLayers[i]->dumpFrameEvents(result);
4167 }
4168}
4169
Dan Stozae77c7662016-05-13 11:37:28 -07004170void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4171 result.append("Buffering stats:\n");
4172 result.append(" [Layer name] <Active time> <Two buffer> "
4173 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004174 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004175 typedef std::tuple<std::string, float, float, float> BufferTuple;
4176 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004177 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004178 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004179 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004180 if (stats.numSegments == 0) {
4181 continue;
4182 }
4183 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4184 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4185 stats.totalTime;
4186 float doubleBufferRatio = static_cast<float>(
4187 stats.doubleBufferedTime) / stats.totalTime;
4188 float tripleBufferRatio = static_cast<float>(
4189 stats.tripleBufferedTime) / stats.totalTime;
4190 sorted.insert({activeTime, {name, twoBufferRatio,
4191 doubleBufferRatio, tripleBufferRatio}});
4192 }
4193 for (const auto& sortedPair : sorted) {
4194 float activeTime = sortedPair.first;
4195 const BufferTuple& values = sortedPair.second;
4196 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4197 std::get<0>(values).c_str(), activeTime,
4198 std::get<1>(values), std::get<2>(values),
4199 std::get<3>(values));
4200 }
4201 result.append("\n");
4202}
4203
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004204void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004205 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004206 const int32_t displayId = display->getId();
4207 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4208 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004209 continue;
4210 }
4211
Dominik Laskowski7e045462018-05-30 13:02:02 -07004212 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004213 uint8_t port;
4214 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004215 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004216 result.append("no identification data\n");
4217 continue;
4218 }
4219
4220 if (!isEdid(data)) {
4221 result.append("unknown identification data: ");
4222 for (uint8_t byte : data) {
4223 result.appendFormat("%x ", byte);
4224 }
4225 result.append("\n");
4226 continue;
4227 }
4228
4229 const auto edid = parseEdid(data);
4230 if (!edid) {
4231 result.append("invalid EDID: ");
4232 for (uint8_t byte : data) {
4233 result.appendFormat("%x ", byte);
4234 }
4235 result.append("\n");
4236 continue;
4237 }
4238
4239 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4240 result.append(edid->displayName.data(), edid->displayName.length());
4241 result.append("\"\n");
4242 }
4243 result.append("\n");
4244}
4245
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004246void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4247 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004248 result.appendFormat("DisplayColorSetting: %s\n",
4249 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004250
4251 // TODO: print out if wide-color mode is active or not
4252
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004253 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004254 const int32_t displayId = display->getId();
4255 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004256 continue;
4257 }
4258
Dominik Laskowski7e045462018-05-30 13:02:02 -07004259 result.appendFormat("Display %d color modes:\n", displayId);
4260 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004261 for (auto&& mode : modes) {
4262 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4263 }
4264
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004265 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004266 result.appendFormat(" Current color mode: %s (%d)\n",
4267 decodeColorMode(currentMode).c_str(), currentMode);
4268 }
4269 result.append("\n");
4270}
4271
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004272LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004273 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004274 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4275 const State& state = useDrawing ? mDrawingState : mCurrentState;
4276 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004277 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004278 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004279 });
4280
4281 return layersProto;
4282}
4283
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004284LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004285 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004286
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004287 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004288 resolution->set_w(display.getWidth());
4289 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004290
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004291 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4292 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4293 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004294
Dominik Laskowski7e045462018-05-30 13:02:02 -07004295 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004296 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004297 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004298 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004299 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004300 }
4301 });
4302
4303 return layersProto;
4304}
4305
Mathias Agopian74d211a2013-04-22 16:55:35 +02004306void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4307 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004308{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004309 bool colorize = false;
4310 if (index < args.size()
4311 && (args[index] == String16("--color"))) {
4312 colorize = true;
4313 index++;
4314 }
4315
4316 Colorizer colorizer(colorize);
4317
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004318 // figure out if we're stuck somewhere
4319 const nsecs_t now = systemTime();
4320 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4321 const nsecs_t inTransaction(mDebugInTransaction);
4322 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4323 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4324
4325 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004326 * Dump library configuration.
4327 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004328
4329 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004330 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004331 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004332 appendSfConfigString(result);
4333 appendUiConfigString(result);
4334 appendGuiConfigString(result);
4335 result.append("\n");
4336
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004337 result.append("\nDisplay identification data:\n");
4338 dumpDisplayIdentificationData(result);
4339
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004340 result.append("\nWide-Color information:\n");
4341 dumpWideColorInfo(result);
4342
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004343 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004344 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004345 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004346 result.append(SyncFeatures::getInstance().toString());
4347 result.append("\n");
4348
Andy McFadden41d67d72014-04-25 16:58:34 -07004349 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004350 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004351 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004352
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004353 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4354 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004355 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4356 getHwComposer().isConnected(displayId)) {
4357 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004358 result.appendFormat("Display %d: "
4359 "app phase %" PRId64 " ns, "
4360 "sf phase %" PRId64 " ns, "
4361 "early app phase %" PRId64 " ns, "
4362 "early sf phase %" PRId64 " ns, "
4363 "early app gl phase %" PRId64 " ns, "
4364 "early sf gl phase %" PRId64 " ns, "
4365 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4366 displayId,
4367 vsyncPhaseOffsetNs,
4368 sfVsyncPhaseOffsetNs,
4369 appEarlyOffset,
4370 sfEarlyOffset,
4371 appEarlyGlOffset,
4372 sfEarlyOffset,
4373 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004374 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004375 result.append("\n");
4376
Dan Stozab90cf072015-03-05 11:05:59 -08004377 // Dump static screen stats
4378 result.append("\n");
4379 dumpStaticScreenStats(result);
4380 result.append("\n");
4381
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004382 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4383
Dan Stozae77c7662016-05-13 11:37:28 -07004384 dumpBufferingStats(result);
4385
Andy McFadden4803b742012-09-24 19:07:20 -07004386 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004387 * Dump the visible layer list
4388 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004389 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004390 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004391 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4392 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004393 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004394
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004395 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004396 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004397 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004398 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004399
4400 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004401 * Dump Display state
4402 */
4403
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004404 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004405 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004406 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004407 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004408 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004409 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004410 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004411
4412 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004413 * Dump SurfaceFlinger global state
4414 */
4415
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004416 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004417 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004418 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004419
Mathias Agopian888c8222012-08-04 21:10:38 -07004420 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004421 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004422
David Sodmanbc815282017-11-05 18:57:52 -08004423 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004424
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004425 if (display) {
4426 display->undefinedRegion.dump(result, "undefinedRegion");
4427 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4428 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004429 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004430 result.appendFormat(" last eglSwapBuffers() time: %f us\n"
4431 " last transaction time : %f us\n"
4432 " transaction-flags : %08x\n"
4433 " gpu_to_cpu_unsupported : %d\n",
4434 mLastSwapBufferTime / 1000.0, mLastTransactionTime / 1000.0,
4435 mTransactionFlags, !mGpuToCpuSupported);
4436
4437 if (display) {
4438 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4439 result.appendFormat(" refresh-rate : %f fps\n"
4440 " x-dpi : %f\n"
4441 " y-dpi : %f\n",
4442 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4443 activeConfig->getDpiY());
4444 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004445
Mathias Agopian74d211a2013-04-22 16:55:35 +02004446 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004447 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004448
Mathias Agopian74d211a2013-04-22 16:55:35 +02004449 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004450 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004451
4452 /*
4453 * VSYNC state
4454 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004455 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004456 result.append("\n");
4457
4458 /*
4459 * HWC layer minidump
4460 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004461 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004462 const int32_t displayId = display->getId();
4463 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004464 continue;
4465 }
4466
Dominik Laskowski7e045462018-05-30 13:02:02 -07004467 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004468 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004469 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004470 result.append("\n");
4471 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004472
4473 /*
4474 * Dump HWComposer state
4475 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004476 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004477 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004478 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004479 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004480 result.appendFormat(" h/w composer %s\n",
4481 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004482 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004483
4484 /*
4485 * Dump gralloc state
4486 */
4487 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4488 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004489
4490 /*
4491 * Dump VrFlinger state if in use.
4492 */
4493 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4494 result.append("VrFlinger state:\n");
4495 result.append(mVrFlinger->Dump().c_str());
4496 result.append("\n");
4497 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004498}
4499
Dominik Laskowski7e045462018-05-30 13:02:02 -07004500const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004501 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004502 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004503 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004504 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004505 }
4506 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004507
4508 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4509 static const Vector<sp<Layer>> empty;
4510 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004511}
4512
Keun young Park63f165f2012-08-31 10:53:36 -07004513bool SurfaceFlinger::startDdmConnection()
4514{
4515 void* libddmconnection_dso =
4516 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4517 if (!libddmconnection_dso) {
4518 return false;
4519 }
4520 void (*DdmConnection_start)(const char* name);
4521 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004522 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004523 if (!DdmConnection_start) {
4524 dlclose(libddmconnection_dso);
4525 return false;
4526 }
4527 (*DdmConnection_start)(getServiceName());
4528 return true;
4529}
4530
Chia-I Wu28f320b2018-05-03 11:02:56 -07004531void SurfaceFlinger::updateColorMatrixLocked() {
4532 mat4 colorMatrix;
4533 if (mGlobalSaturationFactor != 1.0f) {
4534 // Rec.709 luma coefficients
4535 float3 luminance{0.213f, 0.715f, 0.072f};
4536 luminance *= 1.0f - mGlobalSaturationFactor;
4537 mat4 saturationMatrix = mat4(
4538 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4539 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4540 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4541 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4542 );
4543 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4544 } else {
4545 colorMatrix = mClientColorMatrix * mDaltonizer();
4546 }
4547
4548 if (mCurrentState.colorMatrix != colorMatrix) {
4549 mCurrentState.colorMatrix = colorMatrix;
4550 mCurrentState.colorMatrixChanged = true;
4551 setTransactionFlags(eTransactionNeeded);
4552 }
4553}
4554
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004555status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulece2437712018-07-19 17:01:45 -07004556#pragma clang diagnostic push
4557#pragma clang diagnostic error "-Wswitch-enum"
4558 switch (static_cast<ISurfaceComposerTag>(code)) {
4559 // These methods should at minimum make sure that the client requested
4560 // access to SF.
4561 case AUTHENTICATE_SURFACE:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004562 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004563 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulece2437712018-07-19 17:01:45 -07004564 case CREATE_CONNECTION:
4565 case CREATE_DISPLAY:
4566 case DESTROY_DISPLAY:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004567 case ENABLE_VSYNC_INJECTIONS:
Ana Krulece2437712018-07-19 17:01:45 -07004568 case GET_ACTIVE_COLOR_MODE:
4569 case GET_ANIMATION_FRAME_STATS:
4570 case GET_HDR_CAPABILITIES:
4571 case GET_DISPLAY_COLOR_MODES:
4572 case SET_ACTIVE_CONFIG:
4573 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004574 case INJECT_VSYNC:
Ana Krulece2437712018-07-19 17:01:45 -07004575 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004576 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4577 IPCThreadState* ipc = IPCThreadState::self();
4578 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4579 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004580 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004581 }
Robert Carr1db73f62016-12-21 12:58:51 -08004582 return OK;
4583 }
Ana Krulece2437712018-07-19 17:01:45 -07004584 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004585 IPCThreadState* ipc = IPCThreadState::self();
4586 const int pid = ipc->getCallingPid();
4587 const int uid = ipc->getCallingUid();
Ana Krulece2437712018-07-19 17:01:45 -07004588 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4589 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004590 return PERMISSION_DENIED;
4591 }
Ana Krulece2437712018-07-19 17:01:45 -07004592 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004593 }
Ana Krulece2437712018-07-19 17:01:45 -07004594 // Used by apps to hook Choreographer to SurfaceFlinger.
4595 case CREATE_DISPLAY_EVENT_CONNECTION:
4596 // The following calls are currently used by clients that do not
4597 // request necessary permissions. However, they do not expose any secret
4598 // information, so it is OK to pass them.
4599 case GET_ACTIVE_CONFIG:
4600 case GET_BUILT_IN_DISPLAY:
4601 case GET_DISPLAY_CONFIGS:
4602 case GET_DISPLAY_STATS:
4603 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4604 // Calling setTransactionState is safe, because you need to have been
4605 // granted a reference to Client* and Handle* to do anything with it.
4606 case SET_TRANSACTION_STATE:
4607 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4608 case CREATE_SCOPED_CONNECTION: {
4609 return OK;
4610 }
4611 case CAPTURE_LAYERS:
4612 case CAPTURE_SCREEN: {
4613 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004614 IPCThreadState* ipc = IPCThreadState::self();
4615 const int pid = ipc->getCallingPid();
4616 const int uid = ipc->getCallingUid();
4617 if ((uid != AID_GRAPHICS) &&
4618 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4619 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4620 return PERMISSION_DENIED;
4621 }
Ana Krulece2437712018-07-19 17:01:45 -07004622 return OK;
4623 }
4624 // The following codes are deprecated and should never be allowed to access SF.
4625 case CONNECT_DISPLAY_UNUSED:
4626 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4627 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4628 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004629 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004630 }
Ana Krulece2437712018-07-19 17:01:45 -07004631
Ana Krulec562aee02018-08-08 14:13:44 -07004632 // These codes are used for the IBinder protocol to either interrogate the recipient
4633 // side of the transaction for its canonical interface descriptor or to dump its state.
4634 // We let them pass by default.
4635 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION) {
Ana Krulece2437712018-07-19 17:01:45 -07004636 return OK;
4637 }
David Sodmandeed4e72018-08-08 12:44:26 -07004638 // Numbers from 1000 to 1029 are currently use for backdoors. The code
Ana Krulece2437712018-07-19 17:01:45 -07004639 // in onTransact verifies that the user is root, and has access to use SF.
David Sodmandeed4e72018-08-08 12:44:26 -07004640 if (code >= 1000 && code <= 1029) {
Ana Krulece2437712018-07-19 17:01:45 -07004641 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4642 return OK;
4643 }
4644 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4645 return PERMISSION_DENIED;
4646#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004647}
4648
Ana Krulece2437712018-07-19 17:01:45 -07004649status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4650 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004651 status_t credentialCheck = CheckTransactCodeCredentials(code);
4652 if (credentialCheck != OK) {
4653 return credentialCheck;
4654 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004655
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004656 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4657 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004658 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004659 IPCThreadState* ipc = IPCThreadState::self();
4660 const int uid = ipc->getCallingUid();
4661 if (CC_UNLIKELY(uid != AID_SYSTEM
4662 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004663 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004664 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004665 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004666 return PERMISSION_DENIED;
4667 }
4668 int n;
4669 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004670 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004671 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004672 return NO_ERROR;
4673 case 1002: // SHOW_UPDATES
4674 n = data.readInt32();
4675 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004676 invalidateHwcGeometry();
4677 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004678 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004679 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004680 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004681 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004682 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004683 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004684 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004685 setTransactionFlags(
4686 eTransactionNeeded|
4687 eDisplayTransactionNeeded|
4688 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004689 return NO_ERROR;
4690 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004691 case 1006:{ // send empty update
4692 signalRefresh();
4693 return NO_ERROR;
4694 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004695 case 1008: // toggle use of hw composer
4696 n = data.readInt32();
4697 mDebugDisableHWC = n ? 1 : 0;
4698 invalidateHwcGeometry();
4699 repaintEverything();
4700 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004701 case 1009: // toggle use of transform hint
4702 n = data.readInt32();
4703 mDebugDisableTransformHint = n ? 1 : 0;
4704 invalidateHwcGeometry();
4705 repaintEverything();
4706 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004707 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004708 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004709 reply->writeInt32(0);
4710 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004711 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004712 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004713 return NO_ERROR;
4714 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004715 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004716 if (!display) {
4717 return NAME_NOT_FOUND;
4718 }
4719
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004720 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004721 return NO_ERROR;
4722 }
4723 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004724 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004725 // daltonize
4726 n = data.readInt32();
4727 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004728 case 1:
4729 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4730 break;
4731 case 2:
4732 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4733 break;
4734 case 3:
4735 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4736 break;
4737 default:
4738 mDaltonizer.setType(ColorBlindnessType::None);
4739 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004740 }
4741 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004742 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004743 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004744 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004745 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004746
4747 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004748 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004749 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004750 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004751 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004752 // apply a color matrix
4753 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004754 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004755 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004756 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004757 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004758 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004759 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004760 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004761 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004762 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004763 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004764
4765 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4766 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004767 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004768 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4769 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4770 }
4771
Chia-I Wu28f320b2018-05-03 11:02:56 -07004772 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004773 return NO_ERROR;
4774 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004775 // This is an experimental interface
4776 // Needs to be shifted to proper binder interface when we productize
4777 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004778 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07004779 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004780 return NO_ERROR;
4781 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004782 case 1017: {
4783 n = data.readInt32();
4784 mForceFullDamage = static_cast<bool>(n);
4785 return NO_ERROR;
4786 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004787 case 1018: { // Modify Choreographer's phase offset
4788 n = data.readInt32();
4789 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4790 return NO_ERROR;
4791 }
4792 case 1019: { // Modify SurfaceFlinger's phase offset
4793 n = data.readInt32();
4794 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4795 return NO_ERROR;
4796 }
Irvel468051e2016-06-13 16:44:44 -07004797 case 1020: { // Layer updates interceptor
4798 n = data.readInt32();
4799 if (n) {
4800 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004801 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004802 }
4803 else{
4804 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004805 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004806 }
4807 return NO_ERROR;
4808 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004809 case 1021: { // Disable HWC virtual displays
4810 n = data.readInt32();
4811 mUseHwcVirtualDisplays = !n;
4812 return NO_ERROR;
4813 }
Romain Guy0147a172017-06-01 13:53:56 -07004814 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004815 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004816 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004817
Chia-I Wu28f320b2018-05-03 11:02:56 -07004818 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004819 return NO_ERROR;
4820 }
Romain Guy54f154a2017-10-24 21:40:32 +01004821 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004822 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004823 invalidateHwcGeometry();
4824 repaintEverything();
4825 return NO_ERROR;
4826 }
4827 case 1024: { // Is wide color gamut rendering/color management supported?
4828 reply->writeBool(hasWideColorDisplay);
4829 return NO_ERROR;
4830 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004831 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004832 n = data.readInt32();
4833 if (n) {
4834 ALOGV("LayerTracing enabled");
4835 mTracing.enable();
4836 doTracing("tracing.enable");
4837 reply->writeInt32(NO_ERROR);
4838 } else {
4839 ALOGV("LayerTracing disabled");
4840 status_t err = mTracing.disable();
4841 reply->writeInt32(err);
4842 }
4843 return NO_ERROR;
4844 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004845 case 1026: { // Get layer tracing status
4846 reply->writeBool(mTracing.isEnabled());
4847 return NO_ERROR;
4848 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004849 // Is a DisplayColorSetting supported?
4850 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004851 const auto display = getDefaultDisplayDevice();
4852 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004853 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004854 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004855
4856 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4857 switch (setting) {
4858 case DisplayColorSetting::MANAGED:
4859 reply->writeBool(hasWideColorDisplay);
4860 break;
4861 case DisplayColorSetting::UNMANAGED:
4862 reply->writeBool(true);
4863 break;
4864 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004865 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004866 break;
4867 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004868 reply->writeBool(
4869 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004870 break;
4871 }
4872 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004873 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004874 // Is VrFlinger active?
4875 case 1028: {
4876 Mutex::Autolock _l(mStateLock);
4877 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4878 return NO_ERROR;
4879 }
David Sodman6d46c1e2018-07-13 12:59:48 -07004880 case 1029: {
4881 // Code 1029 is an experimental feature that allows applications to
4882 // simulate a high frequency panel by setting a multiplier and divisor
4883 // on the VSYNC-sf clock. If either the multiplier or divisor are
4884 // 0, then the code will set both to 1 to return the VSYNC-sf clock
4885 // to it's normal frequency.
4886 int multiplier = data.readInt32();
4887 int divisor = data.readInt32();
4888
4889 if ((multiplier == 0) || (divisor == 0)) {
4890 multiplier = 1;
4891 divisor = 1;
4892 }
4893
4894 if ((multiplier == 1) && (divisor == 1)) {
4895 enableHardwareVsync();
4896 } else {
4897 disableHardwareVsync(true);
4898 }
4899 getBE().mHwc->getActiveConfig(DisplayDevice::DISPLAY_PRIMARY)
4900 ->scalePanelFrequency(multiplier, divisor);
4901 mPrimaryDispSync->scalePeriod(multiplier, divisor);
4902
4903 ATRACE_INT("PeriodMultiplier", multiplier);
4904 ATRACE_INT("PeriodDivisor", divisor);
4905 return NO_ERROR;
4906 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004907 }
4908 }
4909 return err;
4910}
4911
Steven Thomas6d8110b2017-08-31 18:24:21 -07004912void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004913 android_atomic_or(1, &mRepaintEverything);
4914 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004915}
4916
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004917// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4918class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004919public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004920 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4921 ~WindowDisconnector() {
4922 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004923 }
4924
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004925private:
4926 ANativeWindow* mWindow;
4927 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004928};
4929
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004930status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4931 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4932 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4933 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004934 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004935 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004936
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004937 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004938
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004939 const auto display = getDisplayDeviceLocked(displayToken);
4940 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004941
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004942 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004943
4944 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004945 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004946 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004947}
4948
4949status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004950 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004951 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004952 ATRACE_CALL();
4953
4954 class LayerRenderArea : public RenderArea {
4955 public:
Robert Carr578038f2018-03-09 12:25:24 -08004956 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4957 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004958 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004959 mLayer(layer),
4960 mCrop(crop),
4961 mFlinger(flinger),
4962 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004963 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004964 Rect getBounds() const override {
4965 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07004966 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07004967 }
Marissa Wall61c58622018-07-18 10:12:20 -07004968 int getHeight() const override {
4969 return mLayer->getActiveHeight(mLayer->getDrawingState());
4970 }
4971 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07004972 bool isSecure() const override { return false; }
4973 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004974 Rect getSourceCrop() const override {
4975 if (mCrop.isEmpty()) {
4976 return getBounds();
4977 } else {
4978 return mCrop;
4979 }
4980 }
Robert Carr578038f2018-03-09 12:25:24 -08004981 class ReparentForDrawing {
4982 public:
4983 const sp<Layer>& oldParent;
4984 const sp<Layer>& newParent;
4985
4986 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4987 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004988 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004989 }
Robert Carr15eae092018-03-23 13:43:53 -07004990 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004991 };
4992
4993 void render(std::function<void()> drawLayers) override {
4994 if (!mChildrenOnly) {
4995 mTransform = mLayer->getTransform().inverse();
4996 drawLayers();
4997 } else {
4998 Rect bounds = getBounds();
4999 screenshotParentLayer =
5000 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
5001 bounds.getWidth(), bounds.getHeight(), 0);
5002
5003 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5004 drawLayers();
5005 }
5006 }
chaviwa76b2712017-09-20 12:02:26 -07005007
chaviwa76b2712017-09-20 12:02:26 -07005008 private:
chaviw7206d492017-11-10 16:16:12 -08005009 const sp<Layer> mLayer;
5010 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005011
5012 // In the "childrenOnly" case we reparent the children to a screenshot
5013 // layer which has no properties set and which does not draw.
5014 sp<ContainerLayer> screenshotParentLayer;
5015 Transform mTransform;
5016
5017 SurfaceFlinger* mFlinger;
5018 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005019 };
5020
5021 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5022 auto parent = layerHandle->owner.promote();
5023
chaviw7206d492017-11-10 16:16:12 -08005024 if (parent == nullptr || parent->isPendingRemoval()) {
5025 ALOGE("captureLayers called with a removed parent");
5026 return NAME_NOT_FOUND;
5027 }
5028
Robert Carr578038f2018-03-09 12:25:24 -08005029 const int uid = IPCThreadState::self()->getCallingUid();
5030 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5031 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5032 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5033 return PERMISSION_DENIED;
5034 }
5035
chaviw7206d492017-11-10 16:16:12 -08005036 Rect crop(sourceCrop);
5037 if (sourceCrop.width() <= 0) {
5038 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005039 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005040 }
5041
5042 if (sourceCrop.height() <= 0) {
5043 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005044 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005045 }
5046
5047 int32_t reqWidth = crop.width() * frameScale;
5048 int32_t reqHeight = crop.height() * frameScale;
5049
Robert Carr578038f2018-03-09 12:25:24 -08005050 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005051
Robert Carr578038f2018-03-09 12:25:24 -08005052 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005053 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5054 if (!layer->isVisible()) {
5055 return;
Robert Carr578038f2018-03-09 12:25:24 -08005056 } else if (childrenOnly && layer == parent.get()) {
5057 return;
chaviwa76b2712017-09-20 12:02:26 -07005058 }
5059 visitor(layer);
5060 });
5061 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005062 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005063}
5064
5065status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5066 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005067 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005068 bool useIdentityTransform) {
5069 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005070
Iris Chang7501ed62018-04-30 14:45:42 +08005071 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07005072
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005073 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5074 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5075 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5076 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005077
5078 // This mutex protects syncFd and captureResult for communication of the return values from the
5079 // main thread back to this Binder thread
5080 std::mutex captureMutex;
5081 std::condition_variable captureCondition;
5082 std::unique_lock<std::mutex> captureLock(captureMutex);
5083 int syncFd = -1;
5084 std::optional<status_t> captureResult;
5085
Robert Carr03480e22018-01-04 16:02:06 -08005086 const int uid = IPCThreadState::self()->getCallingUid();
5087 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5088
Dominik Laskowski8c001672018-05-30 16:52:06 -07005089 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005090 // If there is a refresh pending, bug out early and tell the binder thread to try again
5091 // after the refresh.
5092 if (mRefreshPending) {
5093 ATRACE_NAME("Skipping screenshot for now");
5094 std::unique_lock<std::mutex> captureLock(captureMutex);
5095 captureResult = std::make_optional<status_t>(EAGAIN);
5096 captureCondition.notify_one();
5097 return;
5098 }
5099
5100 status_t result = NO_ERROR;
5101 int fd = -1;
5102 {
5103 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005104 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005105 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5106 useIdentityTransform, forSystem, &fd);
5107 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005108 }
5109
5110 {
5111 std::unique_lock<std::mutex> captureLock(captureMutex);
5112 syncFd = fd;
5113 captureResult = std::make_optional<status_t>(result);
5114 captureCondition.notify_one();
5115 }
5116 });
5117
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005118 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005119 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005120 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005121 while (*captureResult == EAGAIN) {
5122 captureResult.reset();
5123 result = postMessageAsync(message);
5124 if (result != NO_ERROR) {
5125 return result;
5126 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005127 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005128 }
5129 result = *captureResult;
5130 }
5131
5132 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005133 sync_wait(syncFd, -1);
5134 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005135 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005136
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005137 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005138}
5139
chaviwa76b2712017-09-20 12:02:26 -07005140void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5141 TraverseLayersFunction traverseLayers, bool yswap,
5142 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005143 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005144
Lloyd Pique144e1162017-12-20 16:44:52 -08005145 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005146
5147 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005148 const auto raWidth = renderArea.getWidth();
5149 const auto raHeight = renderArea.getHeight();
5150
5151 const auto reqWidth = renderArea.getReqWidth();
5152 const auto reqHeight = renderArea.getReqHeight();
5153 Rect sourceCrop = renderArea.getSourceCrop();
5154
Iris Chang7501ed62018-04-30 14:45:42 +08005155 bool filtering = false;
5156 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5157 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5158 static_cast<int32_t>(reqHeight) != raWidth;
5159 } else {
5160 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5161 static_cast<int32_t>(reqHeight) != raHeight;
5162 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005163
Dan Stozac1879002014-05-22 15:59:05 -07005164 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005165 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005166 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005167 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005168 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5169 Transform tr;
5170 uint32_t flags = 0x00;
5171 switch (mPrimaryDisplayOrientation) {
5172 case DisplayState::eOrientation90:
5173 flags = Transform::ROT_90;
5174 break;
5175 case DisplayState::eOrientation180:
5176 flags = Transform::ROT_180;
5177 break;
5178 case DisplayState::eOrientation270:
5179 flags = Transform::ROT_270;
5180 break;
5181 }
5182 tr.set(flags, raWidth, raHeight);
5183 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005184 }
5185
5186 // ensure that sourceCrop is inside screen
5187 if (sourceCrop.left < 0) {
5188 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5189 }
chaviwa76b2712017-09-20 12:02:26 -07005190 if (sourceCrop.right > raWidth) {
5191 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005192 }
5193 if (sourceCrop.top < 0) {
5194 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5195 }
chaviwa76b2712017-09-20 12:02:26 -07005196 if (sourceCrop.bottom > raHeight) {
5197 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005198 }
5199
Chia-I Wu36574d92018-05-16 10:54:36 -07005200 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5201 engine.setOutputDataSpace(Dataspace::SRGB);
5202 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005203
Mathias Agopian180f10d2013-04-10 22:55:41 -07005204 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005205 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005206
Iris Chang7501ed62018-04-30 14:45:42 +08005207 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5208 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5209 // convert hw orientation into flag presentation
5210 // here inverse transform needed
5211 uint8_t hw_rot_90 = 0x00;
5212 uint8_t hw_flip_hv = 0x00;
5213 switch (mPrimaryDisplayOrientation) {
5214 case DisplayState::eOrientation90:
5215 hw_rot_90 = Transform::ROT_90;
5216 hw_flip_hv = Transform::ROT_180;
5217 break;
5218 case DisplayState::eOrientation180:
5219 hw_flip_hv = Transform::ROT_180;
5220 break;
5221 case DisplayState::eOrientation270:
5222 hw_rot_90 = Transform::ROT_90;
5223 break;
5224 }
5225
5226 // transform flags operation
5227 // 1) flip H V if both have ROT_90 flag
5228 // 2) XOR these flags
5229 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5230 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5231 if (rotation_rot_90 & hw_rot_90) {
5232 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5233 }
5234 rotation = static_cast<Transform::orientation_flags>
5235 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5236 }
5237
Mathias Agopian180f10d2013-04-10 22:55:41 -07005238 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005239 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005240 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005241 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005242
chaviw50da5042018-04-09 13:49:37 -07005243 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005244 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005245 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005246
chaviwa76b2712017-09-20 12:02:26 -07005247 traverseLayers([&](Layer* layer) {
5248 if (filtering) layer->setFiltering(true);
David Sodmanca10ed22018-04-16 14:10:25 -07005249 layer->drawNow(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005250 if (filtering) layer->setFiltering(false);
5251 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005252}
5253
chaviwa76b2712017-09-20 12:02:26 -07005254status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5255 TraverseLayersFunction traverseLayers,
5256 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005257 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005258 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005259 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005260 ATRACE_CALL();
5261
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005262 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005263
5264 traverseLayers([&](Layer* layer) {
5265 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5266 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005267
Robert Carr03480e22018-01-04 16:02:06 -08005268 // We allow the system server to take screenshots of secure layers for
5269 // use in situations like the Screen-rotation animation and place
5270 // the impetus on WindowManager to not persist them.
5271 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005272 ALOGW("FB is protected: PERMISSION_DENIED");
5273 return PERMISSION_DENIED;
5274 }
5275
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005276 // this binds the given EGLImage as a framebuffer for the
5277 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005278 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005279 if (bufferBond.getStatus() != NO_ERROR) {
5280 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005281 return INVALID_OPERATION;
5282 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005283
Dan Stozaabcda352017-06-01 14:37:39 -07005284 // this will in fact render into our dequeued buffer
5285 // via an FBO, which means we didn't have to create
5286 // an EGLSurface and therefore we're not
5287 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005288 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005289
Dan Stozaabcda352017-06-01 14:37:39 -07005290 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005291 getRenderEngine().finish();
5292 *outSyncFd = -1;
5293
chaviwa76b2712017-09-20 12:02:26 -07005294 const auto reqWidth = renderArea.getReqWidth();
5295 const auto reqHeight = renderArea.getReqHeight();
5296
Dan Stozaabcda352017-06-01 14:37:39 -07005297 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5298 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005299 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005300 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005301 } else {
5302 base::unique_fd syncFd = getRenderEngine().flush();
5303 if (syncFd < 0) {
5304 getRenderEngine().finish();
5305 }
5306 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005307 }
5308
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005309 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005310}
5311
Mathias Agopiand5556842013-09-19 17:08:37 -07005312void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005313 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005314 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005315 for (size_t y = 0; y < h; y++) {
5316 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5317 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005318 if (p[x] != 0xFF000000) return;
5319 }
5320 }
chaviwa76b2712017-09-20 12:02:26 -07005321 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005322
Robert Carr2047fae2016-11-28 14:09:09 -08005323 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005324 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005325 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005326 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5327 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5328 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5329 static_cast<float>(state.color.a));
5330 i++;
5331 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005332 }
5333}
5334
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005335// ---------------------------------------------------------------------------
5336
Dan Stoza412903f2017-04-27 13:42:17 -07005337void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5338 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005339}
5340
Dan Stoza412903f2017-04-27 13:42:17 -07005341void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5342 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005343}
5344
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005345void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5346 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005347 const LayerVector::Visitor& visitor) {
5348 // We loop through the first level of layers without traversing,
5349 // as we need to interpret min/max layer Z in the top level Z space.
5350 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005351 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005352 continue;
5353 }
5354 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005355 // relative layers are traversed in Layer::traverseInZOrder
5356 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005357 continue;
5358 }
5359 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005360 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005361 return;
5362 }
chaviwa76b2712017-09-20 12:02:26 -07005363 if (!layer->isVisible()) {
5364 return;
5365 }
5366 visitor(layer);
5367 });
5368 }
5369}
5370
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005371}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005372
Lloyd Pique074e8122018-07-26 12:57:23 -07005373
Mathias Agopian3f844832013-08-07 21:24:32 -07005374#if defined(__gl_h_)
5375#error "don't include gl/gl.h in this file"
5376#endif
5377
5378#if defined(__gl2_h_)
5379#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005380#endif