blob: f41102f556244be087399da03a8d24cdfd080c00 [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"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020066#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080067#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080070#include "DdmConnection.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070071#include "DispSync.h"
Robert Carr578038f2018-03-09 12:25:24 -080072#include "DisplayDevice.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070073#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080074#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070076#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080077#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078#include "SurfaceFlinger.h"
Robert Carr578038f2018-03-09 12:25:24 -080079#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080
Steven Thomasb02664d2017-07-26 18:48:28 -070081#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070082#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070083#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070084#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070085#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080086
Mathias Agopianff2ed702013-09-01 21:36:12 -070087#include "Effects/Daltonizer.h"
88
Mathias Agopian875d8e12013-06-07 15:35:48 -070089#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070090#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070091
Jiyong Park4b20c2e2017-01-14 19:45:11 +090092#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080093#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
94#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090095#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090096
chaviw1d044282017-09-27 12:19:28 -070097#include <layerproto/LayerProtoParser.h>
98
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080099#define DISPLAY_COUNT 1
100
Mathias Agopianfee2b462013-07-03 12:34:01 -0700101/*
102 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
103 * black pixels.
104 */
105#define DEBUG_SCREENSHOTS false
106
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800107namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700108
Jaesoo Lee43518572017-01-23 19:03:16 +0900109using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900110using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700111using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700112using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700113using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700114using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900115
Steven Thomasb02664d2017-07-26 18:48:28 -0700116namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700117
118#pragma clang diagnostic push
119#pragma clang diagnostic error "-Wswitch-enum"
120
121bool isWideColorMode(const ColorMode colorMode) {
122 switch (colorMode) {
123 case ColorMode::DISPLAY_P3:
124 case ColorMode::ADOBE_RGB:
125 case ColorMode::DCI_P3:
126 case ColorMode::BT2020:
127 case ColorMode::BT2100_PQ:
128 case ColorMode::BT2100_HLG:
129 return true;
130 case ColorMode::NATIVE:
131 case ColorMode::STANDARD_BT601_625:
132 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
133 case ColorMode::STANDARD_BT601_525:
134 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
135 case ColorMode::STANDARD_BT709:
136 case ColorMode::SRGB:
137 return false;
138 }
139 return false;
140}
141
142#pragma clang diagnostic pop
143
Steven Thomasb02664d2017-07-26 18:48:28 -0700144class ConditionalLock {
145public:
146 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
147 if (lock) {
148 mMutex.lock();
149 }
150 }
151 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
152private:
153 Mutex& mMutex;
154 bool mLocked;
155};
Peiyong Linfca547f2018-07-09 13:03:33 -0700156
Steven Thomasb02664d2017-07-26 18:48:28 -0700157} // namespace anonymous
158
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800159// ---------------------------------------------------------------------------
160
Mathias Agopian99b49842011-06-27 16:05:52 -0700161const String16 sHardwareTest("android.permission.HARDWARE_TEST");
162const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
163const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
164const String16 sDump("android.permission.DUMP");
165
166// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800167int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
168int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700169int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700170bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800171uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800172bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800173bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800174int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800175// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600176bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700177
Kalle Raitaa099a242017-01-11 11:17:29 -0800178
179std::string getHwcServiceName() {
180 char value[PROPERTY_VALUE_MAX] = {};
181 property_get("debug.sf.hwc_service_name", value, "default");
182 ALOGI("Using HWComposer service: '%s'", value);
183 return std::string(value);
184}
185
186bool useTrebleTestingOverride() {
187 char value[PROPERTY_VALUE_MAX] = {};
188 property_get("debug.sf.treble_testing_override", value, "false");
189 ALOGI("Treble testing override: '%s'", value);
190 return std::string(value) == "true";
191}
192
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800193std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
194 switch(displayColorSetting) {
195 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700196 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800197 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700198 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800199 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700200 return std::string("Enhanced");
201 default:
202 return std::string("Unknown ") +
203 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800204 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800205}
206
Lloyd Pique99d3da52018-01-22 17:48:03 -0800207NativeWindowSurface::~NativeWindowSurface() = default;
208
209namespace impl {
210
211class NativeWindowSurface final : public android::NativeWindowSurface {
212public:
213 static std::unique_ptr<android::NativeWindowSurface> create(
214 const sp<IGraphicBufferProducer>& producer) {
215 return std::make_unique<NativeWindowSurface>(producer);
216 }
217
218 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
219 : surface(new Surface(producer, false)) {}
220
221 ~NativeWindowSurface() override = default;
222
223private:
224 sp<ANativeWindow> getNativeWindow() const override { return surface; }
225
226 void preallocateBuffers() override { surface->allocateBuffers(); }
227
228 sp<Surface> surface;
229};
230
231} // namespace impl
232
David Sodmanbc815282017-11-05 18:57:52 -0800233SurfaceFlingerBE::SurfaceFlingerBE()
234 : mHwcServiceName(getHwcServiceName()),
235 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800236 mFrameBuckets(),
237 mTotalTime(0),
238 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800239 mComposerSequenceId(0) {
240}
241
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800242SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800243 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800244 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700245 mTransactionPending(false),
246 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700247 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700248 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700249 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800250 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700251 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800252 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800253 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800254 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800255 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800256 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700257 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700258 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700259 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700260 mDebugInSwapBuffers(0),
261 mLastSwapBufferTime(0),
262 mDebugInTransaction(0),
263 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700264 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000265 mPrimaryDispSync("PrimaryDispSync"),
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
David Sodman99974d22017-11-28 12:04:33 -0800326 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700327
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800328 // debugging stuff...
329 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700330
Mathias Agopianb4b17302013-03-20 18:36:41 -0700331 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700332 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700333
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800334 property_get("debug.sf.showupdates", value, "0");
335 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700336
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700337 property_get("debug.sf.ddms", value, "0");
338 mDebugDDMS = atoi(value);
339 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700340 if (!startDdmConnection()) {
341 // start failed, and DDMS debugging not enabled
342 mDebugDDMS = 0;
343 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700344 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700345 ALOGI_IF(mDebugRegion, "showupdates enabled");
346 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700347
348 property_get("debug.sf.disable_backpressure", value, "0");
349 mPropagateBackpressure = !atoi(value);
350 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700351
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800352 property_get("debug.sf.enable_hwc_vds", value, "0");
353 mUseHwcVirtualDisplays = atoi(value);
354 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800355
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800356 property_get("ro.sf.disable_triple_buffer", value, "1");
357 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800358 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700359
Yiwei Zhang243b3782018-05-15 17:40:04 -0700360 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700361 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
362 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
363
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200364 property_get("debug.sf.early_phase_offset_ns", value, "-1");
365 const int earlySfOffsetNs = atoi(value);
366
367 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
368 const int earlyGlSfOffsetNs = atoi(value);
369
370 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
371 const int earlyAppOffsetNs = atoi(value);
372
373 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
374 const int earlyGlAppOffsetNs = atoi(value);
375
376 const VSyncModulator::Offsets earlyOffsets =
377 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
378 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
379 const VSyncModulator::Offsets earlyGlOffsets =
380 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
381 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
382 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
383 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700384
Romain Guy11d63f42017-07-20 12:47:14 -0700385 // We should be reading 'persist.sys.sf.color_saturation' here
386 // but since /data may be encrypted, we need to wait until after vold
387 // comes online to attempt to read the property. The property is
388 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800389
390 if (useTrebleTestingOverride()) {
391 // Without the override SurfaceFlinger cannot connect to HIDL
392 // services that are not listed in the manifests. Considered
393 // deriving the setting from the set service name, but it
394 // would be brittle if the name that's not 'default' is used
395 // for production purposes later on.
396 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
397 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800398}
399
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800400void SurfaceFlinger::onFirstRef()
401{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800402 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800403}
404
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800405SurfaceFlinger::~SurfaceFlinger()
406{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800407}
408
Dan Stozac7014012014-02-14 15:03:43 -0800409void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800410{
411 // the window manager died on us. prepare its eulogy.
412
Andy McFadden13a082e2012-08-24 10:16:42 -0700413 // restore initial conditions (default device unblank, etc)
414 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800415
416 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700417 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800418}
419
Robert Carr1db73f62016-12-21 12:58:51 -0800420static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700421 status_t err = client->initCheck();
422 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800423 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800424 }
Robert Carr1db73f62016-12-21 12:58:51 -0800425 return nullptr;
426}
427
428sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
429 return initClient(new Client(this));
430}
431
432sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
433 const sp<IGraphicBufferProducer>& gbp) {
434 if (authenticateSurfaceTexture(gbp) == false) {
435 return nullptr;
436 }
437 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
438 if (layer == nullptr) {
439 return nullptr;
440 }
441
442 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800443}
444
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700445sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
446 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700447{
448 class DisplayToken : public BBinder {
449 sp<SurfaceFlinger> flinger;
450 virtual ~DisplayToken() {
451 // no more references, this display must be terminated
452 Mutex::Autolock _l(flinger->mStateLock);
453 flinger->mCurrentState.displays.removeItem(this);
454 flinger->setTransactionFlags(eDisplayTransactionNeeded);
455 }
456 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700457 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700458 : flinger(flinger) {
459 }
460 };
461
462 sp<BBinder> token = new DisplayToken(this);
463
464 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700465 DisplayDeviceState info;
466 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700467 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700468 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700469 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800470 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700471 return token;
472}
473
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700474void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700475 Mutex::Autolock _l(mStateLock);
476
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700477 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700478 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700479 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700480 return;
481 }
482
483 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700484 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700485 ALOGE("destroyDisplay called for non-virtual display");
486 return;
487 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700488 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700489 mCurrentState.displays.removeItemsAt(idx);
490 setTransactionFlags(eDisplayTransactionNeeded);
491}
492
Mathias Agopiane57f2922012-08-09 16:29:12 -0700493sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700494 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700495 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800496 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700497 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700498 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700499}
500
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800501void SurfaceFlinger::bootFinished()
502{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700503 if (mStartPropertySetThread->join() != NO_ERROR) {
504 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800505 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800506 const nsecs_t now = systemTime();
507 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000508 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700509
510 // wait patiently for the window manager death
511 const String16 name("window");
512 sp<IBinder> window(defaultServiceManager()->getService(name));
513 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700514 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700515 }
516
Steven Thomas050b2c82017-03-06 11:45:16 -0800517 if (mVrFlinger) {
518 mVrFlinger->OnBootFinished();
519 }
520
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700521 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700522 // formerly we would just kill the process, but we now ask it to exit so it
523 // can choose where to stop the animation.
524 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700525
526 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
527 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
528 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700529
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800530 postMessageAsync(new LambdaMessage([this] {
531 readPersistentProperties();
532 mBootStage = BootStage::FINISHED;
533 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800534}
535
Dan Stoza436ccf32018-06-21 12:10:12 -0700536uint32_t SurfaceFlinger::getNewTexture() {
537 {
538 std::lock_guard lock(mTexturePoolMutex);
539 if (!mTexturePool.empty()) {
540 uint32_t name = mTexturePool.back();
541 mTexturePool.pop_back();
542 ATRACE_INT("TexturePoolSize", mTexturePool.size());
543 return name;
544 }
545
546 // The pool was too small, so increase it for the future
547 ++mTexturePoolSize;
548 }
549
550 // The pool was empty, so we need to get a new texture name directly using a
551 // blocking call to the main thread
552 uint32_t name = 0;
553 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
554 return name;
555}
556
Mathias Agopian3f844832013-08-07 21:24:32 -0700557void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700558 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700559}
560
Lloyd Piquee83f9312018-02-01 12:53:17 -0800561class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700562public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700563 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000564 const char* name) :
565 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700566 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700567 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000568 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
569 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700570 mDispSync(dispSync),
571 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700572 mVsyncMutex(),
573 mPhaseOffset(phaseOffset),
574 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700575
Lloyd Piquee83f9312018-02-01 12:53:17 -0800576 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700577
Lloyd Piquee83f9312018-02-01 12:53:17 -0800578 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700579 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700580 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000581 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700582 static_cast<DispSync::Callback*>(this));
583 if (err != NO_ERROR) {
584 ALOGE("error registering vsync callback: %s (%d)",
585 strerror(-err), err);
586 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700587 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700588 } else {
589 status_t err = mDispSync->removeEventListener(
590 static_cast<DispSync::Callback*>(this));
591 if (err != NO_ERROR) {
592 ALOGE("error unregistering vsync callback: %s (%d)",
593 strerror(-err), err);
594 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700595 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700596 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700597 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700598 }
599
Lloyd Piquee83f9312018-02-01 12:53:17 -0800600 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700601 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700602 mCallback = callback;
603 }
604
Lloyd Piquee83f9312018-02-01 12:53:17 -0800605 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700606 Mutex::Autolock lock(mVsyncMutex);
607
608 // Normalize phaseOffset to [0, period)
609 auto period = mDispSync->getPeriod();
610 phaseOffset %= period;
611 if (phaseOffset < 0) {
612 // If we're here, then phaseOffset is in (-period, 0). After this
613 // operation, it will be in (0, period)
614 phaseOffset += period;
615 }
616 mPhaseOffset = phaseOffset;
617
618 // If we're not enabled, we don't need to mess with the listeners
619 if (!mEnabled) {
620 return;
621 }
622
Dan Stoza84d619e2018-03-28 17:07:36 -0700623 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
624 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700625 if (err != NO_ERROR) {
Dan Stoza84d619e2018-03-28 17:07:36 -0700626 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700627 strerror(-err), err);
628 }
629 }
630
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700631private:
632 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800633 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700634 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700635 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700636 callback = mCallback;
637
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700638 if (mTraceVsync) {
639 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700640 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700641 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700642 }
643
Peiyong Lin566a3b42018-01-09 18:22:43 -0800644 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700645 callback->onVSyncEvent(when);
646 }
647 }
648
Tim Murray4a4e4a22016-04-19 16:29:23 +0000649 const char* const mName;
650
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700651 int mValue;
652
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700653 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700654 const String8 mVsyncOnLabel;
655 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700656
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700657 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700658
659 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800660 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700661
662 Mutex mVsyncMutex; // Protects the following
663 nsecs_t mPhaseOffset;
664 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700665};
666
Lloyd Piquee83f9312018-02-01 12:53:17 -0800667class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700668public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800669 InjectVSyncSource() = default;
670 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700671
Lloyd Piquee83f9312018-02-01 12:53:17 -0800672 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700673 std::lock_guard<std::mutex> lock(mCallbackMutex);
674 mCallback = callback;
675 }
676
Lloyd Piquee83f9312018-02-01 12:53:17 -0800677 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700678 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700679 if (mCallback) {
680 mCallback->onVSyncEvent(when);
681 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700682 }
683
Lloyd Piquee83f9312018-02-01 12:53:17 -0800684 void setVSyncEnabled(bool) override {}
685 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700686
687private:
688 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800689 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700690};
691
Wei Wangf9b05ee2017-07-19 20:59:39 -0700692// Do not call property_set on main thread which will be blocked by init
693// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700694void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700695 ALOGI( "SurfaceFlinger's main thread ready to run. "
696 "Initializing graphics H/W...");
697
Thierry Strudel2924d012017-08-14 15:19:37 -0700698 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900699
Steven Thomasb02664d2017-07-26 18:48:28 -0700700 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800701
Steven Thomasb02664d2017-07-26 18:48:28 -0700702 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800703 mEventThreadSource =
704 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
705 true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800706 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700707 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800708 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800709 "appEventThread");
710 mSfEventThreadSource =
711 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
712 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800713
Lloyd Pique24b0a482018-03-09 18:52:26 -0800714 mSFEventThread =
715 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700716 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800717 [this](nsecs_t timestamp) {
718 mInterceptor->saveVSyncEvent(timestamp);
719 },
720 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800721 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200722 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800723
Steven Thomasb02664d2017-07-26 18:48:28 -0700724 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800725 getBE().mRenderEngine =
726 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
727 hasWideColorDisplay
728 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
729 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800730 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700731
732 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
733 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800734 getBE().mHwc.reset(
735 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700736 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800737 // Process any initial hotplug and resulting display changes.
738 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700739 const auto display = getDefaultDisplayDeviceLocked();
740 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
741 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
742 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800743
Lloyd Piquefcd86612017-12-14 17:15:36 -0800744 // make the default display GLContext current so that we can create textures
745 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700746 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800747
Steven Thomas050b2c82017-03-06 11:45:16 -0800748 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700749 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700750 // This callback is called from the vr flinger dispatch thread. We
751 // need to call signalTransaction(), which requires holding
752 // mStateLock when we're not on the main thread. Acquiring
753 // mStateLock from the vr flinger dispatch thread might trigger a
754 // deadlock in surface flinger (see b/66916578), so post a message
755 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700756 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700757 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
758 mVrFlingerRequestsDisplay = requestDisplay;
759 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700760 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800761 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700762 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
763 getHwComposer()
764 .getHwcDisplayId(display->getId())
765 .value_or(0),
766 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800767 if (!mVrFlinger) {
768 ALOGE("Failed to start vrflinger");
769 }
770 }
771
Lloyd Pique379adc12018-01-22 17:31:47 -0800772 mEventControlThread = std::make_unique<impl::EventControlThread>(
773 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700774
Mathias Agopian92a979a2012-08-02 18:32:23 -0700775 // initialize our drawing state
776 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700777
Andy McFadden13a082e2012-08-24 10:16:42 -0700778 // set initial conditions (e.g. unblank default device)
779 initializeDisplays();
David Sodman0756cdd2018-04-13 11:26:33 -0700780 ALOGV("Displays initialized");
Andy McFadden13a082e2012-08-24 10:16:42 -0700781
David Sodmanbc815282017-11-05 18:57:52 -0800782 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700783
Wei Wangf9b05ee2017-07-19 20:59:39 -0700784 // Inform native graphics APIs whether the present timestamp is supported:
785 if (getHwComposer().hasCapability(
786 HWC2::Capability::PresentFenceIsNotReliable)) {
787 mStartPropertySetThread = new StartPropertySetThread(false);
788 } else {
789 mStartPropertySetThread = new StartPropertySetThread(true);
790 }
791
792 if (mStartPropertySetThread->Start() != NO_ERROR) {
793 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800794 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800795
Chia-I Wud49d6692018-06-27 07:17:41 +0800796 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
797 // is used to saturate legacy sRGB content. However, to make sure the same color under
798 // Display P3 will be saturated to the same color, we intentionally break the API spec
799 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
800 // such saturation matrix on Display P3 is understood fully, the API should always return
801 // identify matrix.
802 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
803 Dataspace::SRGB_LINEAR);
804
805 // we will apply this on Display P3.
806 if (mEnhancedSaturationMatrix != mat4()) {
807 ColorSpace srgb(ColorSpace::sRGB());
808 ColorSpace displayP3(ColorSpace::DisplayP3());
809 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
810 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
811 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
812 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800813
Dan Stoza9e56aa02015-11-02 13:00:03 -0800814 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700815}
816
Romain Guy11d63f42017-07-20 12:47:14 -0700817void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700818 Mutex::Autolock _l(mStateLock);
819
Romain Guy11d63f42017-07-20 12:47:14 -0700820 char value[PROPERTY_VALUE_MAX];
821
822 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800823 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700824 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800825 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100826
827 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700828 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700829}
830
Mathias Agopiana67e4182012-06-19 17:26:12 -0700831void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800832 // Start boot animation service by setting a property mailbox
833 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700834 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800835 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700836 if (mStartPropertySetThread->join() != NO_ERROR) {
837 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800838 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700839}
840
Mathias Agopian875d8e12013-06-07 15:35:48 -0700841size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800842 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700843}
844
Mathias Agopian875d8e12013-06-07 15:35:48 -0700845size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800846 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700847}
848
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800849// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800850
Jamie Gennis582270d2011-08-17 18:19:00 -0700851bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800852 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800853 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800854 return authenticateSurfaceTextureLocked(bufferProducer);
855}
856
857bool SurfaceFlinger::authenticateSurfaceTextureLocked(
858 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800859 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800860 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800861}
862
Brian Anderson6b376712017-04-04 10:51:39 -0700863status_t SurfaceFlinger::getSupportedFrameTimestamps(
864 std::vector<FrameEvent>* outSupported) const {
865 *outSupported = {
866 FrameEvent::REQUESTED_PRESENT,
867 FrameEvent::ACQUIRE,
868 FrameEvent::LATCH,
869 FrameEvent::FIRST_REFRESH_START,
870 FrameEvent::LAST_REFRESH_START,
871 FrameEvent::GPU_COMPOSITION_DONE,
872 FrameEvent::DEQUEUE_READY,
873 FrameEvent::RELEASE,
874 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700875 ConditionalLock _l(mStateLock,
876 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700877 if (!getHwComposer().hasCapability(
878 HWC2::Capability::PresentFenceIsNotReliable)) {
879 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
880 }
881 return NO_ERROR;
882}
883
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700884status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
885 Vector<DisplayInfo>* configs) {
886 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700887 return BAD_VALUE;
888 }
889
Jesse Hall692c7232012-11-08 15:41:56 -0800890 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700891 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
892 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700893 type = i;
894 break;
895 }
896 }
897
898 if (type < 0) {
899 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700900 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700901
Mathias Agopian8b736f12012-08-13 17:54:26 -0700902 // TODO: Not sure if display density should handled by SF any longer
903 class Density {
904 static int getDensityFromProperty(char const* propName) {
905 char property[PROPERTY_VALUE_MAX];
906 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800907 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700908 density = atoi(property);
909 }
910 return density;
911 }
912 public:
913 static int getEmuDensity() {
914 return getDensityFromProperty("qemu.sf.lcd_density"); }
915 static int getBuildDensity() {
916 return getDensityFromProperty("ro.sf.lcd_density"); }
917 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700918
Dan Stoza7f7da322014-05-02 15:26:25 -0700919 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700920
Steven Thomas6d8110b2017-08-31 18:24:21 -0700921 ConditionalLock _l(mStateLock,
922 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800923 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700924 DisplayInfo info = DisplayInfo();
925
Dan Stoza9e56aa02015-11-02 13:00:03 -0800926 float xdpi = hwConfig->getDpiX();
927 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700928
929 if (type == DisplayDevice::DISPLAY_PRIMARY) {
930 // The density of the device is provided by a build property
931 float density = Density::getBuildDensity() / 160.0f;
932 if (density == 0) {
933 // the build doesn't provide a density -- this is wrong!
934 // use xdpi instead
935 ALOGE("ro.sf.lcd_density must be defined as a build property");
936 density = xdpi / 160.0f;
937 }
938 if (Density::getEmuDensity()) {
939 // if "qemu.sf.lcd_density" is specified, it overrides everything
940 xdpi = ydpi = density = Density::getEmuDensity();
941 density /= 160.0f;
942 }
943 info.density = density;
944
945 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700946 const auto display = getDefaultDisplayDeviceLocked();
947 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700948 } else {
949 // TODO: where should this value come from?
950 static const int TV_DENSITY = 213;
951 info.density = TV_DENSITY / 160.0f;
952 info.orientation = 0;
953 }
954
Dan Stoza9e56aa02015-11-02 13:00:03 -0800955 info.w = hwConfig->getWidth();
956 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700957 info.xdpi = xdpi;
958 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800959 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900960 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800961
Andy McFadden91b2ca82014-06-13 14:04:23 -0700962 // This is how far in advance a buffer must be queued for
963 // presentation at a given time. If you want a buffer to appear
964 // on the screen at time N, you must submit the buffer before
965 // (N - presentationDeadline).
966 //
967 // Normally it's one full refresh period (to give SF a chance to
968 // latch the buffer), but this can be reduced by configuring a
969 // DispSync offset. Any additional delays introduced by the hardware
970 // composer or panel must be accounted for here.
971 //
972 // We add an additional 1ms to allow for processing time and
973 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800974 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800975 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700976
977 // All non-virtual displays are currently considered secure.
978 info.secure = true;
979
Iris Chang7501ed62018-04-30 14:45:42 +0800980 if (type == DisplayDevice::DISPLAY_PRIMARY &&
981 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
982 std::swap(info.w, info.h);
983 }
984
Michael Wright28f24d02016-07-12 13:30:53 -0700985 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700986 }
987
Dan Stoza7f7da322014-05-02 15:26:25 -0700988 return NO_ERROR;
989}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700990
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700991status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
992 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700993 return BAD_VALUE;
994 }
995
996 // FIXME for now we always return stats for the primary display
997 memset(stats, 0, sizeof(*stats));
998 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
999 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
1000 return NO_ERROR;
1001}
1002
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001003int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
1004 const auto display = getDisplayDevice(displayToken);
1005 if (!display) {
1006 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +08001007 return BAD_VALUE;
1008 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001009
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001010 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -07001011}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001012
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001013void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
1014 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001015 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001016 return;
1017 }
1018
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001019 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001020 ALOGW("Trying to set config for virtual display");
1021 return;
1022 }
1023
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001024 display->setActiveConfig(mode);
1025 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001026}
1027
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001028status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001029 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001030 Vector<DisplayInfo> configs;
1031 getDisplayConfigs(displayToken, &configs);
1032 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
1033 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
1034 configs.size());
1035 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001036 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001037 const auto display = getDisplayDevice(displayToken);
1038 if (!display) {
1039 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
1040 displayToken.get());
1041 } else if (display->isVirtual()) {
1042 ALOGW("Attempt to set active config %d for virtual display", mode);
1043 } else {
1044 setActiveConfigInternal(display, mode);
1045 }
1046 }));
1047
Mathias Agopian888c8222012-08-04 21:10:38 -07001048 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001049}
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001050status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1051 Vector<ColorMode>* outColorModes) {
1052 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001053 return BAD_VALUE;
1054 }
1055
Michael Wright28f24d02016-07-12 13:30:53 -07001056 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001057 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
1058 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -07001059 type = i;
1060 break;
1061 }
1062 }
1063
1064 if (type < 0) {
1065 return type;
1066 }
1067
Peiyong Lina52f0292018-03-14 17:26:31 -07001068 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001069 {
1070 ConditionalLock _l(mStateLock,
1071 std::this_thread::get_id() != mMainThreadId);
1072 modes = getHwComposer().getColorModes(type);
1073 }
Michael Wright28f24d02016-07-12 13:30:53 -07001074 outColorModes->clear();
1075 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1076
1077 return NO_ERROR;
1078}
1079
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001080ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1081 if (const auto display = getDisplayDevice(displayToken)) {
1082 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001083 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001084 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001085}
1086
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001087void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1088 Dataspace dataSpace, RenderIntent renderIntent) {
1089 ColorMode currentMode = display->getActiveColorMode();
1090 Dataspace currentDataSpace = display->getCompositionDataSpace();
1091 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001092
Peiyong Lin38e9a562018-04-10 16:24:20 -07001093 if (mode == currentMode && dataSpace == currentDataSpace &&
1094 renderIntent == currentRenderIntent) {
1095 return;
1096 }
1097
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001098 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001099 ALOGW("Trying to set config for virtual display");
1100 return;
1101 }
1102
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001103 display->setActiveColorMode(mode);
1104 display->setCompositionDataSpace(dataSpace);
1105 display->setActiveRenderIntent(renderIntent);
1106 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001107
1108 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001109 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1110 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001111}
1112
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001113status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001114 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001115 Vector<ColorMode> modes;
1116 getDisplayColorModes(displayToken, &modes);
1117 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1118 if (mode < ColorMode::NATIVE || !exists) {
1119 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1120 decodeColorMode(mode).c_str(), mode, displayToken.get());
1121 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001122 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001123 const auto display = getDisplayDevice(displayToken);
1124 if (!display) {
1125 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1126 decodeColorMode(mode).c_str(), mode, displayToken.get());
1127 } else if (display->isVirtual()) {
1128 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1129 decodeColorMode(mode).c_str(), mode);
1130 } else {
1131 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1132 RenderIntent::COLORIMETRIC);
1133 }
1134 }));
1135
Michael Wright28f24d02016-07-12 13:30:53 -07001136 return NO_ERROR;
1137}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001138
Svetoslavd85084b2014-03-20 10:28:31 -07001139status_t SurfaceFlinger::clearAnimationFrameStats() {
1140 Mutex::Autolock _l(mStateLock);
1141 mAnimFrameTracker.clearStats();
1142 return NO_ERROR;
1143}
1144
1145status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1146 Mutex::Autolock _l(mStateLock);
1147 mAnimFrameTracker.getStats(outStats);
1148 return NO_ERROR;
1149}
1150
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001151status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1152 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001153 Mutex::Autolock _l(mStateLock);
1154
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001155 const auto display = getDisplayDeviceLocked(displayToken);
1156 if (!display) {
1157 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001158 return BAD_VALUE;
1159 }
1160
Peiyong Linfb069302018-04-25 14:34:31 -07001161 // At this point the DisplayDeivce should already be set up,
1162 // meaning the luminance information is already queried from
1163 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001164 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001165 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1166 capabilities.getDesiredMaxLuminance(),
1167 capabilities.getDesiredMaxAverageLuminance(),
1168 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001169
1170 return NO_ERROR;
1171}
1172
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001173status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001174 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001175 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001176
Chia-I Wu90f669f2017-10-05 14:24:41 -07001177 if (mInjectVSyncs == enable) {
1178 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001179 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001180
1181 if (enable) {
1182 ALOGV("VSync Injections enabled");
1183 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001184 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001185 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001186 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001187 impl::EventThread::InterceptVSyncsCallback(),
1188 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001189 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001190 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001191 } else {
1192 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001193 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001194 }
1195
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001196 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001197 }));
1198
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001199 return NO_ERROR;
1200}
1201
1202status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001203 Mutex::Autolock _l(mStateLock);
1204
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001205 if (!mInjectVSyncs) {
1206 ALOGE("VSync Injections not enabled");
1207 return BAD_VALUE;
1208 }
1209 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1210 ALOGV("Injecting VSync inside SurfaceFlinger");
1211 mVSyncInjector->onInjectSyncEvent(when);
1212 }
1213 return NO_ERROR;
1214}
1215
Lloyd Pique755e3192018-01-31 16:46:15 -08001216status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1217 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001218 IPCThreadState* ipc = IPCThreadState::self();
1219 const int pid = ipc->getCallingPid();
1220 const int uid = ipc->getCallingUid();
1221 if ((uid != AID_SHELL) &&
1222 !PermissionCache::checkPermission(sDump, pid, uid)) {
1223 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1224 return PERMISSION_DENIED;
1225 }
1226
1227 // Try to acquire a lock for 1s, fail gracefully
1228 const status_t err = mStateLock.timedLock(s2ns(1));
1229 const bool locked = (err == NO_ERROR);
1230 if (!locked) {
1231 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1232 return TIMED_OUT;
1233 }
1234
1235 outLayers->clear();
1236 mCurrentState.traverseInZOrder([&](Layer* layer) {
1237 outLayers->push_back(layer->getLayerDebugInfo());
1238 });
1239
1240 mStateLock.unlock();
1241 return NO_ERROR;
1242}
1243
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001244// ----------------------------------------------------------------------------
1245
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001246sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1247 ISurfaceComposer::VsyncSource vsyncSource) {
1248 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1249 return mSFEventThread->createEventConnection();
1250 } else {
1251 return mEventThread->createEventConnection();
1252 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001253}
1254
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001255// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001256
1257void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001258 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001259}
1260
1261void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001262 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001263}
1264
1265void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001266 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001267}
1268
1269void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001270 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001271 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001272}
1273
1274status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001275 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001276 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001277}
1278
1279status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001280 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001281 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001282 if (res == NO_ERROR) {
1283 msg->wait();
1284 }
1285 return res;
1286}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001287
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001288void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001289 do {
1290 waitForEvent();
1291 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001292}
1293
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001294void SurfaceFlinger::enableHardwareVsync() {
1295 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001296 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001297 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001298 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001299 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001300 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001301}
1302
Jesse Hall948fe0c2013-10-14 12:56:09 -07001303void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001304 Mutex::Autolock _l(mHWVsyncLock);
1305
Jesse Hall948fe0c2013-10-14 12:56:09 -07001306 if (makeAvailable) {
1307 mHWVsyncAvailable = true;
1308 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001309 // Hardware vsync is not currently available, so abort the resync
1310 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001311 return;
1312 }
1313
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001314 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1315 if (!getHwComposer().isConnected(displayId)) {
1316 return;
1317 }
1318
1319 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001320 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001321
1322 mPrimaryDispSync.reset();
1323 mPrimaryDispSync.setPeriod(period);
1324
1325 if (!mPrimaryHWVsyncEnabled) {
1326 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001327 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001328 mPrimaryHWVsyncEnabled = true;
1329 }
1330}
1331
Jesse Hall948fe0c2013-10-14 12:56:09 -07001332void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001333 Mutex::Autolock _l(mHWVsyncLock);
1334 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001335 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001336 mPrimaryDispSync.endResync();
1337 mPrimaryHWVsyncEnabled = false;
1338 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001339 if (makeUnavailable) {
1340 mHWVsyncAvailable = false;
1341 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001342}
1343
Tim Murray4a4e4a22016-04-19 16:29:23 +00001344void SurfaceFlinger::resyncWithRateLimit() {
1345 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001346
1347 // No explicit locking is needed here since EventThread holds a lock while calling this method
1348 static nsecs_t sLastResyncAttempted = 0;
1349 const nsecs_t now = systemTime();
1350 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001351 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001352 }
Dan Stoza57164302017-05-08 14:03:54 -07001353 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001354}
1355
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001356void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1357 int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001358 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001359 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001360 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001361 return;
1362 }
1363
1364 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001365 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001366 return;
1367 }
1368
Jamie Gennisd1700752013-10-14 12:22:52 -07001369 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001370
Jamie Gennisd1700752013-10-14 12:22:52 -07001371 { // Scope for the lock
1372 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001373 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001374 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001375 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001376 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001377
1378 if (needsHwVsync) {
1379 enableHardwareVsync();
1380 } else {
1381 disableHardwareVsync(false);
1382 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001383}
1384
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001385void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001386 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1387 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001388}
1389
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001390void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001391 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001392 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001393 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001394
Lloyd Piqueba04e622017-12-14 17:11:26 -08001395 // Ignore events that do not have the right sequenceId.
1396 if (sequenceId != getBE().mComposerSequenceId) {
1397 return;
1398 }
1399
Steven Thomasb02664d2017-07-26 18:48:28 -07001400 // Only lock if we're not on the main thread. This function is normally
1401 // called on a hwbinder thread, but for the primary display it's called on
1402 // the main thread with the state lock already held, so don't attempt to
1403 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001404 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001405
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001406 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001407
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001408 if (std::this_thread::get_id() == mMainThreadId) {
1409 // Process all pending hot plug events immediately if we are on the main thread.
1410 processDisplayHotplugEventsLocked();
1411 }
1412
Lloyd Piqueba04e622017-12-14 17:11:26 -08001413 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001414}
1415
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001416void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001417 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001418 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001419 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001420 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001421 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001422}
1423
Dan Stoza9e56aa02015-11-02 13:00:03 -08001424void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001425 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001426 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001427 getHwComposer().setVsyncEnabled(disp,
1428 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001429}
1430
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001431// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001432void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001433 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001434 // Clear the drawing state so that the logic inside of
1435 // handleTransactionLocked will fire. It will determine the delta between
1436 // mCurrentState and mDrawingState and re-apply all changes when we make the
1437 // transition.
1438 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001439 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001440 mDisplays.clear();
1441}
1442
Steven Thomas050b2c82017-03-06 11:45:16 -08001443void SurfaceFlinger::updateVrFlinger() {
1444 if (!mVrFlinger)
1445 return;
1446 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001447 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001448 return;
1449 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001450
David Sodman105b7dc2017-11-04 20:28:14 -07001451 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001452 ALOGE("Vr flinger is only supported for remote hardware composer"
1453 " service connections. Ignoring request to transition to vr"
1454 " flinger.");
1455 mVrFlingerRequestsDisplay = false;
1456 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001457 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001458
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001459 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001460
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001461 const auto display = getDefaultDisplayDeviceLocked();
1462 LOG_ALWAYS_FATAL_IF(!display);
1463 const int currentDisplayPowerMode = display->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001464
Steven Thomasb02664d2017-07-26 18:48:28 -07001465 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001466 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001467 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001468
Steven Thomasb02664d2017-07-26 18:48:28 -07001469 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001470 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001471 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1472 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001473 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001474
David Sodman105b7dc2017-11-04 20:28:14 -07001475 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1476 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001477
1478 if (vrFlingerRequestsDisplay) {
1479 mVrFlinger->GrantDisplayOwnership();
1480 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001481 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001482 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001483
1484 mVisibleRegionsDirty = true;
1485 invalidateHwcGeometry();
1486
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001487 // Re-enable default display.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001488 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001489
Steven Thomasb02664d2017-07-26 18:48:28 -07001490 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001491 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001492 const nsecs_t period = activeConfig->getVsyncPeriod();
1493 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001494
Steven Thomasb02664d2017-07-26 18:48:28 -07001495 // Use phase of 0 since phase is not known.
1496 // Use latency of 0, which will snap to the ideal latency.
1497 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001498
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001499 android_atomic_or(1, &mRepaintEverything);
1500 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001501}
1502
Mathias Agopian4fec8732012-06-29 14:12:52 -07001503void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001504 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001505 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001506 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001507 bool frameMissed = !mHadClientComposition &&
1508 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001509 (mPreviousPresentFence->getSignalTime() ==
1510 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001511 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001512 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001513 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001514 mTimeStats.incrementMissedFrames();
1515 if (mPropagateBackpressure) {
1516 signalLayerUpdate();
1517 break;
1518 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001519 }
Dan Stoza50182882016-07-08 12:02:20 -07001520
Steven Thomas050b2c82017-03-06 11:45:16 -08001521 // Now that we're going to make it to the handleMessageTransaction()
1522 // call below it's safe to call updateVrFlinger(), which will
1523 // potentially trigger a display handoff.
1524 updateVrFlinger();
1525
Dan Stoza6b9454d2014-11-07 16:00:59 -08001526 bool refreshNeeded = handleMessageTransaction();
1527 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001528 refreshNeeded |= mRepaintEverything;
David Sodman0756cdd2018-04-13 11:26:33 -07001529
1530 preComposition();
1531 rebuildLayerStacks();
1532 calculateWorkingSet();
1533
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001534 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
David Sodman0756cdd2018-04-13 11:26:33 -07001535
Dan Stoza58784442014-12-02 16:58:17 -08001536 // Signal a refresh if a transaction modified the window state,
1537 // a new buffer was latched, or if HWC has requested a full
1538 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001539 signalRefresh();
1540 }
1541 break;
1542 }
1543 case MessageQueue::REFRESH: {
1544 handleMessageRefresh();
1545 break;
1546 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001547 }
1548}
1549
Dan Stoza6b9454d2014-11-07 16:00:59 -08001550bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001551 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001552 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001553 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001554 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001555 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001556 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001557}
1558
Dan Stoza6b9454d2014-11-07 16:00:59 -08001559bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001560 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001561 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001562}
1563
David Sodman0756cdd2018-04-13 11:26:33 -07001564void SurfaceFlinger::calculateWorkingSet() {
1565 ATRACE_CALL();
1566 ALOGV(__FUNCTION__);
1567
1568 // build the h/w work list
1569 if (CC_UNLIKELY(mGeometryInvalid)) {
1570 mGeometryInvalid = false;
1571 for (const auto& [token, display] : mDisplays) {
1572 const auto displayId = display->getId();
1573 if (displayId >= 0) {
1574 const Vector<sp<Layer>>& currentLayers(
1575 display->getVisibleLayersSortedByZ());
1576 for (size_t i = 0; i < currentLayers.size(); i++) {
1577 const auto& layer = currentLayers[i];
1578
1579 if (!layer->hasHwcLayer(displayId)) {
1580 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1581 layer->forceClientComposition(displayId);
1582 continue;
1583 }
1584 }
1585
1586 layer->setGeometry(display, i);
1587 if (mDebugDisableHWC || mDebugRegion) {
1588 layer->forceClientComposition(displayId);
1589 }
1590 }
1591 }
1592 }
1593 }
1594
1595 // Set the per-frame data
1596 for (const auto& [token, display] : mDisplays) {
1597 const auto displayId = display->getId();
1598 if (displayId < 0) {
1599 continue;
1600 }
1601
1602 if (mDrawingState.colorMatrixChanged) {
1603 display->setColorTransform(mDrawingState.colorMatrix);
1604 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1605 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1606 "display %d: %d", displayId, result);
1607 }
1608 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1609 if (layer->isHdrY410()) {
1610 layer->forceClientComposition(displayId);
1611 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1612 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1613 !display->hasHDR10Support()) {
1614 layer->forceClientComposition(displayId);
1615 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1616 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1617 !display->hasHLGSupport()) {
1618 layer->forceClientComposition(displayId);
1619 }
1620
1621 if (layer->getForceClientComposition(displayId)) {
1622 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1623 layer->setCompositionType(displayId, HWC2::Composition::Client);
1624 continue;
1625 }
1626
1627 layer->setPerFrameData(display);
1628 }
1629
1630 if (hasWideColorDisplay) {
1631 ColorMode colorMode;
1632 Dataspace dataSpace;
1633 RenderIntent renderIntent;
1634 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1635 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1636 }
1637 }
1638
1639 mDrawingState.colorMatrixChanged = false;
1640 getBE().mCompositionInfo.clear();
1641
1642 for (const auto& [token, display] : mDisplays) {
1643 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1644 auto displayId = display->getId();
1645 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1646 if (!layer->setHwcLayer(displayId)) {
1647 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1648 }
1649 getBE().mCompositionInfo.push_back(layer->getBE().compositionInfo);
1650 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1651 }
1652 }
1653}
1654
Mathias Agopian4fec8732012-06-29 14:12:52 -07001655void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001656 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001657
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001658 mRefreshPending = false;
1659
David Sodman0756cdd2018-04-13 11:26:33 -07001660 beginFrame();
1661 for (auto compositionInfo : getBE().mCompositionInfo) {
1662 setUpHWComposer(compositionInfo);
1663 }
1664 prepareFrame();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001665 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001666 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001667 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001668 doComposition();
David Sodman0756cdd2018-04-13 11:26:33 -07001669 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001670
Dan Stozabfbffeb2016-07-21 14:49:33 -07001671 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001672 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001673 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001674 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001675 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001676 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001677
Dan Stoza9e56aa02015-11-02 13:00:03 -08001678 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001679}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001680
Mathias Agopiancd60f992012-08-16 16:28:27 -07001681void SurfaceFlinger::doDebugFlashRegions()
1682{
1683 // is debugging enabled
1684 if (CC_LIKELY(!mDebugRegion))
1685 return;
1686
1687 const bool repaintEverything = mRepaintEverything;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001688 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001689 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001690 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001691 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001692 if (!dirtyRegion.isEmpty()) {
1693 // redraw the whole screen
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001694 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001695
1696 // and draw the dirty region
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001697 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001698 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001699 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1700
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001701 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001702 }
1703 }
1704 }
1705
1706 postFramebuffer();
1707
1708 if (mDebugRegion > 1) {
1709 usleep(mDebugRegion * 1000);
1710 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001711
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001712 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001713 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001714 continue;
1715 }
1716
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001717 status_t result = display->prepareFrame(*getBE().mHwc);
1718 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001719 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001720 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001721}
1722
Adrian Roos1e1a1282017-11-01 19:05:31 +01001723void SurfaceFlinger::doTracing(const char* where) {
1724 ATRACE_CALL();
1725 ATRACE_NAME(where);
1726 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001727 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001728 }
1729}
1730
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001731void SurfaceFlinger::logLayerStats() {
1732 ATRACE_CALL();
1733 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001734 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001735 if (display->isPrimary()) {
1736 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001737 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001738 }
1739 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001740
1741 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001742 }
1743}
1744
David Sodman0756cdd2018-04-13 11:26:33 -07001745void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001746{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001747 ATRACE_CALL();
1748 ALOGV("preComposition");
1749
Mathias Agopiancd60f992012-08-16 16:28:27 -07001750 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001751 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman0756cdd2018-04-13 11:26:33 -07001752 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001753 needExtraInvalidate = true;
1754 }
Robert Carr2047fae2016-11-28 14:09:09 -08001755 });
1756
Mathias Agopiancd60f992012-08-16 16:28:27 -07001757 if (needExtraInvalidate) {
1758 signalLayerUpdate();
1759 }
1760}
1761
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001762void SurfaceFlinger::updateCompositorTiming(
1763 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1764 std::shared_ptr<FenceTime>& presentFenceTime) {
1765 // Update queue of past composite+present times and determine the
1766 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001767 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001768 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001769 while (!getBE().mCompositePresentTimes.empty()) {
1770 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001771 // Cached values should have been updated before calling this method,
1772 // which helps avoid duplicate syscalls.
1773 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1774 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1775 break;
1776 }
1777 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001778 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001779 }
1780
1781 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001782 while (getBE().mCompositePresentTimes.size() > 16) {
1783 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001784 }
1785
Brian Andersond0010582017-03-07 13:20:31 -08001786 setCompositorTimingSnapped(
1787 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1788}
1789
1790void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1791 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001792 // Integer division and modulo round toward 0 not -inf, so we need to
1793 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001794 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001795 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1796 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1797
Brian Andersond0010582017-03-07 13:20:31 -08001798 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1799 if (idealLatency <= 0) {
1800 idealLatency = vsyncInterval;
1801 }
1802
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001803 // Snap the latency to a value that removes scheduling jitter from the
1804 // composition and present times, which often have >1ms of jitter.
1805 // Reducing jitter is important if an app attempts to extrapolate
1806 // something (such as user input) to an accurate diasplay time.
1807 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1808 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001809 nsecs_t bias = vsyncInterval / 2;
1810 int64_t extraVsyncs =
1811 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1812 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1813 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001814
David Sodman99974d22017-11-28 12:04:33 -08001815 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1816 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1817 getBE().mCompositorTiming.interval = vsyncInterval;
1818 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001819}
1820
David Sodman0756cdd2018-04-13 11:26:33 -07001821void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001822{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001823 ATRACE_CALL();
1824 ALOGV("postComposition");
1825
Brian Anderson3546a3f2016-07-14 11:51:14 -07001826 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001827 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001828 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001829 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001830 }
1831
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001832 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001833 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001834
David Sodman73beded2017-11-15 11:56:06 -08001835 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001836 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001837 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001838 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001839 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001840 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001841 } else {
1842 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1843 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001844
David Sodman73beded2017-11-15 11:56:06 -08001845 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001846 mPreviousPresentFence =
1847 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1848 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001849 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001850
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001851 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1852 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1853
David Sodman0756cdd2018-04-13 11:26:33 -07001854 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001855 // when we started doing work for this frame, but that should be okay
1856 // since updateCompositorTiming has snapping logic.
1857 updateCompositorTiming(
David Sodman0756cdd2018-04-13 11:26:33 -07001858 vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001859 CompositorTiming compositorTiming;
1860 {
David Sodman99974d22017-11-28 12:04:33 -08001861 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1862 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001863 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001864
Robert Carr2047fae2016-11-28 14:09:09 -08001865 mDrawingState.traverseInZOrder([&](Layer* layer) {
1866 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001867 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001868 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001869 recordBufferingStats(layer->getName().string(),
1870 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001871 }
Robert Carr2047fae2016-11-28 14:09:09 -08001872 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001873
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001874 if (presentFenceTime->isValid()) {
1875 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001876 enableHardwareVsync();
1877 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001878 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001879 }
1880 }
1881
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001882 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001883 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001884 enableHardwareVsync();
1885 }
1886 }
1887
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001888 if (mAnimCompositionPending) {
1889 mAnimCompositionPending = false;
1890
Brian Anderson4e606e32017-03-16 15:34:57 -07001891 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001892 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001893 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001894 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001895 // The HWC doesn't support present fences, so use the refresh
1896 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001897 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001898 mAnimFrameTracker.setActualPresentTime(presentTime);
1899 }
1900 mAnimFrameTracker.advanceFrame();
1901 }
Dan Stozab90cf072015-03-05 11:05:59 -08001902
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001903 mTimeStats.incrementTotalFrames();
1904 if (mHadClientComposition) {
1905 mTimeStats.incrementClientCompositionFrames();
1906 }
1907
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001908 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001909 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001910 return;
1911 }
1912
1913 nsecs_t currentTime = systemTime();
1914 if (mHasPoweredOff) {
1915 mHasPoweredOff = false;
1916 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001917 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001918 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001919 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1920 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001921 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001922 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001923 }
David Sodman4a36e932017-11-07 14:29:47 -08001924 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001925 }
David Sodman4a36e932017-11-07 14:29:47 -08001926 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001927
1928 {
1929 std::lock_guard lock(mTexturePoolMutex);
1930 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1931 if (refillCount > 0) {
1932 const size_t offset = mTexturePool.size();
1933 mTexturePool.resize(mTexturePoolSize);
1934 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1935 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1936 }
1937 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001938}
1939
1940void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001941 ATRACE_CALL();
1942 ALOGV("rebuildLayerStacks");
1943
Mathias Agopiancd60f992012-08-16 16:28:27 -07001944 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001945 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001946 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001947 mVisibleRegionsDirty = false;
1948 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001949
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001950 for (const auto& pair : mDisplays) {
1951 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001952 Region opaqueRegion;
1953 Region dirtyRegion;
1954 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001955 Vector<sp<Layer>> layersNeedingFences;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001956 const Transform& tr = display->getTransform();
1957 const Rect bounds = display->getBounds();
1958 if (display->isPoweredOn()) {
1959 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001960
Jeff Sharkey76488112017-02-27 14:15:18 -07001961 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001962 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001963 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001964 Region drawRegion(tr.transform(
1965 layer->visibleNonTransparentRegion));
1966 drawRegion.andSelf(bounds);
1967 if (!drawRegion.isEmpty()) {
1968 layersSortedByZ.add(layer);
1969 } else {
David Sodman0756cdd2018-04-13 11:26:33 -07001970 if (layer->hasHwcLayer(display->getId())) {
1971 // Clear out the HWC layer if this layer was
1972 // previously visible, but no longer is
1973 hwcLayerDestroyed = layer->destroyHwcLayer(
1974 display->getId());
1975 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001976 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001977 } else {
David Sodman0756cdd2018-04-13 11:26:33 -07001978 if (layer->hasHwcLayer(display->getId())) {
1979 // WM changes display->layerStack upon sleep/awake.
1980 // Here we make sure we delete the HWC layers even if
1981 // WM changed their layer stack.
1982 hwcLayerDestroyed = layer->destroyHwcLayer(
1983 display->getId());
1984 }
Chia-I Wu83806892017-11-16 10:50:20 -08001985 }
1986
1987 // If a layer is not going to get a release fence because
1988 // it is invisible, but it is also going to release its
1989 // old buffer, add it to the list of layers needing
1990 // fences.
1991 if (hwcLayerDestroyed) {
1992 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1993 mLayersWithQueuedFrames.cend(), layer);
1994 if (found != mLayersWithQueuedFrames.cend()) {
1995 layersNeedingFences.add(layer);
1996 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001997 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001998 });
1999 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002000 display->setVisibleLayersSortedByZ(layersSortedByZ);
2001 display->setLayersNeedingFences(layersNeedingFences);
2002 display->undefinedRegion.set(bounds);
2003 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2004 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002005 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002006 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002007}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002008
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002009// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002010// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002011// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002012// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002013// The returned HDR data space is one of
2014// - Dataspace::UNKNOWN
2015// - Dataspace::BT2020_HLG
2016// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002017Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2018 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07002019 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002020 *outHdrDataSpace = Dataspace::UNKNOWN;
2021
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002022 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002023 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002024 case Dataspace::V0_SCRGB:
2025 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002026 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002027 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002028 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002029 case Dataspace::BT2020_PQ:
2030 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002031 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002032 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002033 case Dataspace::BT2020_HLG:
2034 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002035 // When there's mixed PQ content and HLG content, we set the HDR
2036 // data space to be BT2020_PQ and convert HLG to PQ.
2037 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2038 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002039 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002040 break;
2041 default:
2042 break;
2043 }
Romain Guy54f154a2017-10-24 21:40:32 +01002044 }
2045
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002046 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002047}
2048
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002049// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002050void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2051 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002052 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2053 *outMode = ColorMode::NATIVE;
2054 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002055 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002056 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002057 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002058
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002059 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002060 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002061
Peiyong Lindfde5112018-06-05 10:58:41 -07002062 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002063 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002064 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002065 if (isHdr) {
2066 bestDataSpace = hdrDataSpace;
2067 }
2068
Chia-I Wu0d711262018-05-21 15:19:35 -07002069 RenderIntent intent;
2070 switch (mDisplayColorSetting) {
2071 case DisplayColorSetting::MANAGED:
2072 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002073 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002074 break;
2075 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002076 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002077 break;
2078 default: // vendor display color setting
2079 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2080 break;
2081 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002082
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002083 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002084}
2085
David Sodman0756cdd2018-04-13 11:26:33 -07002086void SurfaceFlinger::configureSidebandComposition(const CompositionInfo& compositionInfo) const
2087{
2088 HWC2::Error error;
2089 LOG_ALWAYS_FATAL_IF(compositionInfo.hwc.sidebandStream == nullptr,
2090 "CompositionType is sideband, but sideband stream is nullptr");
2091 error = (compositionInfo.hwc.hwcLayer)
2092 ->setSidebandStream(compositionInfo.hwc.sidebandStream->handle());
2093 if (error != HWC2::Error::None) {
2094 ALOGE("[SF] Failed to set sideband stream %p: %s (%d)",
2095 compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
2096 static_cast<int32_t>(error));
2097 }
2098}
2099
2100void SurfaceFlinger::configureHwcCommonData(const CompositionInfo& compositionInfo) const
2101{
2102 HWC2::Error error;
2103
2104 if (!compositionInfo.hwc.skipGeometry) {
2105 error = (compositionInfo.hwc.hwcLayer)->setBlendMode(compositionInfo.hwc.blendMode);
2106 ALOGE_IF(error != HWC2::Error::None,
2107 "[SF] Failed to set blend mode %s:"
2108 " %s (%d)",
2109 to_string(compositionInfo.hwc.blendMode).c_str(), to_string(error).c_str(),
2110 static_cast<int32_t>(error));
2111
2112 error = (compositionInfo.hwc.hwcLayer)->setDisplayFrame(compositionInfo.hwc.displayFrame);
2113 ALOGE_IF(error != HWC2::Error::None,
2114 "[SF] Failed to set the display frame [%d, %d, %d, %d] %s (%d)",
2115 compositionInfo.hwc.displayFrame.left,
2116 compositionInfo.hwc.displayFrame.right,
2117 compositionInfo.hwc.displayFrame.top,
2118 compositionInfo.hwc.displayFrame.bottom,
2119 to_string(error).c_str(), static_cast<int32_t>(error));
2120
2121 error = (compositionInfo.hwc.hwcLayer)->setSourceCrop(compositionInfo.hwc.sourceCrop);
2122 ALOGE_IF(error != HWC2::Error::None,
2123 "[SF] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: %s (%d)",
2124 compositionInfo.hwc.sourceCrop.left,
2125 compositionInfo.hwc.sourceCrop.right,
2126 compositionInfo.hwc.sourceCrop.top,
2127 compositionInfo.hwc.sourceCrop.bottom,
2128 to_string(error).c_str(), static_cast<int32_t>(error));
2129
2130 error = (compositionInfo.hwc.hwcLayer)->setPlaneAlpha(compositionInfo.hwc.alpha);
2131 ALOGE_IF(error != HWC2::Error::None,
2132 "[SF] Failed to set plane alpha %.3f: "
2133 "%s (%d)",
2134 compositionInfo.hwc.alpha,
2135 to_string(error).c_str(), static_cast<int32_t>(error));
2136
2137
2138 error = (compositionInfo.hwc.hwcLayer)->setZOrder(compositionInfo.hwc.z);
2139 ALOGE_IF(error != HWC2::Error::None,
2140 "[SF] Failed to set Z %u: %s (%d)",
2141 compositionInfo.hwc.z,
2142 to_string(error).c_str(), static_cast<int32_t>(error));
2143
2144 error = (compositionInfo.hwc.hwcLayer)
2145 ->setInfo(compositionInfo.hwc.type, compositionInfo.hwc.appId);
2146 ALOGE_IF(error != HWC2::Error::None,
2147 "[SF] Failed to set info (%d)",
2148 static_cast<int32_t>(error));
2149
2150 error = (compositionInfo.hwc.hwcLayer)->setTransform(compositionInfo.hwc.transform);
2151 ALOGE_IF(error != HWC2::Error::None,
2152 "[SF] Failed to set transform %s: "
2153 "%s (%d)",
2154 to_string(compositionInfo.hwc.transform).c_str(), to_string(error).c_str(),
2155 static_cast<int32_t>(error));
2156 }
2157
2158 error = (compositionInfo.hwc.hwcLayer)->setCompositionType(compositionInfo.compositionType);
2159 ALOGE_IF(error != HWC2::Error::None,
2160 "[SF] Failed to set composition type: %s (%d)",
2161 to_string(error).c_str(), static_cast<int32_t>(error));
2162
2163 error = (compositionInfo.hwc.hwcLayer)->setDataspace(compositionInfo.hwc.dataspace);
2164 ALOGE_IF(error != HWC2::Error::None,
2165 "[SF] Failed to set dataspace: %s (%d)",
2166 to_string(error).c_str(), static_cast<int32_t>(error));
2167
2168 error = (compositionInfo.hwc.hwcLayer)->setPerFrameMetadata(
2169 compositionInfo.hwc.supportedPerFrameMetadata, compositionInfo.hwc.hdrMetadata);
2170 ALOGE_IF(error != HWC2::Error::None && error != HWC2::Error::Unsupported,
2171 "[SF] Failed to set hdrMetadata: %s (%d)",
2172 to_string(error).c_str(), static_cast<int32_t>(error));
2173
2174 error = (compositionInfo.hwc.hwcLayer)->setColor(compositionInfo.hwc.color);
2175 ALOGE_IF(error != HWC2::Error::None,
2176 "[SF] Failed to set color: %s (%d)",
2177 to_string(error).c_str(), static_cast<int32_t>(error));
2178
2179 error = (compositionInfo.hwc.hwcLayer)->setVisibleRegion(compositionInfo.hwc.visibleRegion);
2180 ALOGE_IF(error != HWC2::Error::None,
2181 "[SF] Failed to set visible region: %s (%d)",
2182 to_string(error).c_str(), static_cast<int32_t>(error));
2183}
2184
2185void SurfaceFlinger::configureDeviceComposition(const CompositionInfo& compositionInfo) const
2186{
2187 HWC2::Error error;
2188
2189 error = (compositionInfo.hwc.hwcLayer)->setSurfaceDamage(compositionInfo.hwc.surfaceDamage);
2190 ALOGE_IF(error != HWC2::Error::None,
2191 "[SF] Failed to set surface damage: %s (%d)",
2192 to_string(error).c_str(), static_cast<int32_t>(error));
2193
2194 error = (compositionInfo.hwc.hwcLayer)->setBuffer(compositionInfo.mBufferSlot,
2195 compositionInfo.mBuffer, compositionInfo.hwc.fence);
2196 ALOGE_IF(error != HWC2::Error::None,
2197 "[SF] Failed to set buffer: %s (%d)",
2198 to_string(error).c_str(), static_cast<int32_t>(error));
2199}
2200
2201void SurfaceFlinger::beginFrame()
2202{
2203 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002204
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002205 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002206 bool dirty = !display->getDirtyRegion(mRepaintEverything).isEmpty();
2207 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2208 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
Jesse Hallb7a05492014-08-14 15:45:06 -07002209
2210 // If nothing has changed (!dirty), don't recompose.
2211 // If something changed, but we don't currently have any visible layers,
2212 // and didn't when we last did a composition, then skip it this time.
2213 // The second rule does two things:
2214 // - When all layers are removed from a display, we'll emit one black
2215 // frame, then nothing more until we get new layers.
2216 // - When a display is created with a private layer stack, we won't
2217 // emit any black frames until a layer is added to the layer stack.
2218 bool mustRecompose = dirty && !(empty && wasEmpty);
2219
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002220 ALOGV_IF(display->isVirtual(), "Display %d: %s composition (%sdirty %sempty %swasEmpty)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002221 display->getId(), mustRecompose ? "doing" : "skipping", dirty ? "+" : "-",
2222 empty ? "+" : "-", wasEmpty ? "+" : "-");
Jesse Hallb7a05492014-08-14 15:45:06 -07002223
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002224 display->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07002225
2226 if (mustRecompose) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002227 display->lastCompositionHadVisibleLayers = !empty;
Jesse Hallb7a05492014-08-14 15:45:06 -07002228 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07002229 }
David Sodman0756cdd2018-04-13 11:26:33 -07002230}
Jesse Hall028dc8f2013-08-20 16:35:32 -07002231
David Sodman0756cdd2018-04-13 11:26:33 -07002232void SurfaceFlinger::prepareFrame()
2233{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002234 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002235 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002236 continue;
2237 }
2238
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002239 status_t result = display->prepareFrame(*getBE().mHwc);
2240 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002241 display->getId(), result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002242 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002243}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002244
David Sodman0756cdd2018-04-13 11:26:33 -07002245void SurfaceFlinger::setUpHWComposer(const CompositionInfo& compositionInfo) {
2246 ATRACE_CALL();
2247 ALOGV("setUpHWComposer");
2248
2249 switch (compositionInfo.compositionType)
2250 {
2251 case HWC2::Composition::Invalid:
2252 case HWC2::Composition::Client:
2253 break;
2254
2255 case HWC2::Composition::Sideband:
2256 configureSidebandComposition(compositionInfo);
2257 break;
2258
2259 case HWC2::Composition::SolidColor:
2260 configureHwcCommonData(compositionInfo);
2261 break;
2262
2263 case HWC2::Composition::Device:
2264 case HWC2::Composition::Cursor:
2265 configureHwcCommonData(compositionInfo);
2266 configureDeviceComposition(compositionInfo);
2267 break;
2268 }
2269}
2270
Mathias Agopiancd60f992012-08-16 16:28:27 -07002271void SurfaceFlinger::doComposition() {
2272 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002273 ALOGV("doComposition");
2274
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002275 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002276 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002277 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002278 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002279 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002280
2281 // repaint the framebuffer (if needed)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002282 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002283
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002284 display->dirtyRegion.clear();
2285 display->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002286 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002287 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002288 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002289}
2290
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002291void SurfaceFlinger::postFramebuffer()
2292{
Mathias Agopian841cde52012-03-01 15:44:37 -08002293 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002294 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002295
Mathias Agopiana44b0412011-10-16 18:46:35 -07002296 const nsecs_t now = systemTime();
2297 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002298
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002299 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002300 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002301 continue;
2302 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07002303 const auto displayId = display->getId();
2304 if (displayId >= 0) {
2305 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002306 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002307 display->onSwapBuffersCompleted();
2308 display->makeCurrent();
2309 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002310 // The layer buffer from the previous frame (if any) is released
2311 // by HWC only when the release fence from this frame (if any) is
2312 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002313 auto hwcLayer = layer->getHwcLayer(displayId);
2314 sp<Fence> releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
Chia-I Wu7b549592017-11-15 09:14:57 -08002315
2316 // If the layer was client composited in the previous frame, we
2317 // need to merge with the previous client target acquire fence.
2318 // Since we do not track that, always merge with the current
2319 // client target acquire fence when it is available, even though
2320 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002321 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002322 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002323 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002324 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002325
David Sodmanb8af7922017-12-21 15:17:55 -08002326 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002327 }
Chia-I Wu83806892017-11-16 10:50:20 -08002328
2329 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002330 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002331 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002332 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002333 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002334 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002335 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002336 }
2337 }
2338
Dominik Laskowski7e045462018-05-30 13:02:02 -07002339 if (displayId >= 0) {
2340 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002341 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002342 }
2343
Mathias Agopiana44b0412011-10-16 18:46:35 -07002344 mLastSwapBufferTime = systemTime() - now;
2345 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002346
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002347 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002348 const auto display = getDefaultDisplayDeviceLocked();
2349 if (display && getHwComposer().isConnected(display->getId())) {
2350 const uint32_t flipCount = display->getPageFlipCount();
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002351 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2352 logFrameStats();
2353 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002354 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002355}
2356
Mathias Agopian87baae12012-07-31 12:38:26 -07002357void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002358{
Mathias Agopian841cde52012-03-01 15:44:37 -08002359 ATRACE_CALL();
2360
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002361 // here we keep a copy of the drawing state (that is the state that's
2362 // going to be overwritten by handleTransactionLocked()) outside of
2363 // mStateLock so that the side-effects of the State assignment
2364 // don't happen with mStateLock held (which can cause deadlocks).
2365 State drawingState(mDrawingState);
2366
Mathias Agopianca4d3602011-05-19 15:38:14 -07002367 Mutex::Autolock _l(mStateLock);
2368 const nsecs_t now = systemTime();
2369 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002370
Mathias Agopianca4d3602011-05-19 15:38:14 -07002371 // Here we're guaranteed that some transaction flags are set
2372 // so we can call handleTransactionLocked() unconditionally.
2373 // We call getTransactionFlags(), which will also clear the flags,
2374 // with mStateLock held to guarantee that mCurrentState won't change
2375 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002376
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002377 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002378 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002379 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002380
Mathias Agopianca4d3602011-05-19 15:38:14 -07002381 mLastTransactionTime = systemTime() - now;
2382 mDebugInTransaction = 0;
2383 invalidateHwcGeometry();
2384 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002385}
2386
Dominik Laskowski7e045462018-05-30 13:02:02 -07002387DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002388 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002389 // Figure out whether the event is for the primary display or an
2390 // external display by matching the Hwc display id against one for a
2391 // connected display. If we did not find a match, we then check what
2392 // displays are not already connected to determine the type. If we don't
2393 // have a connected primary display, we assume the new display is meant to
2394 // be the primary display, and then if we don't have an external display,
2395 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002396 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2397 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002398 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002399 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002400 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002401 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002402 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002403 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002404 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002405 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002406 return DisplayDevice::DISPLAY_EXTERNAL;
2407 }
2408
2409 return DisplayDevice::DISPLAY_ID_INVALID;
2410}
2411
Lloyd Piqueba04e622017-12-14 17:11:26 -08002412void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2413 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002414 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002415 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002416 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002417 continue;
2418 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002419
2420 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2421 ALOGE("External displays are not supported by the vr hardware composer.");
2422 continue;
2423 }
2424
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002425 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002426 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002427 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002428 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002429 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002430
2431 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002432 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002433 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002434 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002435 DisplayDeviceState info;
2436 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002437 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2438 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002439 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002440 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002441 mInterceptor->saveDisplayCreation(info);
2442 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002443 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002444 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002445
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002446 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002447 if (idx >= 0) {
2448 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002449 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002450 mCurrentState.displays.removeItemsAt(idx);
2451 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002452 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002453 }
2454
2455 processDisplayChangesLocked();
2456 }
2457
2458 mPendingHotplugEvents.clear();
2459}
2460
Lloyd Pique99d3da52018-01-22 17:48:03 -08002461sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002462 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002463 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002464 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002465 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002466
Lloyd Pique99d3da52018-01-22 17:48:03 -08002467 if (hasWideColorDisplay) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002468 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002469 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002470 if (isWideColorMode(colorMode)) {
2471 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002472 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002473
Dominik Laskowski7e045462018-05-30 13:02:02 -07002474 std::vector<RenderIntent> renderIntents =
2475 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002476 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002477 }
2478 }
2479
Peiyong Lin62665892018-04-16 11:07:44 -07002480 HdrCapabilities hdrCapabilities;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002481 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002482
2483 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2484 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2485
2486 /*
2487 * Create our display's surface
2488 */
2489 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2490 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002491 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002492 renderSurface->setNativeWindow(nativeWindow.get());
2493 const int displayWidth = renderSurface->queryWidth();
2494 const int displayHeight = renderSurface->queryHeight();
2495
2496 // Make sure that composition can never be stalled by a virtual display
2497 // consumer that isn't processing buffers fast enough. We have to do this
2498 // in two places:
2499 // * Here, in case the display is composed entirely by HWC.
2500 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2501 // window's swap interval in eglMakeCurrent, so they'll override the
2502 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002503 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002504 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2505 }
2506
2507 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002508 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002509
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002510 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002511 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2512 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2513 displayHeight, hasWideColorGamut, hdrCapabilities,
2514 getHwComposer().getSupportedPerFrameMetadata(displayId),
2515 hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002516
2517 if (maxFrameBufferAcquiredBuffers >= 3) {
2518 nativeWindowSurface->preallocateBuffers();
2519 }
2520
2521 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002522 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2523 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002524 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002525 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002526 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002527 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002528 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002529 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002530 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002531 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002532 display->setLayerStack(state.layerStack);
2533 display->setProjection(state.orientation, state.viewport, state.frame);
2534 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002535
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002536 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002537}
2538
Lloyd Pique347200f2017-12-14 17:00:15 -08002539void SurfaceFlinger::processDisplayChangesLocked() {
2540 // here we take advantage of Vector's copy-on-write semantics to
2541 // improve performance by skipping the transaction entirely when
2542 // know that the lists are identical
2543 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2544 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2545 if (!curr.isIdenticalTo(draw)) {
2546 mVisibleRegionsDirty = true;
2547 const size_t cc = curr.size();
2548 size_t dc = draw.size();
2549
2550 // find the displays that were removed
2551 // (ie: in drawing state but not in current state)
2552 // also handle displays that changed
2553 // (ie: displays that are in both lists)
2554 for (size_t i = 0; i < dc;) {
2555 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2556 if (j < 0) {
2557 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002558 // Call makeCurrent() on the primary display so we can
2559 // be sure that nothing associated with this display
2560 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002561 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2562 defaultDisplay->makeCurrent();
2563 }
2564 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2565 display->disconnect(getHwComposer());
2566 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002567 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2568 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2569 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2570 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2571 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002572 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002573 } else {
2574 // this display is in both lists. see if something changed.
2575 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002576 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002577 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2578 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2579 if (state_binder != draw_binder) {
2580 // changing the surface is like destroying and
2581 // recreating the DisplayDevice, so we just remove it
2582 // from the drawing state, so that it get re-added
2583 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002584 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2585 display->disconnect(getHwComposer());
2586 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002587 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002588 mDrawingState.displays.removeItemsAt(i);
2589 dc--;
2590 // at this point we must loop to the next item
2591 continue;
2592 }
2593
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002594 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002595 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002596 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002597 }
2598 if ((state.orientation != draw[i].orientation) ||
2599 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002600 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002601 }
2602 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002603 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002604 }
2605 }
2606 }
2607 ++i;
2608 }
2609
2610 // find displays that were added
2611 // (ie: in current state but not in drawing state)
2612 for (size_t i = 0; i < cc; i++) {
2613 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2614 const DisplayDeviceState& state(curr[i]);
2615
2616 sp<DisplaySurface> dispSurface;
2617 sp<IGraphicBufferProducer> producer;
2618 sp<IGraphicBufferProducer> bqProducer;
2619 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002620 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002621
Dominik Laskowski7e045462018-05-30 13:02:02 -07002622 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002623 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002624 // Virtual displays without a surface are dormant:
2625 // they have external state (layer stack, projection,
2626 // etc.) but no internal state (i.e. a DisplayDevice).
2627 if (state.surface != nullptr) {
2628 // Allow VR composer to use virtual displays.
2629 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2630 int width = 0;
2631 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2632 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2633 int height = 0;
2634 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2635 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2636 int intFormat = 0;
2637 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2638 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002639 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002640
Dominik Laskowski7e045462018-05-30 13:02:02 -07002641 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2642 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002643 }
2644
2645 // TODO: Plumb requested format back up to consumer
2646
2647 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002648 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002649 bqProducer, bqConsumer,
2650 state.displayName);
2651
2652 dispSurface = vds;
2653 producer = vds;
2654 }
2655 } else {
2656 ALOGE_IF(state.surface != nullptr,
2657 "adding a supported display, but rendering "
2658 "surface is provided (%p), ignoring it",
2659 state.surface.get());
2660
Dominik Laskowski7e045462018-05-30 13:02:02 -07002661 displayId = state.type;
2662 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002663 producer = bqProducer;
2664 }
2665
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002666 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002667 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002668 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002669 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002670 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002671 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002672 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2673 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2674 true);
2675 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2676 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2677 true);
2678 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002679 }
2680 }
2681 }
2682 }
2683 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002684
2685 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002686}
2687
Mathias Agopian87baae12012-07-31 12:38:26 -07002688void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002689{
Dan Stoza7dde5992015-05-22 09:51:44 -07002690 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002691 mCurrentState.traverseInZOrder([](Layer* layer) {
2692 layer->notifyAvailableFrames();
2693 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002694
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002695 /*
2696 * Traversal of the children
2697 * (perform the transaction for each of them if needed)
2698 */
2699
Mathias Agopian3559b072012-08-15 13:46:03 -07002700 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002701 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002702 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002703 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002704
2705 const uint32_t flags = layer->doTransaction(0);
2706 if (flags & Layer::eVisibleRegion)
2707 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002708 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002709 }
2710
2711 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002712 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002713 */
2714
Mathias Agopiane57f2922012-08-09 16:29:12 -07002715 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002716 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002717 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002718 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002719
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002720 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002721 // The transform hint might have changed for some layers
2722 // (either because a display has changed, or because a layer
2723 // as changed).
2724 //
2725 // Walk through all the layers in currentLayers,
2726 // and update their transform hint.
2727 //
2728 // If a layer is visible only on a single display, then that
2729 // display is used to calculate the hint, otherwise we use the
2730 // default display.
2731 //
2732 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2733 // the hint is set before we acquire a buffer from the surface texture.
2734 //
2735 // NOTE: layer transactions have taken place already, so we use their
2736 // drawing state. However, SurfaceFlinger's own transaction has not
2737 // happened yet, so we must use the current state layer list
2738 // (soon to become the drawing state list).
2739 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002740 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002741 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002742 bool first = true;
2743 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002744 // NOTE: we rely on the fact that layers are sorted by
2745 // layerStack first (so we don't have to traverse the list
2746 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002747 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002748 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002749 currentlayerStack = layerStack;
2750 // figure out if this layerstack is mirrored
2751 // (more than one display) if so, pick the default display,
2752 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002753 hintDisplay = nullptr;
2754 for (const auto& [token, display] : mDisplays) {
2755 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2756 if (hintDisplay) {
2757 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002758 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002759 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002760 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002761 }
2762 }
2763 }
2764 }
Chet Haase91d25932013-04-11 15:24:55 -07002765
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002766 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002767 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2768 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002769
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002770 // could be null when this layer is using a layerStack
2771 // that is not visible on any display. Also can occur at
2772 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002773 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002774 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002775
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002776 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002777 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002778 if (hintDisplay) {
2779 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002780 }
Robert Carr2047fae2016-11-28 14:09:09 -08002781
2782 first = false;
2783 });
Mathias Agopian84300952012-11-21 16:02:13 -08002784 }
2785
2786
Mathias Agopian3559b072012-08-15 13:46:03 -07002787 /*
2788 * Perform our own transaction if needed
2789 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002790
2791 if (mLayersAdded) {
2792 mLayersAdded = false;
2793 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002794 mVisibleRegionsDirty = true;
2795 }
2796
2797 // some layers might have been removed, so
2798 // we need to update the regions they're exposing.
2799 if (mLayersRemoved) {
2800 mLayersRemoved = false;
2801 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002802 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002803 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002804 // this layer is not visible anymore
2805 // TODO: we could traverse the tree from front to back and
2806 // compute the actual visible region
2807 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002808 Region visibleReg;
2809 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002810 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002811 }
Robert Carr2047fae2016-11-28 14:09:09 -08002812 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002813 }
2814
2815 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002816
2817 updateCursorAsync();
2818}
2819
2820void SurfaceFlinger::updateCursorAsync()
2821{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002822 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002823 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002824 continue;
2825 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002826
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002827 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2828 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002829 }
2830 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002831}
2832
2833void SurfaceFlinger::commitTransaction()
2834{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002835 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002836 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002837 for (const auto& l : mLayersPendingRemoval) {
2838 recordBufferingStats(l->getName().string(),
2839 l->getOccupancyHistory(true));
2840 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002841 }
2842 mLayersPendingRemoval.clear();
2843 }
2844
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002845 // If this transaction is part of a window animation then the next frame
2846 // we composite should be considered an animation as well.
2847 mAnimCompositionPending = mAnimTransactionPending;
2848
Mathias Agopian4fec8732012-06-29 14:12:52 -07002849 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002850 // clear the "changed" flags in current state
2851 mCurrentState.colorMatrixChanged = false;
2852
Robert Carr1f0a16a2016-10-24 16:27:39 -07002853 mDrawingState.traverseInZOrder([](Layer* layer) {
2854 layer->commitChildList();
2855 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002856 mTransactionPending = false;
2857 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002858 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002859}
2860
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002861void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2862 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002863 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002864 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002865
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002866 Region aboveOpaqueLayers;
2867 Region aboveCoveredLayers;
2868 Region dirty;
2869
Mathias Agopian87baae12012-07-31 12:38:26 -07002870 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002871
Robert Carr2047fae2016-11-28 14:09:09 -08002872 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002873 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002874 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002875
Jesse Hall01e29052013-02-19 16:13:35 -08002876 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002877 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002878 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002879 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002880
Mathias Agopianab028732010-03-16 16:41:46 -07002881 /*
2882 * opaqueRegion: area of a surface that is fully opaque.
2883 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002884 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002885
2886 /*
2887 * visibleRegion: area of a surface that is visible on screen
2888 * and not fully transparent. This is essentially the layer's
2889 * footprint minus the opaque regions above it.
2890 * Areas covered by a translucent surface are considered visible.
2891 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002892 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002893
2894 /*
2895 * coveredRegion: area of a surface that is covered by all
2896 * visible regions above it (which includes the translucent areas).
2897 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002898 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002899
Jesse Halla8026d22012-09-25 13:25:04 -07002900 /*
2901 * transparentRegion: area of a surface that is hinted to be completely
2902 * transparent. This is only used to tell when the layer has no visible
2903 * non-transparent regions and can be removed from the layer list. It
2904 * does not affect the visibleRegion of this layer or any layers
2905 * beneath it. The hint may not be correct if apps don't respect the
2906 * SurfaceView restrictions (which, sadly, some don't).
2907 */
2908 Region transparentRegion;
2909
Mathias Agopianab028732010-03-16 16:41:46 -07002910
2911 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002912 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002913 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002914 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002915 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002916 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002917 if (!visibleRegion.isEmpty()) {
2918 // Remove the transparent area from the visible region
2919 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002920 if (tr.preserveRects()) {
2921 // transform the transparent region
2922 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002923 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002924 // transformation too complex, can't do the
2925 // transparent region optimization.
2926 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002927 }
Mathias Agopianab028732010-03-16 16:41:46 -07002928 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002929
Mathias Agopianab028732010-03-16 16:41:46 -07002930 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002931 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002932 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002933 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2934 // the opaque region is the layer's footprint
2935 opaqueRegion = visibleRegion;
2936 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002937 }
2938 }
2939
Robert Carre5f4f692018-01-12 13:12:28 -08002940 if (visibleRegion.isEmpty()) {
2941 layer->clearVisibilityRegions();
2942 return;
2943 }
2944
Mathias Agopianab028732010-03-16 16:41:46 -07002945 // Clip the covered region to the visible region
2946 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2947
2948 // Update aboveCoveredLayers for next (lower) layer
2949 aboveCoveredLayers.orSelf(visibleRegion);
2950
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002951 // subtract the opaque region covered by the layers above us
2952 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002953
2954 // compute this layer's dirty region
2955 if (layer->contentDirty) {
2956 // we need to invalidate the whole region
2957 dirty = visibleRegion;
2958 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002959 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002960 layer->contentDirty = false;
2961 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002962 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002963 * the exposed region consists of two components:
2964 * 1) what's VISIBLE now and was COVERED before
2965 * 2) what's EXPOSED now less what was EXPOSED before
2966 *
2967 * note that (1) is conservative, we start with the whole
2968 * visible region but only keep what used to be covered by
2969 * something -- which mean it may have been exposed.
2970 *
2971 * (2) handles areas that were not covered by anything but got
2972 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002973 */
Mathias Agopianab028732010-03-16 16:41:46 -07002974 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002975 const Region oldVisibleRegion = layer->visibleRegion;
2976 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002977 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2978 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002979 }
2980 dirty.subtractSelf(aboveOpaqueLayers);
2981
2982 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002983 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002984
Mathias Agopianab028732010-03-16 16:41:46 -07002985 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002986 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002987
Jesse Halla8026d22012-09-25 13:25:04 -07002988 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002989 layer->setVisibleRegion(visibleRegion);
2990 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002991 layer->setVisibleNonTransparentRegion(
2992 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002993 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002994
Mathias Agopian87baae12012-07-31 12:38:26 -07002995 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002996}
2997
Chia-I Wuab0c3192017-08-01 11:29:00 -07002998void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002999 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003000 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
3001 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003002 }
3003 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003004}
3005
Dan Stoza6b9454d2014-11-07 16:00:59 -08003006bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003007{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003008 ALOGV("handlePageFlip");
3009
Brian Andersond6927fb2016-07-23 23:37:30 -07003010 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003011
Mathias Agopian4fec8732012-06-29 14:12:52 -07003012 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003013 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003014 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003015
3016 // Store the set of layers that need updates. This set must not change as
3017 // buffers are being latched, as this could result in a deadlock.
3018 // Example: Two producers share the same command stream and:
3019 // 1.) Layer 0 is latched
3020 // 2.) Layer 0 gets a new frame
3021 // 2.) Layer 1 gets a new frame
3022 // 3.) Layer 1 is latched.
3023 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3024 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003025 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003026 if (layer->hasQueuedFrame()) {
3027 frameQueued = true;
3028 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003029 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003030 } else {
3031 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003032 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003033 } else {
3034 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003035 }
Robert Carr2047fae2016-11-28 14:09:09 -08003036 });
3037
Dan Stoza9e56aa02015-11-02 13:00:03 -08003038 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07003039 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07003040 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003041 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07003042 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06003043 newDataLatched = true;
3044 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003045 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003046
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003047 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003048
3049 // If we will need to wake up at some time in the future to deal with a
3050 // queued frame that shouldn't be displayed during this vsync period, wake
3051 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003052 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003053 signalLayerUpdate();
3054 }
3055
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003056 // enter boot animation on first buffer latch
3057 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3058 ALOGI("Enter boot animation");
3059 mBootStage = BootStage::BOOTANIMATION;
3060 }
3061
Dan Stoza6b9454d2014-11-07 16:00:59 -08003062 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003063 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003064}
3065
Mathias Agopianad456f92011-01-13 17:53:01 -08003066void SurfaceFlinger::invalidateHwcGeometry()
3067{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003068 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003069}
3070
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003071void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
3072 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003073 // We only need to actually compose the display if:
3074 // 1) It is being handled by hardware composer, which may need this to
3075 // keep its virtual display state machine in sync, or
3076 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07003077 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08003078 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003079 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003080 return;
3081 }
3082
Dan Stoza9e56aa02015-11-02 13:00:03 -08003083 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003084 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003085
3086 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003087 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003088}
3089
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003090bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003091 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003092
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003093 const Region bounds(display->bounds());
3094 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003095 const auto displayId = display->getId();
3096 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003097 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003098
Chia-I Wu8e50e692018-05-04 10:12:37 -07003099 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003100 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003101
Dan Stoza9e56aa02015-11-02 13:00:03 -08003102 if (hasClientComposition) {
3103 ALOGV("hasClientComposition");
3104
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003105 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003106 if (display->hasWideColorGamut()) {
3107 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003108 }
3109 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003110 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003111 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003112
Dominik Laskowski7e045462018-05-30 13:02:02 -07003113 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003114 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3115 HWC2::Capability::SkipClientColorTransform);
3116
Chia-I Wud49d6692018-06-27 07:17:41 +08003117 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003118 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3119 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003120 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003121 }
3122
Chia-I Wud49d6692018-06-27 07:17:41 +08003123 // The current enhanced saturation matrix is designed to enhance Display P3,
3124 // thus we only apply this matrix when the render intent is not colorimetric
3125 // and the output color space is Display P3.
3126 needsEnhancedColorMatrix =
3127 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3128 outputDataspace == Dataspace::DISPLAY_P3);
3129 if (needsEnhancedColorMatrix) {
3130 colorMatrix *= mEnhancedSaturationMatrix;
3131 }
3132
3133 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003134
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003135 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003136 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003137 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003138 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003139
3140 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003141 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3142 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3143 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003144 }
3145 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003146 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003147
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003148 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003149 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003150 // when using overlays, we assume a fully transparent framebuffer
3151 // NOTE: we could reduce how much we need to clear, for instance
3152 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003153 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003154 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003155 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003156 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003157 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003158 // we're left with the letterbox region
3159 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003160 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003161
3162 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003163 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003164
Mathias Agopianb9494d52012-04-18 02:28:45 -07003165 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003166 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003167 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003168 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003169 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003170 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003171
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003172 if (!display->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07003173 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07003174 // scissor on the main display. It should never be needed
3175 // anyways (though in theory it could since the API allows it).
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003176 const Rect& bounds = display->getBounds();
3177 const Rect& scissor = display->getScissor();
Mathias Agopianf45c5102012-10-24 16:29:17 -07003178 if (scissor != bounds) {
3179 // scissor doesn't match the screen's dimensions, so we
3180 // need to clear everything outside of it and enable
3181 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003182
Mathias Agopianf45c5102012-10-24 16:29:17 -07003183 // enable scissor for this frame
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003184 const uint32_t height = display->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08003185 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07003186 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003187 }
3188 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003189 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003190
Mathias Agopian85d751c2012-08-29 16:59:24 -07003191 /*
3192 * and then, render the layers targeted at the framebuffer
3193 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003194
Dan Stoza9e56aa02015-11-02 13:00:03 -08003195 ALOGV("Rendering client layers");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003196 const Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003197 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003198 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003199 const Region clip(bounds.intersect(
3200 displayTransform.transform(layer->visibleRegion)));
3201 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07003202 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003203 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003204 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003205 case HWC2::Composition::Cursor:
3206 case HWC2::Composition::Device:
3207 case HWC2::Composition::Sideband:
3208 case HWC2::Composition::SolidColor: {
3209 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07003210 if (layer->getClearClientTarget(displayId) && !firstLayer &&
3211 layer->isOpaque(state) && (state.color.a == 1.0f) && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003212 // never clear the very first layer since we're
3213 // guaranteed the FB is already cleared
3214 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003215 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003216 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003217 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003218 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003219 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003220 break;
3221 }
3222 default:
3223 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003224 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003225 } else {
3226 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003227 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003228 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003229 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003230
Chia-I Wud49d6692018-06-27 07:17:41 +08003231 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003232 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003233 }
3234
Mathias Agopianf45c5102012-10-24 16:29:17 -07003235 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003236 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003237 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003238}
3239
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003240void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
3241 const Region& region) const {
3242 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003243 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003244 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003245}
3246
Dan Stoza7d89d062015-04-30 13:29:25 -07003247status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003248 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003249 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003250 const sp<Layer>& lbc,
3251 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003252{
Dan Stoza7d89d062015-04-30 13:29:25 -07003253 // add this layer to the current state list
3254 {
3255 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003256 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003257 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3258 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003259 return NO_MEMORY;
3260 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003261 if (parent == nullptr) {
3262 mCurrentState.layersSortedByZ.add(lbc);
3263 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003264 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003265 ALOGE("addClientLayer called with a removed parent");
3266 return NAME_NOT_FOUND;
3267 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003268 parent->addChild(lbc);
3269 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003270
Yiwei Zhang243b3782018-05-15 17:40:04 -07003271 if (gbc != nullptr) {
3272 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3273 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3274 mMaxGraphicBufferProducerListSize,
3275 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3276 mGraphicBufferProducerList.size(),
3277 mMaxGraphicBufferProducerListSize, mNumLayers);
3278 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003279 mLayersAdded = true;
3280 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003281 }
3282
Mathias Agopian96f08192010-06-02 23:28:45 -07003283 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003284 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003285
Dan Stoza7d89d062015-04-30 13:29:25 -07003286 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003287}
3288
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003289status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003290 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003291 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3292}
Robert Carr7f9b8992017-03-10 11:08:39 -08003293
chaviwca27f252018-02-06 16:46:39 -08003294status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3295 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003296 if (layer->isPendingRemoval()) {
3297 return NO_ERROR;
3298 }
3299
Robert Carr1f0a16a2016-10-24 16:27:39 -07003300 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003301 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003302 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003303 if (topLevelOnly) {
3304 return NO_ERROR;
3305 }
3306
Chia-I Wu98f1c102017-05-30 14:54:08 -07003307 sp<Layer> ancestor = p;
3308 while (ancestor->getParent() != nullptr) {
3309 ancestor = ancestor->getParent();
3310 }
3311 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3312 ALOGE("removeLayer called with a layer whose parent has been removed");
3313 return NAME_NOT_FOUND;
3314 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003315
3316 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003317 } else {
3318 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003319 }
3320
Robert Carr136e2f62017-02-08 17:54:29 -08003321 // As a matter of normal operation, the LayerCleaner will produce a second
3322 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3323 // so we will succeed in promoting it, but it's already been removed
3324 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3325 // otherwise something has gone wrong and we are leaking the layer.
3326 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003327 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3328 layer->getName().string(),
3329 (p != nullptr) ? p->getName().string() : "no-parent");
3330 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003331 } else if (index < 0) {
3332 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003333 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003334
Chia-I Wuc6657022017-08-15 11:18:17 -07003335 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003336 mLayersPendingRemoval.add(layer);
3337 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003338 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003339 setTransactionFlags(eTransactionNeeded);
3340 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003341}
3342
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003343uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003344 return android_atomic_release_load(&mTransactionFlags);
3345}
3346
Mathias Agopian3f844832013-08-07 21:24:32 -07003347uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003348 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3349}
3350
Mathias Agopian3f844832013-08-07 21:24:32 -07003351uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003352 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3353}
3354
3355uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3356 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003357 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003358 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003359 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003360 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003361 }
3362 return old;
3363}
3364
chaviwca27f252018-02-06 16:46:39 -08003365bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3366 for (const ComposerState& state : states) {
3367 // Here we need to check that the interface we're given is indeed
3368 // one of our own. A malicious client could give us a nullptr
3369 // IInterface, or one of its own or even one of our own but a
3370 // different type. All these situations would cause us to crash.
3371 if (state.client == nullptr) {
3372 return true;
3373 }
3374
3375 sp<IBinder> binder = IInterface::asBinder(state.client);
3376 if (binder == nullptr) {
3377 return true;
3378 }
3379
3380 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3381 return true;
3382 }
3383 }
3384 return false;
3385}
3386
Mathias Agopian8b33f032012-07-24 20:43:54 -07003387void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003388 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003389 const Vector<DisplayState>& displays,
3390 uint32_t flags)
3391{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003392 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003393 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003394 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003395
chaviwca27f252018-02-06 16:46:39 -08003396 if (containsAnyInvalidClientState(states)) {
3397 return;
3398 }
3399
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003400 if (flags & eAnimation) {
3401 // For window updates that are part of an animation we must wait for
3402 // previous animation "frames" to be handled.
3403 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003404 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003405 if (CC_UNLIKELY(err != NO_ERROR)) {
3406 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003407 // caller after a few seconds.
3408 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3409 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003410 mAnimTransactionPending = false;
3411 break;
3412 }
3413 }
3414 }
3415
chaviwca27f252018-02-06 16:46:39 -08003416 for (const DisplayState& display : displays) {
3417 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003418 }
3419
chaviwca27f252018-02-06 16:46:39 -08003420 for (const ComposerState& state : states) {
3421 transactionFlags |= setClientStateLocked(state);
3422 }
3423
3424 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3425 // as destroyed should only occur after setting all other states. This is to allow for a
3426 // child re-parent to happen before marking its original parent as destroyed (which would
3427 // then mark the child as destroyed).
3428 for (const ComposerState& state : states) {
3429 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003430 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003431
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003432 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3433 // anyway. This can be used as a flush mechanism for previous async transactions.
3434 // Empty animation transaction can be used to simulate back-pressure, so also force a
3435 // transaction for empty animation transactions.
3436 if (transactionFlags == 0 &&
3437 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003438 transactionFlags = eTransactionNeeded;
3439 }
3440
Mathias Agopian386aa982011-11-07 21:58:03 -08003441 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003442 if (mInterceptor->isEnabled()) {
3443 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003444 }
Irvel468051e2016-06-13 16:44:44 -07003445
Mathias Agopian386aa982011-11-07 21:58:03 -08003446 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003447 const auto start = (flags & eEarlyWakeup)
3448 ? VSyncModulator::TransactionStart::EARLY
3449 : VSyncModulator::TransactionStart::NORMAL;
3450 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003451
3452 // if this is a synchronous transaction, wait for it to take effect
3453 // before returning.
3454 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003455 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003456 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003457 if (flags & eAnimation) {
3458 mAnimTransactionPending = true;
3459 }
3460 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003461 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3462 if (CC_UNLIKELY(err != NO_ERROR)) {
3463 // just in case something goes wrong in SF, return to the
3464 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003465 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3466 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003467 break;
3468 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003469 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003470 }
3471}
3472
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003473uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3474 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3475 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003476
Mathias Agopiane57f2922012-08-09 16:29:12 -07003477 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003478 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3479
3480 const uint32_t what = s.what;
3481 if (what & DisplayState::eSurfaceChanged) {
3482 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3483 state.surface = s.surface;
3484 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003485 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003486 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003487 if (what & DisplayState::eLayerStackChanged) {
3488 if (state.layerStack != s.layerStack) {
3489 state.layerStack = s.layerStack;
3490 flags |= eDisplayTransactionNeeded;
3491 }
3492 }
3493 if (what & DisplayState::eDisplayProjectionChanged) {
3494 if (state.orientation != s.orientation) {
3495 state.orientation = s.orientation;
3496 flags |= eDisplayTransactionNeeded;
3497 }
3498 if (state.frame != s.frame) {
3499 state.frame = s.frame;
3500 flags |= eDisplayTransactionNeeded;
3501 }
3502 if (state.viewport != s.viewport) {
3503 state.viewport = s.viewport;
3504 flags |= eDisplayTransactionNeeded;
3505 }
3506 }
3507 if (what & DisplayState::eDisplaySizeChanged) {
3508 if (state.width != s.width) {
3509 state.width = s.width;
3510 flags |= eDisplayTransactionNeeded;
3511 }
3512 if (state.height != s.height) {
3513 state.height = s.height;
3514 flags |= eDisplayTransactionNeeded;
3515 }
3516 }
3517
Mathias Agopiane57f2922012-08-09 16:29:12 -07003518 return flags;
3519}
3520
Robert Carrd4ae7f32018-06-07 16:10:57 -07003521bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3522 IPCThreadState* ipc = IPCThreadState::self();
3523 const int pid = ipc->getCallingPid();
3524 const int uid = ipc->getCallingUid();
3525
3526 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3527 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3528 return false;
3529 }
3530 return true;
3531}
3532
chaviwca27f252018-02-06 16:46:39 -08003533uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3534 const layer_state_t& s = composerState.state;
3535 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3536
Mathias Agopian13127d82013-03-05 17:47:11 -08003537 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003538 if (layer == nullptr) {
3539 return 0;
3540 }
3541
3542 if (layer->isPendingRemoval()) {
3543 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3544 return 0;
3545 }
3546
3547 uint32_t flags = 0;
3548
3549 const uint32_t what = s.what;
3550 bool geometryAppliesWithResize =
3551 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003552
3553 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3554 // pending state will also be deferred.
3555 if (what & layer_state_t::eDeferTransaction) {
3556 layer->pushPendingState();
3557 }
3558
chaviw8b3871a2017-11-01 17:41:01 -07003559 if (what & layer_state_t::ePositionChanged) {
3560 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3561 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003562 }
chaviw8b3871a2017-11-01 17:41:01 -07003563 }
3564 if (what & layer_state_t::eLayerChanged) {
3565 // NOTE: index needs to be calculated before we update the state
3566 const auto& p = layer->getParent();
3567 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003568 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003569 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003570 mCurrentState.layersSortedByZ.removeAt(idx);
3571 mCurrentState.layersSortedByZ.add(layer);
3572 // we need traversal (state changed)
3573 // AND transaction (list changed)
3574 flags |= eTransactionNeeded|eTraversalNeeded;
3575 }
chaviw8b3871a2017-11-01 17:41:01 -07003576 } else {
3577 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003578 flags |= eTransactionNeeded|eTraversalNeeded;
3579 }
3580 }
chaviw8b3871a2017-11-01 17:41:01 -07003581 }
3582 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003583 // NOTE: index needs to be calculated before we update the state
3584 const auto& p = layer->getParent();
3585 if (p == nullptr) {
3586 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3587 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3588 mCurrentState.layersSortedByZ.removeAt(idx);
3589 mCurrentState.layersSortedByZ.add(layer);
3590 // we need traversal (state changed)
3591 // AND transaction (list changed)
3592 flags |= eTransactionNeeded|eTraversalNeeded;
3593 }
3594 } else {
3595 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3596 flags |= eTransactionNeeded|eTraversalNeeded;
3597 }
chaviw8b3871a2017-11-01 17:41:01 -07003598 }
3599 }
3600 if (what & layer_state_t::eSizeChanged) {
3601 if (layer->setSize(s.w, s.h)) {
3602 flags |= eTraversalNeeded;
3603 }
3604 }
3605 if (what & layer_state_t::eAlphaChanged) {
3606 if (layer->setAlpha(s.alpha))
3607 flags |= eTraversalNeeded;
3608 }
3609 if (what & layer_state_t::eColorChanged) {
3610 if (layer->setColor(s.color))
3611 flags |= eTraversalNeeded;
3612 }
3613 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003614 // TODO: b/109894387
3615 //
3616 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3617 // rotation. To see the problem observe that if we have a square parent, and a child
3618 // of the same size, then we rotate the child 45 degrees around it's center, the child
3619 // must now be cropped to a non rectangular 8 sided region.
3620 //
3621 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3622 // private API, and the WindowManager only uses rotation in one case, which is on a top
3623 // level layer in which cropping is not an issue.
3624 //
3625 // However given that abuse of rotation matrices could lead to surfaces extending outside
3626 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3627 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3628 // transformations.
3629 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003630 flags |= eTraversalNeeded;
3631 }
3632 if (what & layer_state_t::eTransparentRegionChanged) {
3633 if (layer->setTransparentRegionHint(s.transparentRegion))
3634 flags |= eTraversalNeeded;
3635 }
3636 if (what & layer_state_t::eFlagsChanged) {
3637 if (layer->setFlags(s.flags, s.mask))
3638 flags |= eTraversalNeeded;
3639 }
3640 if (what & layer_state_t::eCropChanged) {
3641 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3642 flags |= eTraversalNeeded;
3643 }
3644 if (what & layer_state_t::eFinalCropChanged) {
3645 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3646 flags |= eTraversalNeeded;
3647 }
3648 if (what & layer_state_t::eLayerStackChanged) {
3649 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3650 // We only allow setting layer stacks for top level layers,
3651 // everything else inherits layer stack from its parent.
3652 if (layer->hasParent()) {
3653 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3654 layer->getName().string());
3655 } else if (idx < 0) {
3656 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3657 "that also does not appear in the top level layer list. Something"
3658 " has gone wrong.", layer->getName().string());
3659 } else if (layer->setLayerStack(s.layerStack)) {
3660 mCurrentState.layersSortedByZ.removeAt(idx);
3661 mCurrentState.layersSortedByZ.add(layer);
3662 // we need traversal (state changed)
3663 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003664 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003665 }
3666 }
3667 if (what & layer_state_t::eDeferTransaction) {
3668 if (s.barrierHandle != nullptr) {
3669 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3670 } else if (s.barrierGbp != nullptr) {
3671 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3672 if (authenticateSurfaceTextureLocked(gbp)) {
3673 const auto& otherLayer =
3674 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3675 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3676 } else {
3677 ALOGE("Attempt to defer transaction to to an"
3678 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003679 }
3680 }
chaviw8b3871a2017-11-01 17:41:01 -07003681 // We don't trigger a traversal here because if no other state is
3682 // changed, we don't want this to cause any more work
3683 }
3684 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003685 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003686 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003687 if (!hadParent) {
3688 mCurrentState.layersSortedByZ.remove(layer);
3689 }
chaviw8b3871a2017-11-01 17:41:01 -07003690 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003691 }
chaviw8b3871a2017-11-01 17:41:01 -07003692 }
3693 if (what & layer_state_t::eReparentChildren) {
3694 if (layer->reparentChildren(s.reparentHandle)) {
3695 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003696 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003697 }
chaviw8b3871a2017-11-01 17:41:01 -07003698 if (what & layer_state_t::eDetachChildren) {
3699 layer->detachChildren();
3700 }
3701 if (what & layer_state_t::eOverrideScalingModeChanged) {
3702 layer->setOverrideScalingMode(s.overrideScalingMode);
3703 // We don't trigger a traversal here because if no other state is
3704 // changed, we don't want this to cause any more work
3705 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003706 return flags;
3707}
3708
chaviwca27f252018-02-06 16:46:39 -08003709void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3710 const layer_state_t& state = composerState.state;
3711 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3712
3713 sp<Layer> layer(client->getLayerUser(state.surface));
3714 if (layer == nullptr) {
3715 return;
3716 }
3717
3718 if (layer->isPendingRemoval()) {
3719 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3720 return;
3721 }
3722
3723 if (state.what & layer_state_t::eDestroySurface) {
3724 removeLayerLocked(mStateLock, layer);
3725 }
3726}
3727
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003728status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003729 const String8& name,
3730 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003731 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003732 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003733 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003734{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003735 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003736 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003737 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003738 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003739 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003740
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003741 status_t result = NO_ERROR;
3742
3743 sp<Layer> layer;
3744
Cody Northropbc755282017-03-31 12:00:08 -06003745 String8 uniqueName = getUniqueLayerName(name);
3746
Mathias Agopian3165cc22012-08-08 19:42:09 -07003747 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3748 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003749 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003750 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003751 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003752
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003753 break;
chaviw13fdc492017-06-27 12:40:18 -07003754 case ISurfaceComposerClient::eFXSurfaceColor:
3755 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003756 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003757 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003758 break;
3759 default:
3760 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003761 break;
3762 }
3763
Dan Stoza7d89d062015-04-30 13:29:25 -07003764 if (result != NO_ERROR) {
3765 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003766 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003767
Chia-I Wuab0c3192017-08-01 11:29:00 -07003768 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3769 // TODO b/64227542
3770 if (windowType == 441731) {
3771 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3772 layer->setPrimaryDisplayOnly();
3773 }
3774
Albert Chaulk479c60c2017-01-27 14:21:34 -05003775 layer->setInfo(windowType, ownerUid);
3776
Robert Carr1f0a16a2016-10-24 16:27:39 -07003777 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003778 if (result != NO_ERROR) {
3779 return result;
3780 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003781 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003782
3783 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003784 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003785}
3786
Cody Northropbc755282017-03-31 12:00:08 -06003787String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3788{
3789 bool matchFound = true;
3790 uint32_t dupeCounter = 0;
3791
3792 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3793 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3794
Dan Stoza436ccf32018-06-21 12:10:12 -07003795 // Grab the state lock since we're accessing mCurrentState
3796 Mutex::Autolock lock(mStateLock);
3797
Cody Northropbc755282017-03-31 12:00:08 -06003798 // Loop over layers until we're sure there is no matching name
3799 while (matchFound) {
3800 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003801 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003802 if (layer->getName() == uniqueName) {
3803 matchFound = true;
3804 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3805 }
3806 });
3807 }
3808
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003809 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3810 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003811
3812 return uniqueName;
3813}
3814
David Sodman0c69cad2017-08-21 12:12:51 -07003815status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003816 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3817 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003818{
3819 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003820 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003821 case PIXEL_FORMAT_TRANSPARENT:
3822 case PIXEL_FORMAT_TRANSLUCENT:
3823 format = PIXEL_FORMAT_RGBA_8888;
3824 break;
3825 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003826 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003827 break;
3828 }
3829
David Sodman0c69cad2017-08-21 12:12:51 -07003830 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3831 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003832 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003833 *handle = layer->getHandle();
3834 *gbp = layer->getProducer();
3835 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003836 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003837
David Sodman0c69cad2017-08-21 12:12:51 -07003838 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003839 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003840}
3841
chaviw13fdc492017-06-27 12:40:18 -07003842status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003843 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003844 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003845{
chaviw13fdc492017-06-27 12:40:18 -07003846 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003847 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003848 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003849}
3850
Mathias Agopianac9fa422013-02-11 16:40:36 -08003851status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003852{
Robert Carr9524cb32017-02-13 11:32:32 -08003853 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003854 status_t err = NO_ERROR;
3855 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003856 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003857 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003858 err = removeLayer(l);
3859 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3860 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003861 }
3862 return err;
3863}
3864
Mathias Agopian13127d82013-03-05 17:47:11 -08003865status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003866{
Mathias Agopian67106042013-03-14 19:18:13 -07003867 // called by ~LayerCleaner() when all references to the IBinder (handle)
3868 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003869 sp<Layer> l = layer.promote();
3870 if (l == nullptr) {
3871 // The layer has already been removed, carry on
3872 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003873 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003874 // If we have a parent, then we can continue to live as long as it does.
3875 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003876}
3877
Mathias Agopianb60314a2012-04-10 22:09:54 -07003878// ---------------------------------------------------------------------------
3879
Andy McFadden13a082e2012-08-24 10:16:42 -07003880void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003881 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3882 if (!displayToken) return;
3883
Jesse Hall01e29052013-02-19 16:13:35 -08003884 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003885 Vector<ComposerState> state;
3886 Vector<DisplayState> displays;
3887 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003888 d.what = DisplayState::eDisplayProjectionChanged |
3889 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003890 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003891 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003892 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003893 d.frame.makeInvalid();
3894 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003895 d.width = 0;
3896 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003897 displays.add(d);
3898 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003899
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003900 const auto display = getDisplayDevice(displayToken);
3901 if (!display) return;
3902
3903 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3904
3905 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003906 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003907 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003908
Brian Andersond0010582017-03-07 13:20:31 -08003909 // Use phase of 0 since phase is not known.
3910 // Use latency of 0, which will snap to the ideal latency.
3911 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003912}
3913
3914void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003915 // Async since we may be called from the main thread.
3916 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003917}
3918
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003919void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3920 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003921 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003922 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003923
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003924 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003925 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003926 return;
3927 }
3928
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003929 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003930 ALOGW("Trying to set power mode for virtual display");
3931 return;
3932 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003933
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003934 display->setPowerMode(mode);
3935
Lloyd Pique4dccc412018-01-22 17:21:36 -08003936 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003937 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003938 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003939 if (idx < 0) {
3940 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3941 return;
3942 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003943 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003944 }
3945
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003946 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003947 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003948 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003949 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003950 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003951 // FIXME: eventthread only knows about the main display right now
3952 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003953 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003954 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003955
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003956 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003957 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003958 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003959
3960 struct sched_param param = {0};
3961 param.sched_priority = 1;
3962 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3963 ALOGW("Couldn't set SCHED_FIFO on display on");
3964 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003965 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003966 // Turn off the display
3967 struct sched_param param = {0};
3968 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3969 ALOGW("Couldn't set SCHED_OTHER on display off");
3970 }
3971
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003972 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003973 disableHardwareVsync(true); // also cancels any in-progress resync
3974
Mathias Agopiancde87a32012-09-13 14:09:01 -07003975 // FIXME: eventthread only knows about the main display right now
3976 mEventThread->onScreenReleased();
3977 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003978
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003979 getHwComposer().setPowerMode(type, mode);
3980 mVisibleRegionsDirty = true;
3981 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003982 } else if (mode == HWC_POWER_MODE_DOZE ||
3983 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003984 // Update display while dozing
3985 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003986 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003987 // FIXME: eventthread only knows about the main display right now
3988 mEventThread->onScreenAcquired();
3989 resyncToHardwareVsync(true);
3990 }
3991 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3992 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003993 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003994 disableHardwareVsync(true); // also cancels any in-progress resync
3995 // FIXME: eventthread only knows about the main display right now
3996 mEventThread->onScreenReleased();
3997 }
3998 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003999 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004000 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004001 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004002 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004003
4004 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004005}
4006
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004007void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004008 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004009 const auto display = getDisplayDevice(displayToken);
4010 if (!display) {
4011 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4012 displayToken.get());
4013 } else if (display->isVirtual()) {
4014 ALOGW("Attempt to set power mode %d for virtual display", mode);
4015 } else {
4016 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004017 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004018 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004019}
4020
4021// ---------------------------------------------------------------------------
4022
Lloyd Pique755e3192018-01-31 16:46:15 -08004023status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4024 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004025 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004026
Mathias Agopianbd115332013-04-18 16:41:04 -07004027 IPCThreadState* ipc = IPCThreadState::self();
4028 const int pid = ipc->getCallingPid();
4029 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004030
Mathias Agopianbd115332013-04-18 16:41:04 -07004031 if ((uid != AID_SHELL) &&
4032 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004033 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07004034 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004035 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004036 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004037 // (this would indicate SF is stuck, but we want to be able to
4038 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004039 status_t err = mStateLock.timedLock(s2ns(1));
4040 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004041 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004042 result.appendFormat(
4043 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4044 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004045 }
4046
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004047 bool dumpAll = true;
4048 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004049 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004050
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004051 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004052 if ((index < numArgs) &&
4053 (args[index] == String16("--list"))) {
4054 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004055 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004056 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004057 }
4058
4059 if ((index < numArgs) &&
4060 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004061 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004062 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004063 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004064 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004065
4066 if ((index < numArgs) &&
4067 (args[index] == String16("--latency-clear"))) {
4068 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004069 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004070 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004071 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004072
4073 if ((index < numArgs) &&
4074 (args[index] == String16("--dispsync"))) {
4075 index++;
4076 mPrimaryDispSync.dump(result);
4077 dumpAll = false;
4078 }
Dan Stozab90cf072015-03-05 11:05:59 -08004079
4080 if ((index < numArgs) &&
4081 (args[index] == String16("--static-screen"))) {
4082 index++;
4083 dumpStaticScreenStats(result);
4084 dumpAll = false;
4085 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004086
4087 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004088 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004089 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004090 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004091 dumpAll = false;
4092 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004093
4094 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4095 index++;
4096 dumpWideColorInfo(result);
4097 dumpAll = false;
4098 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004099
4100 if ((index < numArgs) &&
4101 (args[index] == String16("--enable-layer-stats"))) {
4102 index++;
4103 mLayerStats.enable();
4104 dumpAll = false;
4105 }
4106
4107 if ((index < numArgs) &&
4108 (args[index] == String16("--disable-layer-stats"))) {
4109 index++;
4110 mLayerStats.disable();
4111 dumpAll = false;
4112 }
4113
4114 if ((index < numArgs) &&
4115 (args[index] == String16("--clear-layer-stats"))) {
4116 index++;
4117 mLayerStats.clear();
4118 dumpAll = false;
4119 }
4120
4121 if ((index < numArgs) &&
4122 (args[index] == String16("--dump-layer-stats"))) {
4123 index++;
4124 mLayerStats.dump(result);
4125 dumpAll = false;
4126 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004127
4128 if ((index < numArgs) &&
4129 (args[index] == String16("--display-identification"))) {
4130 index++;
4131 dumpDisplayIdentificationData(result);
4132 dumpAll = false;
4133 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004134
4135 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4136 index++;
4137 mTimeStats.parseArgs(asProto, args, index, result);
4138 dumpAll = false;
4139 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004140 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004141
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004142 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004143 if (asProto) {
4144 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4145 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4146 } else {
4147 dumpAllLocked(args, index, result);
4148 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004149 }
4150
Mathias Agopian9795c422009-08-26 16:36:26 -07004151 if (locked) {
4152 mStateLock.unlock();
4153 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004154 }
4155 write(fd, result.string(), result.size());
4156 return NO_ERROR;
4157}
4158
Dan Stozac7014012014-02-14 15:03:43 -08004159void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4160 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004161{
Robert Carr2047fae2016-11-28 14:09:09 -08004162 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004163 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004164 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004165}
4166
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004167void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004168 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004169{
4170 String8 name;
4171 if (index < args.size()) {
4172 name = String8(args[index]);
4173 index++;
4174 }
4175
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004176 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4177 getHwComposer().isConnected(displayId)) {
4178 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4179 const nsecs_t period = activeConfig->getVsyncPeriod();
4180 result.appendFormat("%" PRId64 "\n", period);
4181 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004182
4183 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004184 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004185 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004186 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004187 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004188 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004189 }
Robert Carr2047fae2016-11-28 14:09:09 -08004190 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004191 }
4192}
4193
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004194void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004195 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004196{
4197 String8 name;
4198 if (index < args.size()) {
4199 name = String8(args[index]);
4200 index++;
4201 }
4202
Robert Carr2047fae2016-11-28 14:09:09 -08004203 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004204 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004205 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004206 }
Robert Carr2047fae2016-11-28 14:09:09 -08004207 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004208
Svetoslavd85084b2014-03-20 10:28:31 -07004209 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004210}
4211
Jamie Gennis6547ff42013-07-16 20:12:42 -07004212// This should only be called from the main thread. Otherwise it would need
4213// the lock and should use mCurrentState rather than mDrawingState.
4214void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004215 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004216 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004217 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004218
4219 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4220}
4221
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004222void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004223{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004224 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004225
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004226 if (isLayerTripleBufferingDisabled())
4227 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004228
4229 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004230 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004231 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004232 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004233 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4234 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004235 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004236}
4237
Dan Stozab90cf072015-03-05 11:05:59 -08004238void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4239{
4240 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004241 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4242 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004243 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004244 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004245 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4246 b + 1, bucketTimeSec, percent);
4247 }
David Sodman4a36e932017-11-07 14:29:47 -08004248 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004249 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004250 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004251 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004252 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004253}
4254
Dan Stozae77c7662016-05-13 11:37:28 -07004255void SurfaceFlinger::recordBufferingStats(const char* layerName,
4256 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004257 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4258 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004259 for (const auto& segment : history) {
4260 if (!segment.usedThirdBuffer) {
4261 stats.twoBufferTime += segment.totalTime;
4262 }
4263 if (segment.occupancyAverage < 1.0f) {
4264 stats.doubleBufferedTime += segment.totalTime;
4265 } else if (segment.occupancyAverage < 2.0f) {
4266 stats.tripleBufferedTime += segment.totalTime;
4267 }
4268 ++stats.numSegments;
4269 stats.totalTime += segment.totalTime;
4270 }
4271}
4272
Brian Andersond6927fb2016-07-23 23:37:30 -07004273void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4274 result.appendFormat("Layer frame timestamps:\n");
4275
4276 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4277 const size_t count = currentLayers.size();
4278 for (size_t i=0 ; i<count ; i++) {
4279 currentLayers[i]->dumpFrameEvents(result);
4280 }
4281}
4282
Dan Stozae77c7662016-05-13 11:37:28 -07004283void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4284 result.append("Buffering stats:\n");
4285 result.append(" [Layer name] <Active time> <Two buffer> "
4286 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004287 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004288 typedef std::tuple<std::string, float, float, float> BufferTuple;
4289 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004290 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004291 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004292 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004293 if (stats.numSegments == 0) {
4294 continue;
4295 }
4296 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4297 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4298 stats.totalTime;
4299 float doubleBufferRatio = static_cast<float>(
4300 stats.doubleBufferedTime) / stats.totalTime;
4301 float tripleBufferRatio = static_cast<float>(
4302 stats.tripleBufferedTime) / stats.totalTime;
4303 sorted.insert({activeTime, {name, twoBufferRatio,
4304 doubleBufferRatio, tripleBufferRatio}});
4305 }
4306 for (const auto& sortedPair : sorted) {
4307 float activeTime = sortedPair.first;
4308 const BufferTuple& values = sortedPair.second;
4309 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4310 std::get<0>(values).c_str(), activeTime,
4311 std::get<1>(values), std::get<2>(values),
4312 std::get<3>(values));
4313 }
4314 result.append("\n");
4315}
4316
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004317void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004318 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004319 const int32_t displayId = display->getId();
4320 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4321 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004322 continue;
4323 }
4324
Dominik Laskowski7e045462018-05-30 13:02:02 -07004325 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004326 uint8_t port;
4327 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004328 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004329 result.append("no identification data\n");
4330 continue;
4331 }
4332
4333 if (!isEdid(data)) {
4334 result.append("unknown identification data: ");
4335 for (uint8_t byte : data) {
4336 result.appendFormat("%x ", byte);
4337 }
4338 result.append("\n");
4339 continue;
4340 }
4341
4342 const auto edid = parseEdid(data);
4343 if (!edid) {
4344 result.append("invalid EDID: ");
4345 for (uint8_t byte : data) {
4346 result.appendFormat("%x ", byte);
4347 }
4348 result.append("\n");
4349 continue;
4350 }
4351
4352 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4353 result.append(edid->displayName.data(), edid->displayName.length());
4354 result.append("\"\n");
4355 }
4356 result.append("\n");
4357}
4358
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004359void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4360 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004361 result.appendFormat("DisplayColorSetting: %s\n",
4362 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004363
4364 // TODO: print out if wide-color mode is active or not
4365
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004366 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004367 const int32_t displayId = display->getId();
4368 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004369 continue;
4370 }
4371
Dominik Laskowski7e045462018-05-30 13:02:02 -07004372 result.appendFormat("Display %d color modes:\n", displayId);
4373 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004374 for (auto&& mode : modes) {
4375 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4376 }
4377
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004378 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004379 result.appendFormat(" Current color mode: %s (%d)\n",
4380 decodeColorMode(currentMode).c_str(), currentMode);
4381 }
4382 result.append("\n");
4383}
4384
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004385LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004386 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004387 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4388 const State& state = useDrawing ? mDrawingState : mCurrentState;
4389 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004390 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004391 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004392 });
4393
4394 return layersProto;
4395}
4396
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004397LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004398 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004399
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004400 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004401 resolution->set_w(display.getWidth());
4402 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004403
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004404 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4405 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4406 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004407
Dominik Laskowski7e045462018-05-30 13:02:02 -07004408 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004409 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004410 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004411 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004412 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004413 }
4414 });
4415
4416 return layersProto;
4417}
4418
Mathias Agopian74d211a2013-04-22 16:55:35 +02004419void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4420 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004421{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004422 bool colorize = false;
4423 if (index < args.size()
4424 && (args[index] == String16("--color"))) {
4425 colorize = true;
4426 index++;
4427 }
4428
4429 Colorizer colorizer(colorize);
4430
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004431 // figure out if we're stuck somewhere
4432 const nsecs_t now = systemTime();
4433 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4434 const nsecs_t inTransaction(mDebugInTransaction);
4435 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4436 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4437
4438 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004439 * Dump library configuration.
4440 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004441
4442 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004443 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004444 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004445 appendSfConfigString(result);
4446 appendUiConfigString(result);
4447 appendGuiConfigString(result);
4448 result.append("\n");
4449
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004450 result.append("\nDisplay identification data:\n");
4451 dumpDisplayIdentificationData(result);
4452
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004453 result.append("\nWide-Color information:\n");
4454 dumpWideColorInfo(result);
4455
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004456 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004457 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004458 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004459 result.append(SyncFeatures::getInstance().toString());
4460 result.append("\n");
4461
Andy McFadden41d67d72014-04-25 16:58:34 -07004462 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004463 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004464 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004465
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004466 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4467 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004468 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4469 getHwComposer().isConnected(displayId)) {
4470 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004471 result.appendFormat("Display %d: "
4472 "app phase %" PRId64 " ns, "
4473 "sf phase %" PRId64 " ns, "
4474 "early app phase %" PRId64 " ns, "
4475 "early sf phase %" PRId64 " ns, "
4476 "early app gl phase %" PRId64 " ns, "
4477 "early sf gl phase %" PRId64 " ns, "
4478 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4479 displayId,
4480 vsyncPhaseOffsetNs,
4481 sfVsyncPhaseOffsetNs,
4482 appEarlyOffset,
4483 sfEarlyOffset,
4484 appEarlyGlOffset,
4485 sfEarlyOffset,
4486 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004487 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004488 result.append("\n");
4489
Dan Stozab90cf072015-03-05 11:05:59 -08004490 // Dump static screen stats
4491 result.append("\n");
4492 dumpStaticScreenStats(result);
4493 result.append("\n");
4494
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004495 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4496
Dan Stozae77c7662016-05-13 11:37:28 -07004497 dumpBufferingStats(result);
4498
Andy McFadden4803b742012-09-24 19:07:20 -07004499 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004500 * Dump the visible layer list
4501 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004502 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004503 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004504 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4505 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004506 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004507
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004508 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004509 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004510 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004511 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004512
4513 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004514 * Dump Display state
4515 */
4516
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004517 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004518 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004519 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004520 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004521 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004522 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004523 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004524
4525 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004526 * Dump SurfaceFlinger global state
4527 */
4528
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004529 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004530 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004531 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004532
Mathias Agopian888c8222012-08-04 21:10:38 -07004533 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004534 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004535
David Sodmanbc815282017-11-05 18:57:52 -08004536 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004537
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004538 if (display) {
4539 display->undefinedRegion.dump(result, "undefinedRegion");
4540 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4541 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004542 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004543 result.appendFormat(" last eglSwapBuffers() time: %f us\n"
4544 " last transaction time : %f us\n"
4545 " transaction-flags : %08x\n"
4546 " gpu_to_cpu_unsupported : %d\n",
4547 mLastSwapBufferTime / 1000.0, mLastTransactionTime / 1000.0,
4548 mTransactionFlags, !mGpuToCpuSupported);
4549
4550 if (display) {
4551 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4552 result.appendFormat(" refresh-rate : %f fps\n"
4553 " x-dpi : %f\n"
4554 " y-dpi : %f\n",
4555 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4556 activeConfig->getDpiY());
4557 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004558
Mathias Agopian74d211a2013-04-22 16:55:35 +02004559 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004560 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004561
Mathias Agopian74d211a2013-04-22 16:55:35 +02004562 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004563 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004564
4565 /*
4566 * VSYNC state
4567 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004568 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004569 result.append("\n");
4570
4571 /*
4572 * HWC layer minidump
4573 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004574 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004575 const int32_t displayId = display->getId();
4576 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004577 continue;
4578 }
4579
Dominik Laskowski7e045462018-05-30 13:02:02 -07004580 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004581 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004582 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004583 result.append("\n");
4584 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004585
4586 /*
4587 * Dump HWComposer state
4588 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004589 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004590 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004591 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004592 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004593 result.appendFormat(" h/w composer %s\n",
4594 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004595 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004596
4597 /*
4598 * Dump gralloc state
4599 */
4600 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4601 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004602
4603 /*
4604 * Dump VrFlinger state if in use.
4605 */
4606 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4607 result.append("VrFlinger state:\n");
4608 result.append(mVrFlinger->Dump().c_str());
4609 result.append("\n");
4610 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004611}
4612
Dominik Laskowski7e045462018-05-30 13:02:02 -07004613const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004614 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004615 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004616 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004617 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004618 }
4619 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004620
4621 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4622 static const Vector<sp<Layer>> empty;
4623 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004624}
4625
Keun young Park63f165f2012-08-31 10:53:36 -07004626bool SurfaceFlinger::startDdmConnection()
4627{
4628 void* libddmconnection_dso =
4629 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4630 if (!libddmconnection_dso) {
4631 return false;
4632 }
4633 void (*DdmConnection_start)(const char* name);
4634 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004635 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004636 if (!DdmConnection_start) {
4637 dlclose(libddmconnection_dso);
4638 return false;
4639 }
4640 (*DdmConnection_start)(getServiceName());
4641 return true;
4642}
4643
Chia-I Wu28f320b2018-05-03 11:02:56 -07004644void SurfaceFlinger::updateColorMatrixLocked() {
4645 mat4 colorMatrix;
4646 if (mGlobalSaturationFactor != 1.0f) {
4647 // Rec.709 luma coefficients
4648 float3 luminance{0.213f, 0.715f, 0.072f};
4649 luminance *= 1.0f - mGlobalSaturationFactor;
4650 mat4 saturationMatrix = mat4(
4651 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4652 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4653 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4654 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4655 );
4656 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4657 } else {
4658 colorMatrix = mClientColorMatrix * mDaltonizer();
4659 }
4660
4661 if (mCurrentState.colorMatrix != colorMatrix) {
4662 mCurrentState.colorMatrix = colorMatrix;
4663 mCurrentState.colorMatrixChanged = true;
4664 setTransactionFlags(eTransactionNeeded);
4665 }
4666}
4667
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004668status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004669 switch (code) {
4670 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004671 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004672 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004673 case CLEAR_ANIMATION_FRAME_STATS:
4674 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004675 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004676 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004677 case ENABLE_VSYNC_INJECTIONS:
4678 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004679 {
4680 // codes that require permission check
Robert Carrd4ae7f32018-06-07 16:10:57 -07004681 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4682 IPCThreadState* ipc = IPCThreadState::self();
4683 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4684 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004685 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004686 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004687 break;
4688 }
Robert Carr1db73f62016-12-21 12:58:51 -08004689 /*
4690 * Calling setTransactionState is safe, because you need to have been
4691 * granted a reference to Client* and Handle* to do anything with it.
4692 *
4693 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4694 */
4695 case SET_TRANSACTION_STATE:
4696 case CREATE_SCOPED_CONNECTION:
4697 {
4698 return OK;
4699 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004700 case CAPTURE_SCREEN:
4701 {
4702 // codes that require permission check
4703 IPCThreadState* ipc = IPCThreadState::self();
4704 const int pid = ipc->getCallingPid();
4705 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004706 if ((uid != AID_GRAPHICS) &&
4707 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004708 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004709 return PERMISSION_DENIED;
4710 }
4711 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004712 }
chaviwa76b2712017-09-20 12:02:26 -07004713 case CAPTURE_LAYERS: {
4714 IPCThreadState* ipc = IPCThreadState::self();
4715 const int pid = ipc->getCallingPid();
4716 const int uid = ipc->getCallingUid();
4717 if ((uid != AID_GRAPHICS) &&
4718 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4719 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4720 return PERMISSION_DENIED;
4721 }
4722 break;
4723 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004724 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004725 return OK;
4726}
4727
4728status_t SurfaceFlinger::onTransact(
4729 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4730{
4731 status_t credentialCheck = CheckTransactCodeCredentials(code);
4732 if (credentialCheck != OK) {
4733 return credentialCheck;
4734 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004735
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004736 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4737 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004738 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004739 IPCThreadState* ipc = IPCThreadState::self();
4740 const int uid = ipc->getCallingUid();
4741 if (CC_UNLIKELY(uid != AID_SYSTEM
4742 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004743 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004744 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004745 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004746 return PERMISSION_DENIED;
4747 }
4748 int n;
4749 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004750 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004751 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004752 return NO_ERROR;
4753 case 1002: // SHOW_UPDATES
4754 n = data.readInt32();
4755 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004756 invalidateHwcGeometry();
4757 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004758 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004759 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004760 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004761 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004762 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004763 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004764 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004765 setTransactionFlags(
4766 eTransactionNeeded|
4767 eDisplayTransactionNeeded|
4768 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004769 return NO_ERROR;
4770 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004771 case 1006:{ // send empty update
4772 signalRefresh();
4773 return NO_ERROR;
4774 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004775 case 1008: // toggle use of hw composer
4776 n = data.readInt32();
4777 mDebugDisableHWC = n ? 1 : 0;
4778 invalidateHwcGeometry();
4779 repaintEverything();
4780 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004781 case 1009: // toggle use of transform hint
4782 n = data.readInt32();
4783 mDebugDisableTransformHint = n ? 1 : 0;
4784 invalidateHwcGeometry();
4785 repaintEverything();
4786 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004787 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004788 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004789 reply->writeInt32(0);
4790 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004791 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004792 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004793 return NO_ERROR;
4794 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004795 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004796 if (!display) {
4797 return NAME_NOT_FOUND;
4798 }
4799
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004800 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004801 return NO_ERROR;
4802 }
4803 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004804 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004805 // daltonize
4806 n = data.readInt32();
4807 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004808 case 1:
4809 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4810 break;
4811 case 2:
4812 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4813 break;
4814 case 3:
4815 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4816 break;
4817 default:
4818 mDaltonizer.setType(ColorBlindnessType::None);
4819 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004820 }
4821 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004822 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004823 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004824 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004825 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004826
4827 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004828 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004829 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004830 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004831 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004832 // apply a color matrix
4833 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004834 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004835 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004836 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004837 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004838 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004839 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004840 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004841 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004842 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004843 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004844
4845 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4846 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004847 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004848 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4849 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4850 }
4851
Chia-I Wu28f320b2018-05-03 11:02:56 -07004852 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004853 return NO_ERROR;
4854 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004855 // This is an experimental interface
4856 // Needs to be shifted to proper binder interface when we productize
4857 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004858 n = data.readInt32();
4859 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004860 return NO_ERROR;
4861 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004862 case 1017: {
4863 n = data.readInt32();
4864 mForceFullDamage = static_cast<bool>(n);
4865 return NO_ERROR;
4866 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004867 case 1018: { // Modify Choreographer's phase offset
4868 n = data.readInt32();
4869 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4870 return NO_ERROR;
4871 }
4872 case 1019: { // Modify SurfaceFlinger's phase offset
4873 n = data.readInt32();
4874 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4875 return NO_ERROR;
4876 }
Irvel468051e2016-06-13 16:44:44 -07004877 case 1020: { // Layer updates interceptor
4878 n = data.readInt32();
4879 if (n) {
4880 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004881 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004882 }
4883 else{
4884 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004885 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004886 }
4887 return NO_ERROR;
4888 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004889 case 1021: { // Disable HWC virtual displays
4890 n = data.readInt32();
4891 mUseHwcVirtualDisplays = !n;
4892 return NO_ERROR;
4893 }
Romain Guy0147a172017-06-01 13:53:56 -07004894 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004895 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004896 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004897
Chia-I Wu28f320b2018-05-03 11:02:56 -07004898 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004899 return NO_ERROR;
4900 }
Romain Guy54f154a2017-10-24 21:40:32 +01004901 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004902 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004903 invalidateHwcGeometry();
4904 repaintEverything();
4905 return NO_ERROR;
4906 }
4907 case 1024: { // Is wide color gamut rendering/color management supported?
4908 reply->writeBool(hasWideColorDisplay);
4909 return NO_ERROR;
4910 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004911 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004912 n = data.readInt32();
4913 if (n) {
4914 ALOGV("LayerTracing enabled");
4915 mTracing.enable();
4916 doTracing("tracing.enable");
4917 reply->writeInt32(NO_ERROR);
4918 } else {
4919 ALOGV("LayerTracing disabled");
4920 status_t err = mTracing.disable();
4921 reply->writeInt32(err);
4922 }
4923 return NO_ERROR;
4924 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004925 case 1026: { // Get layer tracing status
4926 reply->writeBool(mTracing.isEnabled());
4927 return NO_ERROR;
4928 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004929 // Is a DisplayColorSetting supported?
4930 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004931 const auto display = getDefaultDisplayDevice();
4932 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004933 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004934 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004935
4936 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4937 switch (setting) {
4938 case DisplayColorSetting::MANAGED:
4939 reply->writeBool(hasWideColorDisplay);
4940 break;
4941 case DisplayColorSetting::UNMANAGED:
4942 reply->writeBool(true);
4943 break;
4944 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004945 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004946 break;
4947 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004948 reply->writeBool(
4949 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004950 break;
4951 }
4952 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004953 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004954 // Is VrFlinger active?
4955 case 1028: {
4956 Mutex::Autolock _l(mStateLock);
4957 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4958 return NO_ERROR;
4959 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004960 }
4961 }
4962 return err;
4963}
4964
Steven Thomas6d8110b2017-08-31 18:24:21 -07004965void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004966 android_atomic_or(1, &mRepaintEverything);
4967 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004968}
4969
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004970// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4971class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004972public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004973 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4974 ~WindowDisconnector() {
4975 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004976 }
4977
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004978private:
4979 ANativeWindow* mWindow;
4980 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004981};
4982
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004983status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4984 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4985 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4986 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004987 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004988 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004989
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004990 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004991
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004992 const auto display = getDisplayDeviceLocked(displayToken);
4993 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004994
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004995 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004996
4997 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004998 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004999 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005000}
5001
5002status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08005003 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005004 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005005 ATRACE_CALL();
5006
5007 class LayerRenderArea : public RenderArea {
5008 public:
Robert Carr578038f2018-03-09 12:25:24 -08005009 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
5010 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07005011 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08005012 mLayer(layer),
5013 mCrop(crop),
5014 mFlinger(flinger),
5015 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005016 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005017 Rect getBounds() const override {
5018 const Layer::State& layerState(mLayer->getDrawingState());
5019 return Rect(layerState.active.w, layerState.active.h);
5020 }
5021 int getHeight() const override { return mLayer->getDrawingState().active.h; }
5022 int getWidth() const override { return mLayer->getDrawingState().active.w; }
5023 bool isSecure() const override { return false; }
5024 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005025 Rect getSourceCrop() const override {
5026 if (mCrop.isEmpty()) {
5027 return getBounds();
5028 } else {
5029 return mCrop;
5030 }
5031 }
Robert Carr578038f2018-03-09 12:25:24 -08005032 class ReparentForDrawing {
5033 public:
5034 const sp<Layer>& oldParent;
5035 const sp<Layer>& newParent;
5036
5037 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5038 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005039 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005040 }
Robert Carr15eae092018-03-23 13:43:53 -07005041 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005042 };
5043
5044 void render(std::function<void()> drawLayers) override {
5045 if (!mChildrenOnly) {
5046 mTransform = mLayer->getTransform().inverse();
5047 drawLayers();
5048 } else {
5049 Rect bounds = getBounds();
5050 screenshotParentLayer =
5051 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
5052 bounds.getWidth(), bounds.getHeight(), 0);
5053
5054 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5055 drawLayers();
5056 }
5057 }
chaviwa76b2712017-09-20 12:02:26 -07005058
chaviwa76b2712017-09-20 12:02:26 -07005059 private:
chaviw7206d492017-11-10 16:16:12 -08005060 const sp<Layer> mLayer;
5061 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005062
5063 // In the "childrenOnly" case we reparent the children to a screenshot
5064 // layer which has no properties set and which does not draw.
5065 sp<ContainerLayer> screenshotParentLayer;
5066 Transform mTransform;
5067
5068 SurfaceFlinger* mFlinger;
5069 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005070 };
5071
5072 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5073 auto parent = layerHandle->owner.promote();
5074
chaviw7206d492017-11-10 16:16:12 -08005075 if (parent == nullptr || parent->isPendingRemoval()) {
5076 ALOGE("captureLayers called with a removed parent");
5077 return NAME_NOT_FOUND;
5078 }
5079
Robert Carr578038f2018-03-09 12:25:24 -08005080 const int uid = IPCThreadState::self()->getCallingUid();
5081 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5082 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5083 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5084 return PERMISSION_DENIED;
5085 }
5086
chaviw7206d492017-11-10 16:16:12 -08005087 Rect crop(sourceCrop);
5088 if (sourceCrop.width() <= 0) {
5089 crop.left = 0;
5090 crop.right = parent->getCurrentState().active.w;
5091 }
5092
5093 if (sourceCrop.height() <= 0) {
5094 crop.top = 0;
5095 crop.bottom = parent->getCurrentState().active.h;
5096 }
5097
5098 int32_t reqWidth = crop.width() * frameScale;
5099 int32_t reqHeight = crop.height() * frameScale;
5100
Robert Carr578038f2018-03-09 12:25:24 -08005101 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005102
Robert Carr578038f2018-03-09 12:25:24 -08005103 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005104 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5105 if (!layer->isVisible()) {
5106 return;
Robert Carr578038f2018-03-09 12:25:24 -08005107 } else if (childrenOnly && layer == parent.get()) {
5108 return;
chaviwa76b2712017-09-20 12:02:26 -07005109 }
5110 visitor(layer);
5111 });
5112 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005113 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005114}
5115
5116status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5117 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005118 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005119 bool useIdentityTransform) {
5120 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005121
Iris Chang7501ed62018-04-30 14:45:42 +08005122 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07005123
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005124 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5125 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5126 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5127 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005128
5129 // This mutex protects syncFd and captureResult for communication of the return values from the
5130 // main thread back to this Binder thread
5131 std::mutex captureMutex;
5132 std::condition_variable captureCondition;
5133 std::unique_lock<std::mutex> captureLock(captureMutex);
5134 int syncFd = -1;
5135 std::optional<status_t> captureResult;
5136
Robert Carr03480e22018-01-04 16:02:06 -08005137 const int uid = IPCThreadState::self()->getCallingUid();
5138 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5139
Dominik Laskowski8c001672018-05-30 16:52:06 -07005140 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005141 // If there is a refresh pending, bug out early and tell the binder thread to try again
5142 // after the refresh.
5143 if (mRefreshPending) {
5144 ATRACE_NAME("Skipping screenshot for now");
5145 std::unique_lock<std::mutex> captureLock(captureMutex);
5146 captureResult = std::make_optional<status_t>(EAGAIN);
5147 captureCondition.notify_one();
5148 return;
5149 }
5150
5151 status_t result = NO_ERROR;
5152 int fd = -1;
5153 {
5154 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005155 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005156 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5157 useIdentityTransform, forSystem, &fd);
5158 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005159 }
5160
5161 {
5162 std::unique_lock<std::mutex> captureLock(captureMutex);
5163 syncFd = fd;
5164 captureResult = std::make_optional<status_t>(result);
5165 captureCondition.notify_one();
5166 }
5167 });
5168
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005169 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005170 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005171 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005172 while (*captureResult == EAGAIN) {
5173 captureResult.reset();
5174 result = postMessageAsync(message);
5175 if (result != NO_ERROR) {
5176 return result;
5177 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005178 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005179 }
5180 result = *captureResult;
5181 }
5182
5183 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005184 sync_wait(syncFd, -1);
5185 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005186 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005187
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005188 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005189}
5190
chaviwa76b2712017-09-20 12:02:26 -07005191void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5192 TraverseLayersFunction traverseLayers, bool yswap,
5193 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005194 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005195
Lloyd Pique144e1162017-12-20 16:44:52 -08005196 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005197
5198 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005199 const auto raWidth = renderArea.getWidth();
5200 const auto raHeight = renderArea.getHeight();
5201
5202 const auto reqWidth = renderArea.getReqWidth();
5203 const auto reqHeight = renderArea.getReqHeight();
5204 Rect sourceCrop = renderArea.getSourceCrop();
5205
Iris Chang7501ed62018-04-30 14:45:42 +08005206 bool filtering = false;
5207 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5208 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5209 static_cast<int32_t>(reqHeight) != raWidth;
5210 } else {
5211 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5212 static_cast<int32_t>(reqHeight) != raHeight;
5213 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005214
Dan Stozac1879002014-05-22 15:59:05 -07005215 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005216 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005217 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005218 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005219 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5220 Transform tr;
5221 uint32_t flags = 0x00;
5222 switch (mPrimaryDisplayOrientation) {
5223 case DisplayState::eOrientation90:
5224 flags = Transform::ROT_90;
5225 break;
5226 case DisplayState::eOrientation180:
5227 flags = Transform::ROT_180;
5228 break;
5229 case DisplayState::eOrientation270:
5230 flags = Transform::ROT_270;
5231 break;
5232 }
5233 tr.set(flags, raWidth, raHeight);
5234 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005235 }
5236
5237 // ensure that sourceCrop is inside screen
5238 if (sourceCrop.left < 0) {
5239 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5240 }
chaviwa76b2712017-09-20 12:02:26 -07005241 if (sourceCrop.right > raWidth) {
5242 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005243 }
5244 if (sourceCrop.top < 0) {
5245 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5246 }
chaviwa76b2712017-09-20 12:02:26 -07005247 if (sourceCrop.bottom > raHeight) {
5248 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005249 }
5250
Chia-I Wu36574d92018-05-16 10:54:36 -07005251 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5252 engine.setOutputDataSpace(Dataspace::SRGB);
5253 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005254
Mathias Agopian180f10d2013-04-10 22:55:41 -07005255 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005256 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005257
Iris Chang7501ed62018-04-30 14:45:42 +08005258 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5259 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5260 // convert hw orientation into flag presentation
5261 // here inverse transform needed
5262 uint8_t hw_rot_90 = 0x00;
5263 uint8_t hw_flip_hv = 0x00;
5264 switch (mPrimaryDisplayOrientation) {
5265 case DisplayState::eOrientation90:
5266 hw_rot_90 = Transform::ROT_90;
5267 hw_flip_hv = Transform::ROT_180;
5268 break;
5269 case DisplayState::eOrientation180:
5270 hw_flip_hv = Transform::ROT_180;
5271 break;
5272 case DisplayState::eOrientation270:
5273 hw_rot_90 = Transform::ROT_90;
5274 break;
5275 }
5276
5277 // transform flags operation
5278 // 1) flip H V if both have ROT_90 flag
5279 // 2) XOR these flags
5280 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5281 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5282 if (rotation_rot_90 & hw_rot_90) {
5283 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5284 }
5285 rotation = static_cast<Transform::orientation_flags>
5286 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5287 }
5288
Mathias Agopian180f10d2013-04-10 22:55:41 -07005289 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005290 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005291 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005292 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005293
chaviw50da5042018-04-09 13:49:37 -07005294 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005295 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005296 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005297
chaviwa76b2712017-09-20 12:02:26 -07005298 traverseLayers([&](Layer* layer) {
5299 if (filtering) layer->setFiltering(true);
David Sodmanca10ed22018-04-16 14:10:25 -07005300 layer->drawNow(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005301 if (filtering) layer->setFiltering(false);
5302 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005303}
5304
chaviwa76b2712017-09-20 12:02:26 -07005305status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5306 TraverseLayersFunction traverseLayers,
5307 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005308 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005309 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005310 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005311 ATRACE_CALL();
5312
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005313 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005314
5315 traverseLayers([&](Layer* layer) {
5316 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5317 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005318
Robert Carr03480e22018-01-04 16:02:06 -08005319 // We allow the system server to take screenshots of secure layers for
5320 // use in situations like the Screen-rotation animation and place
5321 // the impetus on WindowManager to not persist them.
5322 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005323 ALOGW("FB is protected: PERMISSION_DENIED");
5324 return PERMISSION_DENIED;
5325 }
5326
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005327 // this binds the given EGLImage as a framebuffer for the
5328 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005329 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005330 if (bufferBond.getStatus() != NO_ERROR) {
5331 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005332 return INVALID_OPERATION;
5333 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005334
Dan Stozaabcda352017-06-01 14:37:39 -07005335 // this will in fact render into our dequeued buffer
5336 // via an FBO, which means we didn't have to create
5337 // an EGLSurface and therefore we're not
5338 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005339 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005340
Dan Stozaabcda352017-06-01 14:37:39 -07005341 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005342 getRenderEngine().finish();
5343 *outSyncFd = -1;
5344
chaviwa76b2712017-09-20 12:02:26 -07005345 const auto reqWidth = renderArea.getReqWidth();
5346 const auto reqHeight = renderArea.getReqHeight();
5347
Dan Stozaabcda352017-06-01 14:37:39 -07005348 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5349 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005350 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005351 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005352 } else {
5353 base::unique_fd syncFd = getRenderEngine().flush();
5354 if (syncFd < 0) {
5355 getRenderEngine().finish();
5356 }
5357 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005358 }
5359
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005360 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005361}
5362
Mathias Agopiand5556842013-09-19 17:08:37 -07005363void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005364 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005365 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005366 for (size_t y = 0; y < h; y++) {
5367 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5368 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005369 if (p[x] != 0xFF000000) return;
5370 }
5371 }
chaviwa76b2712017-09-20 12:02:26 -07005372 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005373
Robert Carr2047fae2016-11-28 14:09:09 -08005374 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005375 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005376 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005377 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5378 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5379 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5380 static_cast<float>(state.color.a));
5381 i++;
5382 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005383 }
5384}
5385
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005386// ---------------------------------------------------------------------------
5387
Dan Stoza412903f2017-04-27 13:42:17 -07005388void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5389 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005390}
5391
Dan Stoza412903f2017-04-27 13:42:17 -07005392void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5393 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005394}
5395
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005396void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5397 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005398 const LayerVector::Visitor& visitor) {
5399 // We loop through the first level of layers without traversing,
5400 // as we need to interpret min/max layer Z in the top level Z space.
5401 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005402 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005403 continue;
5404 }
5405 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005406 // relative layers are traversed in Layer::traverseInZOrder
5407 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005408 continue;
5409 }
5410 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005411 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005412 return;
5413 }
chaviwa76b2712017-09-20 12:02:26 -07005414 if (!layer->isVisible()) {
5415 return;
5416 }
5417 visitor(layer);
5418 });
5419 }
5420}
5421
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005422}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005423
Mathias Agopian3f844832013-08-07 21:24:32 -07005424#if defined(__gl_h_)
5425#error "don't include gl/gl.h in this file"
5426#endif
5427
5428#if defined(__gl2_h_)
5429#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005430#endif