blob: 6b222d5291eb367041b6e7e219f0226f47ba39c8 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Chia-I Wud49d6692018-06-27 07:17:41 +080040#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060041#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070043#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080048#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070050
51#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Robert Carr578038f2018-03-09 12:25:24 -080065#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070066#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070067#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020070#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080072#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080073#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070081#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070082#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070083#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070084#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
Mathias Agopian875d8e12013-06-07 15:35:48 -070086#include "RenderEngine/RenderEngine.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070087#include "Scheduler/DispSync.h"
88#include "Scheduler/EventControlThread.h"
89#include "Scheduler/EventThread.h"
90
Mathias Agopianff2ed702013-09-01 21:36:12 -070091#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070092
Jiyong Park4b20c2e2017-01-14 19:45:11 +090093#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080094#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
95#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090096#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090097
chaviw1d044282017-09-27 12:19:28 -070098#include <layerproto/LayerProtoParser.h>
99
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800100#define DISPLAY_COUNT 1
101
Mathias Agopianfee2b462013-07-03 12:34:01 -0700102/*
103 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
104 * black pixels.
105 */
106#define DEBUG_SCREENSHOTS false
107
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800108namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700109
Jaesoo Lee43518572017-01-23 19:03:16 +0900110using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900111using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700112using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700113using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700114using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700115using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900116
Steven Thomasb02664d2017-07-26 18:48:28 -0700117namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700118
119#pragma clang diagnostic push
120#pragma clang diagnostic error "-Wswitch-enum"
121
122bool isWideColorMode(const ColorMode colorMode) {
123 switch (colorMode) {
124 case ColorMode::DISPLAY_P3:
125 case ColorMode::ADOBE_RGB:
126 case ColorMode::DCI_P3:
127 case ColorMode::BT2020:
128 case ColorMode::BT2100_PQ:
129 case ColorMode::BT2100_HLG:
130 return true;
131 case ColorMode::NATIVE:
132 case ColorMode::STANDARD_BT601_625:
133 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
134 case ColorMode::STANDARD_BT601_525:
135 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
136 case ColorMode::STANDARD_BT709:
137 case ColorMode::SRGB:
138 return false;
139 }
140 return false;
141}
142
143#pragma clang diagnostic pop
144
Steven Thomasb02664d2017-07-26 18:48:28 -0700145class ConditionalLock {
146public:
147 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
148 if (lock) {
149 mMutex.lock();
150 }
151 }
152 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
153private:
154 Mutex& mMutex;
155 bool mLocked;
156};
Peiyong Linfca547f2018-07-09 13:03:33 -0700157
Steven Thomasb02664d2017-07-26 18:48:28 -0700158} // namespace anonymous
159
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800160// ---------------------------------------------------------------------------
161
Mathias Agopian99b49842011-06-27 16:05:52 -0700162const String16 sHardwareTest("android.permission.HARDWARE_TEST");
163const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
164const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
165const String16 sDump("android.permission.DUMP");
166
167// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800168int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
169int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700170int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700171bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800172uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800173bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800174bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800175int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800176// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600177bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700178
Kalle Raitaa099a242017-01-11 11:17:29 -0800179
180std::string getHwcServiceName() {
181 char value[PROPERTY_VALUE_MAX] = {};
182 property_get("debug.sf.hwc_service_name", value, "default");
183 ALOGI("Using HWComposer service: '%s'", value);
184 return std::string(value);
185}
186
187bool useTrebleTestingOverride() {
188 char value[PROPERTY_VALUE_MAX] = {};
189 property_get("debug.sf.treble_testing_override", value, "false");
190 ALOGI("Treble testing override: '%s'", value);
191 return std::string(value) == "true";
192}
193
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800194std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
195 switch(displayColorSetting) {
196 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700197 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800198 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700199 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800200 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700201 return std::string("Enhanced");
202 default:
203 return std::string("Unknown ") +
204 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800205 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800206}
207
Lloyd Pique99d3da52018-01-22 17:48:03 -0800208NativeWindowSurface::~NativeWindowSurface() = default;
209
210namespace impl {
211
212class NativeWindowSurface final : public android::NativeWindowSurface {
213public:
214 static std::unique_ptr<android::NativeWindowSurface> create(
215 const sp<IGraphicBufferProducer>& producer) {
216 return std::make_unique<NativeWindowSurface>(producer);
217 }
218
219 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
220 : surface(new Surface(producer, false)) {}
221
222 ~NativeWindowSurface() override = default;
223
224private:
225 sp<ANativeWindow> getNativeWindow() const override { return surface; }
226
227 void preallocateBuffers() override { surface->allocateBuffers(); }
228
229 sp<Surface> surface;
230};
231
232} // namespace impl
233
David Sodmanbc815282017-11-05 18:57:52 -0800234SurfaceFlingerBE::SurfaceFlingerBE()
235 : mHwcServiceName(getHwcServiceName()),
236 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800237 mFrameBuckets(),
238 mTotalTime(0),
239 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800240 mComposerSequenceId(0) {
241}
242
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800243SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800244 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800245 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700246 mTransactionPending(false),
247 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700248 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700249 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700250 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800251 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700252 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800253 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800254 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800255 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800256 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700258 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700259 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700260 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700261 mDebugInSwapBuffers(0),
262 mLastSwapBufferTime(0),
263 mDebugInTransaction(0),
264 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700265 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700266 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700267 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800268 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800269 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700270 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800271 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800272 mCreateBufferQueue(&BufferQueue::createBufferQueue),
273 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800274
275SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800276 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800277
278 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
279 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
280
281 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
282 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
283
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800284 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
285 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800286
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700287 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
288 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
289
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700290 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
291 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
292
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800293 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
294 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
295
Steven Thomas050b2c82017-03-06 11:45:16 -0800296 // Vr flinger is only enabled on Daydream ready devices.
297 useVrFlinger = getBool< ISurfaceFlingerConfigs,
298 &ISurfaceFlingerConfigs::useVrFlinger>(false);
299
Fabien Sanglard1971b632017-03-10 14:50:03 -0800300 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
301 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
302
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600303 hasWideColorDisplay =
304 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
305
Iris Chang7501ed62018-04-30 14:45:42 +0800306 V1_1::DisplayOrientation primaryDisplayOrientation =
307 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
308 V1_1::DisplayOrientation::ORIENTATION_0);
309
310 switch (primaryDisplayOrientation) {
311 case V1_1::DisplayOrientation::ORIENTATION_90:
312 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
313 break;
314 case V1_1::DisplayOrientation::ORIENTATION_180:
315 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
316 break;
317 case V1_1::DisplayOrientation::ORIENTATION_270:
318 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
319 break;
320 default:
321 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
322 break;
323 }
324 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
325
Lloyd Pique41be5d22018-06-21 13:11:48 -0700326 // Note: We create a local temporary with the real DispSync implementation
327 // type temporarily so we can initialize it with the configured values,
328 // before storing it for more generic use using the interface type.
329 auto primaryDispSync = std::make_unique<impl::DispSync>("PrimaryDispSync");
330 primaryDispSync->init(SurfaceFlinger::hasSyncFramework,
331 SurfaceFlinger::dispSyncPresentTimeOffset);
332 mPrimaryDispSync = std::move(primaryDispSync);
Saurabh Shahf4174532017-07-13 10:45:07 -0700333
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800334 // debugging stuff...
335 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700336
Mathias Agopianb4b17302013-03-20 18:36:41 -0700337 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700338 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700339
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800340 property_get("debug.sf.showupdates", value, "0");
341 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700342
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700343 property_get("debug.sf.ddms", value, "0");
344 mDebugDDMS = atoi(value);
345 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700346 if (!startDdmConnection()) {
347 // start failed, and DDMS debugging not enabled
348 mDebugDDMS = 0;
349 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700350 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700351 ALOGI_IF(mDebugRegion, "showupdates enabled");
352 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700353
354 property_get("debug.sf.disable_backpressure", value, "0");
355 mPropagateBackpressure = !atoi(value);
356 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700357
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800358 property_get("debug.sf.enable_hwc_vds", value, "0");
359 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800360 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800361
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800362 property_get("ro.sf.disable_triple_buffer", value, "1");
363 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800364 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700365
Yiwei Zhang243b3782018-05-15 17:40:04 -0700366 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700367 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
368 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
369
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200370 property_get("debug.sf.early_phase_offset_ns", value, "-1");
371 const int earlySfOffsetNs = atoi(value);
372
373 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
374 const int earlyGlSfOffsetNs = atoi(value);
375
376 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
377 const int earlyAppOffsetNs = atoi(value);
378
379 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
380 const int earlyGlAppOffsetNs = atoi(value);
381
382 const VSyncModulator::Offsets earlyOffsets =
383 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
384 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
385 const VSyncModulator::Offsets earlyGlOffsets =
386 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
387 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
388 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
389 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700390
Romain Guy11d63f42017-07-20 12:47:14 -0700391 // We should be reading 'persist.sys.sf.color_saturation' here
392 // but since /data may be encrypted, we need to wait until after vold
393 // comes online to attempt to read the property. The property is
394 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800395
396 if (useTrebleTestingOverride()) {
397 // Without the override SurfaceFlinger cannot connect to HIDL
398 // services that are not listed in the manifests. Considered
399 // deriving the setting from the set service name, but it
400 // would be brittle if the name that's not 'default' is used
401 // for production purposes later on.
402 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
403 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800404}
405
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800406void SurfaceFlinger::onFirstRef()
407{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800408 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800409}
410
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800411SurfaceFlinger::~SurfaceFlinger()
412{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800413}
414
Dan Stozac7014012014-02-14 15:03:43 -0800415void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800416{
417 // the window manager died on us. prepare its eulogy.
418
Andy McFadden13a082e2012-08-24 10:16:42 -0700419 // restore initial conditions (default device unblank, etc)
420 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800421
422 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700423 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800424}
425
Robert Carr1db73f62016-12-21 12:58:51 -0800426static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700427 status_t err = client->initCheck();
428 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800429 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800430 }
Robert Carr1db73f62016-12-21 12:58:51 -0800431 return nullptr;
432}
433
434sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
435 return initClient(new Client(this));
436}
437
438sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
439 const sp<IGraphicBufferProducer>& gbp) {
440 if (authenticateSurfaceTexture(gbp) == false) {
441 return nullptr;
442 }
443 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
444 if (layer == nullptr) {
445 return nullptr;
446 }
447
448 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800449}
450
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700451sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
452 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700453{
454 class DisplayToken : public BBinder {
455 sp<SurfaceFlinger> flinger;
456 virtual ~DisplayToken() {
457 // no more references, this display must be terminated
458 Mutex::Autolock _l(flinger->mStateLock);
459 flinger->mCurrentState.displays.removeItem(this);
460 flinger->setTransactionFlags(eDisplayTransactionNeeded);
461 }
462 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700463 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700464 : flinger(flinger) {
465 }
466 };
467
468 sp<BBinder> token = new DisplayToken(this);
469
470 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700471 DisplayDeviceState info;
472 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700473 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700474 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700475 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800476 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700477 return token;
478}
479
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700480void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700481 Mutex::Autolock _l(mStateLock);
482
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700483 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700484 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700485 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700486 return;
487 }
488
489 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700490 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700491 ALOGE("destroyDisplay called for non-virtual display");
492 return;
493 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700494 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700495 mCurrentState.displays.removeItemsAt(idx);
496 setTransactionFlags(eDisplayTransactionNeeded);
497}
498
Mathias Agopiane57f2922012-08-09 16:29:12 -0700499sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700500 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700501 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800502 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700503 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700504 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700505}
506
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800507void SurfaceFlinger::bootFinished()
508{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700509 if (mStartPropertySetThread->join() != NO_ERROR) {
510 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800511 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800512 const nsecs_t now = systemTime();
513 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000514 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700515
516 // wait patiently for the window manager death
517 const String16 name("window");
518 sp<IBinder> window(defaultServiceManager()->getService(name));
519 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700520 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700521 }
522
Steven Thomas050b2c82017-03-06 11:45:16 -0800523 if (mVrFlinger) {
524 mVrFlinger->OnBootFinished();
525 }
526
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700527 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700528 // formerly we would just kill the process, but we now ask it to exit so it
529 // can choose where to stop the animation.
530 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700531
532 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
533 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
534 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700535
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800536 postMessageAsync(new LambdaMessage([this] {
537 readPersistentProperties();
538 mBootStage = BootStage::FINISHED;
539 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800540}
541
Dan Stoza436ccf32018-06-21 12:10:12 -0700542uint32_t SurfaceFlinger::getNewTexture() {
543 {
544 std::lock_guard lock(mTexturePoolMutex);
545 if (!mTexturePool.empty()) {
546 uint32_t name = mTexturePool.back();
547 mTexturePool.pop_back();
548 ATRACE_INT("TexturePoolSize", mTexturePool.size());
549 return name;
550 }
551
552 // The pool was too small, so increase it for the future
553 ++mTexturePoolSize;
554 }
555
556 // The pool was empty, so we need to get a new texture name directly using a
557 // blocking call to the main thread
558 uint32_t name = 0;
559 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
560 return name;
561}
562
Mathias Agopian3f844832013-08-07 21:24:32 -0700563void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700564 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700565}
566
Lloyd Piquee83f9312018-02-01 12:53:17 -0800567class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700568public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700569 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000570 const char* name) :
571 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700572 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700573 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000574 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
575 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700576 mDispSync(dispSync),
577 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700578 mVsyncMutex(),
579 mPhaseOffset(phaseOffset),
580 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700581
Lloyd Piquee83f9312018-02-01 12:53:17 -0800582 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700583
Lloyd Piquee83f9312018-02-01 12:53:17 -0800584 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700585 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700586 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000587 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700588 static_cast<DispSync::Callback*>(this));
589 if (err != NO_ERROR) {
590 ALOGE("error registering vsync callback: %s (%d)",
591 strerror(-err), err);
592 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700593 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700594 } else {
595 status_t err = mDispSync->removeEventListener(
596 static_cast<DispSync::Callback*>(this));
597 if (err != NO_ERROR) {
598 ALOGE("error unregistering vsync callback: %s (%d)",
599 strerror(-err), err);
600 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700601 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700602 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700603 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700604 }
605
Lloyd Piquee83f9312018-02-01 12:53:17 -0800606 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700607 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700608 mCallback = callback;
609 }
610
Lloyd Piquee83f9312018-02-01 12:53:17 -0800611 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700612 Mutex::Autolock lock(mVsyncMutex);
613
614 // Normalize phaseOffset to [0, period)
615 auto period = mDispSync->getPeriod();
616 phaseOffset %= period;
617 if (phaseOffset < 0) {
618 // If we're here, then phaseOffset is in (-period, 0). After this
619 // operation, it will be in (0, period)
620 phaseOffset += period;
621 }
622 mPhaseOffset = phaseOffset;
623
624 // If we're not enabled, we don't need to mess with the listeners
625 if (!mEnabled) {
626 return;
627 }
628
Dan Stoza84d619e2018-03-28 17:07:36 -0700629 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
630 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700631 if (err != NO_ERROR) {
Dan Stoza84d619e2018-03-28 17:07:36 -0700632 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700633 strerror(-err), err);
634 }
635 }
636
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700637private:
638 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800639 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700640 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700641 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700642 callback = mCallback;
643
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700644 if (mTraceVsync) {
645 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700646 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700647 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700648 }
649
Peiyong Lin566a3b42018-01-09 18:22:43 -0800650 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700651 callback->onVSyncEvent(when);
652 }
653 }
654
Tim Murray4a4e4a22016-04-19 16:29:23 +0000655 const char* const mName;
656
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700657 int mValue;
658
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700659 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700660 const String8 mVsyncOnLabel;
661 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700662
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700663 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700664
665 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800666 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700667
668 Mutex mVsyncMutex; // Protects the following
669 nsecs_t mPhaseOffset;
670 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700671};
672
Lloyd Piquee83f9312018-02-01 12:53:17 -0800673class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700674public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800675 InjectVSyncSource() = default;
676 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700677
Lloyd Piquee83f9312018-02-01 12:53:17 -0800678 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700679 std::lock_guard<std::mutex> lock(mCallbackMutex);
680 mCallback = callback;
681 }
682
Lloyd Piquee83f9312018-02-01 12:53:17 -0800683 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700684 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700685 if (mCallback) {
686 mCallback->onVSyncEvent(when);
687 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700688 }
689
Lloyd Piquee83f9312018-02-01 12:53:17 -0800690 void setVSyncEnabled(bool) override {}
691 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700692
693private:
694 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800695 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700696};
697
Wei Wangf9b05ee2017-07-19 20:59:39 -0700698// Do not call property_set on main thread which will be blocked by init
699// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700700void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700701 ALOGI( "SurfaceFlinger's main thread ready to run. "
702 "Initializing graphics H/W...");
703
Thierry Strudel2924d012017-08-14 15:19:37 -0700704 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900705
Steven Thomasb02664d2017-07-26 18:48:28 -0700706 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800707
Steven Thomasb02664d2017-07-26 18:48:28 -0700708 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800709 mEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700710 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
711 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800712 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700713 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800714 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800715 "appEventThread");
716 mSfEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700717 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800718 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800719
Lloyd Pique24b0a482018-03-09 18:52:26 -0800720 mSFEventThread =
721 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700722 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800723 [this](nsecs_t timestamp) {
724 mInterceptor->saveVSyncEvent(timestamp);
725 },
726 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800727 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200728 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800729
Steven Thomasb02664d2017-07-26 18:48:28 -0700730 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800731 getBE().mRenderEngine =
732 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
733 hasWideColorDisplay
734 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
735 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800736 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700737
738 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
739 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800740 getBE().mHwc.reset(
741 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700742 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800743 // Process any initial hotplug and resulting display changes.
744 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700745 const auto display = getDefaultDisplayDeviceLocked();
746 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
747 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
748 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800749
Lloyd Piquefcd86612017-12-14 17:15:36 -0800750 // make the default display GLContext current so that we can create textures
751 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700752 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800753
Steven Thomas050b2c82017-03-06 11:45:16 -0800754 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700755 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700756 // This callback is called from the vr flinger dispatch thread. We
757 // need to call signalTransaction(), which requires holding
758 // mStateLock when we're not on the main thread. Acquiring
759 // mStateLock from the vr flinger dispatch thread might trigger a
760 // deadlock in surface flinger (see b/66916578), so post a message
761 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700762 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700763 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
764 mVrFlingerRequestsDisplay = requestDisplay;
765 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700766 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800767 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700768 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
769 getHwComposer()
770 .getHwcDisplayId(display->getId())
771 .value_or(0),
772 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800773 if (!mVrFlinger) {
774 ALOGE("Failed to start vrflinger");
775 }
776 }
777
Lloyd Pique379adc12018-01-22 17:31:47 -0800778 mEventControlThread = std::make_unique<impl::EventControlThread>(
779 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700780
Mathias Agopian92a979a2012-08-02 18:32:23 -0700781 // initialize our drawing state
782 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700783
Andy McFadden13a082e2012-08-24 10:16:42 -0700784 // set initial conditions (e.g. unblank default device)
785 initializeDisplays();
786
David Sodmanbc815282017-11-05 18:57:52 -0800787 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700788
Wei Wangf9b05ee2017-07-19 20:59:39 -0700789 // Inform native graphics APIs whether the present timestamp is supported:
790 if (getHwComposer().hasCapability(
791 HWC2::Capability::PresentFenceIsNotReliable)) {
792 mStartPropertySetThread = new StartPropertySetThread(false);
793 } else {
794 mStartPropertySetThread = new StartPropertySetThread(true);
795 }
796
797 if (mStartPropertySetThread->Start() != NO_ERROR) {
798 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800799 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800800
Chia-I Wud49d6692018-06-27 07:17:41 +0800801 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
802 // is used to saturate legacy sRGB content. However, to make sure the same color under
803 // Display P3 will be saturated to the same color, we intentionally break the API spec
804 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
805 // such saturation matrix on Display P3 is understood fully, the API should always return
806 // identify matrix.
807 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
808 Dataspace::SRGB_LINEAR);
809
810 // we will apply this on Display P3.
811 if (mEnhancedSaturationMatrix != mat4()) {
812 ColorSpace srgb(ColorSpace::sRGB());
813 ColorSpace displayP3(ColorSpace::DisplayP3());
814 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
815 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
816 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
817 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800818
Dan Stoza9e56aa02015-11-02 13:00:03 -0800819 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700820}
821
Romain Guy11d63f42017-07-20 12:47:14 -0700822void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700823 Mutex::Autolock _l(mStateLock);
824
Romain Guy11d63f42017-07-20 12:47:14 -0700825 char value[PROPERTY_VALUE_MAX];
826
827 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800828 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700829 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800830 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100831
832 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700833 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700834}
835
Mathias Agopiana67e4182012-06-19 17:26:12 -0700836void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800837 // Start boot animation service by setting a property mailbox
838 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700839 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800840 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700841 if (mStartPropertySetThread->join() != NO_ERROR) {
842 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800843 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700844}
845
Mathias Agopian875d8e12013-06-07 15:35:48 -0700846size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800847 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700848}
849
Mathias Agopian875d8e12013-06-07 15:35:48 -0700850size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800851 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700852}
853
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800854// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800855
Jamie Gennis582270d2011-08-17 18:19:00 -0700856bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800857 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800858 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800859 return authenticateSurfaceTextureLocked(bufferProducer);
860}
861
862bool SurfaceFlinger::authenticateSurfaceTextureLocked(
863 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800864 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800865 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800866}
867
Brian Anderson6b376712017-04-04 10:51:39 -0700868status_t SurfaceFlinger::getSupportedFrameTimestamps(
869 std::vector<FrameEvent>* outSupported) const {
870 *outSupported = {
871 FrameEvent::REQUESTED_PRESENT,
872 FrameEvent::ACQUIRE,
873 FrameEvent::LATCH,
874 FrameEvent::FIRST_REFRESH_START,
875 FrameEvent::LAST_REFRESH_START,
876 FrameEvent::GPU_COMPOSITION_DONE,
877 FrameEvent::DEQUEUE_READY,
878 FrameEvent::RELEASE,
879 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700880 ConditionalLock _l(mStateLock,
881 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700882 if (!getHwComposer().hasCapability(
883 HWC2::Capability::PresentFenceIsNotReliable)) {
884 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
885 }
886 return NO_ERROR;
887}
888
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700889status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
890 Vector<DisplayInfo>* configs) {
891 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700892 return BAD_VALUE;
893 }
894
Jesse Hall692c7232012-11-08 15:41:56 -0800895 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700896 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
897 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700898 type = i;
899 break;
900 }
901 }
902
903 if (type < 0) {
904 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700905 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700906
Mathias Agopian8b736f12012-08-13 17:54:26 -0700907 // TODO: Not sure if display density should handled by SF any longer
908 class Density {
909 static int getDensityFromProperty(char const* propName) {
910 char property[PROPERTY_VALUE_MAX];
911 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800912 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700913 density = atoi(property);
914 }
915 return density;
916 }
917 public:
918 static int getEmuDensity() {
919 return getDensityFromProperty("qemu.sf.lcd_density"); }
920 static int getBuildDensity() {
921 return getDensityFromProperty("ro.sf.lcd_density"); }
922 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700923
Dan Stoza7f7da322014-05-02 15:26:25 -0700924 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700925
Steven Thomas6d8110b2017-08-31 18:24:21 -0700926 ConditionalLock _l(mStateLock,
927 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800928 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700929 DisplayInfo info = DisplayInfo();
930
Dan Stoza9e56aa02015-11-02 13:00:03 -0800931 float xdpi = hwConfig->getDpiX();
932 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700933
934 if (type == DisplayDevice::DISPLAY_PRIMARY) {
935 // The density of the device is provided by a build property
936 float density = Density::getBuildDensity() / 160.0f;
937 if (density == 0) {
938 // the build doesn't provide a density -- this is wrong!
939 // use xdpi instead
940 ALOGE("ro.sf.lcd_density must be defined as a build property");
941 density = xdpi / 160.0f;
942 }
943 if (Density::getEmuDensity()) {
944 // if "qemu.sf.lcd_density" is specified, it overrides everything
945 xdpi = ydpi = density = Density::getEmuDensity();
946 density /= 160.0f;
947 }
948 info.density = density;
949
950 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700951 const auto display = getDefaultDisplayDeviceLocked();
952 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700953 } else {
954 // TODO: where should this value come from?
955 static const int TV_DENSITY = 213;
956 info.density = TV_DENSITY / 160.0f;
957 info.orientation = 0;
958 }
959
Dan Stoza9e56aa02015-11-02 13:00:03 -0800960 info.w = hwConfig->getWidth();
961 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700962 info.xdpi = xdpi;
963 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800964 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900965 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800966
Andy McFadden91b2ca82014-06-13 14:04:23 -0700967 // This is how far in advance a buffer must be queued for
968 // presentation at a given time. If you want a buffer to appear
969 // on the screen at time N, you must submit the buffer before
970 // (N - presentationDeadline).
971 //
972 // Normally it's one full refresh period (to give SF a chance to
973 // latch the buffer), but this can be reduced by configuring a
974 // DispSync offset. Any additional delays introduced by the hardware
975 // composer or panel must be accounted for here.
976 //
977 // We add an additional 1ms to allow for processing time and
978 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800979 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800980 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700981
982 // All non-virtual displays are currently considered secure.
983 info.secure = true;
984
Iris Chang7501ed62018-04-30 14:45:42 +0800985 if (type == DisplayDevice::DISPLAY_PRIMARY &&
986 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
987 std::swap(info.w, info.h);
988 }
989
Michael Wright28f24d02016-07-12 13:30:53 -0700990 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700991 }
992
Dan Stoza7f7da322014-05-02 15:26:25 -0700993 return NO_ERROR;
994}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700995
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700996status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
997 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700998 return BAD_VALUE;
999 }
1000
1001 // FIXME for now we always return stats for the primary display
1002 memset(stats, 0, sizeof(*stats));
Lloyd Pique41be5d22018-06-21 13:11:48 -07001003 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1004 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001005 return NO_ERROR;
1006}
1007
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001008int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
1009 const auto display = getDisplayDevice(displayToken);
1010 if (!display) {
1011 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +08001012 return BAD_VALUE;
1013 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001014
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001015 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -07001016}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001017
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001018void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
1019 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001020 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001021 return;
1022 }
1023
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001024 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001025 ALOGW("Trying to set config for virtual display");
1026 return;
1027 }
1028
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001029 display->setActiveConfig(mode);
1030 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001031}
1032
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001033status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001034 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001035 Vector<DisplayInfo> configs;
1036 getDisplayConfigs(displayToken, &configs);
1037 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
1038 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
1039 configs.size());
1040 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001041 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001042 const auto display = getDisplayDevice(displayToken);
1043 if (!display) {
1044 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
1045 displayToken.get());
1046 } else if (display->isVirtual()) {
1047 ALOGW("Attempt to set active config %d for virtual display", mode);
1048 } else {
1049 setActiveConfigInternal(display, mode);
1050 }
1051 }));
1052
Mathias Agopian888c8222012-08-04 21:10:38 -07001053 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001054}
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001055status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1056 Vector<ColorMode>* outColorModes) {
1057 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001058 return BAD_VALUE;
1059 }
1060
Michael Wright28f24d02016-07-12 13:30:53 -07001061 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001062 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
1063 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -07001064 type = i;
1065 break;
1066 }
1067 }
1068
1069 if (type < 0) {
1070 return type;
1071 }
1072
Peiyong Lina52f0292018-03-14 17:26:31 -07001073 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001074 {
1075 ConditionalLock _l(mStateLock,
1076 std::this_thread::get_id() != mMainThreadId);
1077 modes = getHwComposer().getColorModes(type);
1078 }
Michael Wright28f24d02016-07-12 13:30:53 -07001079 outColorModes->clear();
1080 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1081
1082 return NO_ERROR;
1083}
1084
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001085ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1086 if (const auto display = getDisplayDevice(displayToken)) {
1087 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001088 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001089 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001090}
1091
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001092void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1093 Dataspace dataSpace, RenderIntent renderIntent) {
1094 ColorMode currentMode = display->getActiveColorMode();
1095 Dataspace currentDataSpace = display->getCompositionDataSpace();
1096 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001097
Peiyong Lin38e9a562018-04-10 16:24:20 -07001098 if (mode == currentMode && dataSpace == currentDataSpace &&
1099 renderIntent == currentRenderIntent) {
1100 return;
1101 }
1102
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001103 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001104 ALOGW("Trying to set config for virtual display");
1105 return;
1106 }
1107
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001108 display->setActiveColorMode(mode);
1109 display->setCompositionDataSpace(dataSpace);
1110 display->setActiveRenderIntent(renderIntent);
1111 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001112
1113 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001114 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1115 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001116}
1117
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001118status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001119 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001120 Vector<ColorMode> modes;
1121 getDisplayColorModes(displayToken, &modes);
1122 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1123 if (mode < ColorMode::NATIVE || !exists) {
1124 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1125 decodeColorMode(mode).c_str(), mode, displayToken.get());
1126 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001127 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001128 const auto display = getDisplayDevice(displayToken);
1129 if (!display) {
1130 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1131 decodeColorMode(mode).c_str(), mode, displayToken.get());
1132 } else if (display->isVirtual()) {
1133 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1134 decodeColorMode(mode).c_str(), mode);
1135 } else {
1136 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1137 RenderIntent::COLORIMETRIC);
1138 }
1139 }));
1140
Michael Wright28f24d02016-07-12 13:30:53 -07001141 return NO_ERROR;
1142}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001143
Svetoslavd85084b2014-03-20 10:28:31 -07001144status_t SurfaceFlinger::clearAnimationFrameStats() {
1145 Mutex::Autolock _l(mStateLock);
1146 mAnimFrameTracker.clearStats();
1147 return NO_ERROR;
1148}
1149
1150status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1151 Mutex::Autolock _l(mStateLock);
1152 mAnimFrameTracker.getStats(outStats);
1153 return NO_ERROR;
1154}
1155
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001156status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1157 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001158 Mutex::Autolock _l(mStateLock);
1159
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001160 const auto display = getDisplayDeviceLocked(displayToken);
1161 if (!display) {
1162 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001163 return BAD_VALUE;
1164 }
1165
Peiyong Linfb069302018-04-25 14:34:31 -07001166 // At this point the DisplayDeivce should already be set up,
1167 // meaning the luminance information is already queried from
1168 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001169 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001170 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1171 capabilities.getDesiredMaxLuminance(),
1172 capabilities.getDesiredMaxAverageLuminance(),
1173 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001174
1175 return NO_ERROR;
1176}
1177
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001178status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001179 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001180 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001181
Chia-I Wu90f669f2017-10-05 14:24:41 -07001182 if (mInjectVSyncs == enable) {
1183 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001184 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001185
1186 if (enable) {
1187 ALOGV("VSync Injections enabled");
1188 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001189 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001190 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001191 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001192 impl::EventThread::InterceptVSyncsCallback(),
1193 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001194 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001195 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001196 } else {
1197 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001198 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001199 }
1200
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001201 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001202 }));
1203
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001204 return NO_ERROR;
1205}
1206
1207status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001208 Mutex::Autolock _l(mStateLock);
1209
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001210 if (!mInjectVSyncs) {
1211 ALOGE("VSync Injections not enabled");
1212 return BAD_VALUE;
1213 }
1214 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1215 ALOGV("Injecting VSync inside SurfaceFlinger");
1216 mVSyncInjector->onInjectSyncEvent(when);
1217 }
1218 return NO_ERROR;
1219}
1220
Lloyd Pique755e3192018-01-31 16:46:15 -08001221status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1222 NO_THREAD_SAFETY_ANALYSIS {
Dan Stozae3344402018-08-20 19:53:42 +00001223 IPCThreadState* ipc = IPCThreadState::self();
1224 const int pid = ipc->getCallingPid();
1225 const int uid = ipc->getCallingUid();
1226 if ((uid != AID_SHELL) &&
1227 !PermissionCache::checkPermission(sDump, pid, uid)) {
1228 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1229 return PERMISSION_DENIED;
1230 }
1231
Kalle Raitaa099a242017-01-11 11:17:29 -08001232 // Try to acquire a lock for 1s, fail gracefully
1233 const status_t err = mStateLock.timedLock(s2ns(1));
1234 const bool locked = (err == NO_ERROR);
1235 if (!locked) {
1236 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1237 return TIMED_OUT;
1238 }
1239
1240 outLayers->clear();
1241 mCurrentState.traverseInZOrder([&](Layer* layer) {
1242 outLayers->push_back(layer->getLayerDebugInfo());
1243 });
1244
1245 mStateLock.unlock();
1246 return NO_ERROR;
1247}
1248
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001249// ----------------------------------------------------------------------------
1250
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001251sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1252 ISurfaceComposer::VsyncSource vsyncSource) {
1253 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1254 return mSFEventThread->createEventConnection();
1255 } else {
1256 return mEventThread->createEventConnection();
1257 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001258}
1259
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001260// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001261
1262void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001263 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001264}
1265
1266void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001267 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001268}
1269
1270void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001271 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001272}
1273
1274void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001275 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001276 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001277}
1278
1279status_t SurfaceFlinger::postMessageAsync(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 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001282}
1283
1284status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001285 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001286 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001287 if (res == NO_ERROR) {
1288 msg->wait();
1289 }
1290 return res;
1291}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001292
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001293void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001294 do {
1295 waitForEvent();
1296 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001297}
1298
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001299void SurfaceFlinger::enableHardwareVsync() {
1300 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001301 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001302 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001303 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001304 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001305 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001306}
1307
Jesse Hall948fe0c2013-10-14 12:56:09 -07001308void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001309 Mutex::Autolock _l(mHWVsyncLock);
1310
Jesse Hall948fe0c2013-10-14 12:56:09 -07001311 if (makeAvailable) {
1312 mHWVsyncAvailable = true;
1313 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001314 // Hardware vsync is not currently available, so abort the resync
1315 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001316 return;
1317 }
1318
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001319 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1320 if (!getHwComposer().isConnected(displayId)) {
1321 return;
1322 }
1323
1324 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001325 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001326
Lloyd Pique41be5d22018-06-21 13:11:48 -07001327 mPrimaryDispSync->reset();
1328 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001329
1330 if (!mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001331 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001332 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001333 mPrimaryHWVsyncEnabled = true;
1334 }
1335}
1336
Jesse Hall948fe0c2013-10-14 12:56:09 -07001337void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001338 Mutex::Autolock _l(mHWVsyncLock);
1339 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001340 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001341 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001342 mPrimaryHWVsyncEnabled = false;
1343 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001344 if (makeUnavailable) {
1345 mHWVsyncAvailable = false;
1346 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001347}
1348
Tim Murray4a4e4a22016-04-19 16:29:23 +00001349void SurfaceFlinger::resyncWithRateLimit() {
1350 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001351
1352 // No explicit locking is needed here since EventThread holds a lock while calling this method
1353 static nsecs_t sLastResyncAttempted = 0;
1354 const nsecs_t now = systemTime();
1355 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001356 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001357 }
Dan Stoza57164302017-05-08 14:03:54 -07001358 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001359}
1360
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001361void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1362 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001363 ATRACE_NAME("SF onVsync");
1364
Steven Thomas3cfac282017-02-06 12:29:30 -08001365 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001366 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001367 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001368 return;
1369 }
1370
1371 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001372 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001373 return;
1374 }
1375
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001376 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1377 // For now, we don't do anything with external display vsyncs.
1378 return;
1379 }
1380
Jamie Gennisd1700752013-10-14 12:22:52 -07001381 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001382
Jamie Gennisd1700752013-10-14 12:22:52 -07001383 { // Scope for the lock
1384 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001385 if (mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001386 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001387 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001388 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001389
1390 if (needsHwVsync) {
1391 enableHardwareVsync();
1392 } else {
1393 disableHardwareVsync(false);
1394 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001395}
1396
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001397void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001398 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1399 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001400}
1401
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001402void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001403 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001404 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001405 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001406
Lloyd Piqueba04e622017-12-14 17:11:26 -08001407 // Ignore events that do not have the right sequenceId.
1408 if (sequenceId != getBE().mComposerSequenceId) {
1409 return;
1410 }
1411
Steven Thomasb02664d2017-07-26 18:48:28 -07001412 // Only lock if we're not on the main thread. This function is normally
1413 // called on a hwbinder thread, but for the primary display it's called on
1414 // the main thread with the state lock already held, so don't attempt to
1415 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001416 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001417
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001418 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001419
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001420 if (std::this_thread::get_id() == mMainThreadId) {
1421 // Process all pending hot plug events immediately if we are on the main thread.
1422 processDisplayHotplugEventsLocked();
1423 }
1424
Lloyd Piqueba04e622017-12-14 17:11:26 -08001425 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001426}
1427
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001428void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001429 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001430 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001431 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001432 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001433 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001434}
1435
Dan Stoza9e56aa02015-11-02 13:00:03 -08001436void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001437 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001438 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001439 getHwComposer().setVsyncEnabled(disp,
1440 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001441}
1442
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001443// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001444void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001445 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001446 // Clear the drawing state so that the logic inside of
1447 // handleTransactionLocked will fire. It will determine the delta between
1448 // mCurrentState and mDrawingState and re-apply all changes when we make the
1449 // transition.
1450 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001451 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001452 mDisplays.clear();
1453}
1454
Steven Thomas050b2c82017-03-06 11:45:16 -08001455void SurfaceFlinger::updateVrFlinger() {
1456 if (!mVrFlinger)
1457 return;
1458 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001459 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001460 return;
1461 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001462
David Sodman105b7dc2017-11-04 20:28:14 -07001463 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001464 ALOGE("Vr flinger is only supported for remote hardware composer"
1465 " service connections. Ignoring request to transition to vr"
1466 " flinger.");
1467 mVrFlingerRequestsDisplay = false;
1468 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001469 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001470
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001471 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001472
Steven Thomas0123ac62018-07-12 11:32:34 -07001473 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001474 LOG_ALWAYS_FATAL_IF(!display);
1475 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001476 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1477 // called below. Clear the reference now so we don't accidentally use it
1478 // later.
1479 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001480
Steven Thomasb02664d2017-07-26 18:48:28 -07001481 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001482 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001483 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001484
Steven Thomasb02664d2017-07-26 18:48:28 -07001485 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001486 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001487 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1488 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001489 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001490
David Sodman105b7dc2017-11-04 20:28:14 -07001491 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1492 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001493
1494 if (vrFlingerRequestsDisplay) {
1495 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001496 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001497
1498 mVisibleRegionsDirty = true;
1499 invalidateHwcGeometry();
1500
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001501 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001502 display = getDefaultDisplayDeviceLocked();
1503 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001504 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001505
Steven Thomasb02664d2017-07-26 18:48:28 -07001506 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001507 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001508 const nsecs_t period = activeConfig->getVsyncPeriod();
1509 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001510
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001511 // The present fences returned from vr_hwc are not an accurate
1512 // representation of vsync times.
Lloyd Pique41be5d22018-06-21 13:11:48 -07001513 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1514 !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001515
Steven Thomasb02664d2017-07-26 18:48:28 -07001516 // Use phase of 0 since phase is not known.
1517 // Use latency of 0, which will snap to the ideal latency.
1518 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001519
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001520 resyncToHardwareVsync(false);
1521
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001522 android_atomic_or(1, &mRepaintEverything);
1523 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001524}
1525
Mathias Agopian4fec8732012-06-29 14:12:52 -07001526void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001527 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001528 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001529 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001530 bool frameMissed = !mHadClientComposition &&
1531 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001532 (mPreviousPresentFence->getSignalTime() ==
1533 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001534 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001535 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001536 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001537 mTimeStats.incrementMissedFrames();
1538 if (mPropagateBackpressure) {
1539 signalLayerUpdate();
1540 break;
1541 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001542 }
Dan Stoza50182882016-07-08 12:02:20 -07001543
Steven Thomas050b2c82017-03-06 11:45:16 -08001544 // Now that we're going to make it to the handleMessageTransaction()
1545 // call below it's safe to call updateVrFlinger(), which will
1546 // potentially trigger a display handoff.
1547 updateVrFlinger();
1548
Dan Stoza6b9454d2014-11-07 16:00:59 -08001549 bool refreshNeeded = handleMessageTransaction();
1550 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001551 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001552 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001553 // Signal a refresh if a transaction modified the window state,
1554 // a new buffer was latched, or if HWC has requested a full
1555 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001556 signalRefresh();
1557 }
1558 break;
1559 }
1560 case MessageQueue::REFRESH: {
1561 handleMessageRefresh();
1562 break;
1563 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001564 }
1565}
1566
Dan Stoza6b9454d2014-11-07 16:00:59 -08001567bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001568 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001569 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001570 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001571 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001572 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001573 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001574}
1575
Dan Stoza6b9454d2014-11-07 16:00:59 -08001576bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001577 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001578 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001579}
1580
1581void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001582 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001583
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001584 mRefreshPending = false;
1585
Lloyd Pique074e8122018-07-26 12:57:23 -07001586 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1587
1588 preComposition(refreshStartTime);
1589 rebuildLayerStacks();
1590 setUpHWComposer();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001591 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001592 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001593 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001594 doComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001595 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001596
Dan Stozabfbffeb2016-07-21 14:49:33 -07001597 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001598 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001599 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001600 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001601 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001602 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001603
Dan Stoza9e56aa02015-11-02 13:00:03 -08001604 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001605}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001606
Mathias Agopiancd60f992012-08-16 16:28:27 -07001607void SurfaceFlinger::doDebugFlashRegions()
1608{
1609 // is debugging enabled
1610 if (CC_LIKELY(!mDebugRegion))
1611 return;
1612
1613 const bool repaintEverything = mRepaintEverything;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001614 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001615 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001616 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001617 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001618 if (!dirtyRegion.isEmpty()) {
1619 // redraw the whole screen
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001620 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001621
1622 // and draw the dirty region
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001623 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001624 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001625 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1626
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001627 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001628 }
1629 }
1630 }
1631
1632 postFramebuffer();
1633
1634 if (mDebugRegion > 1) {
1635 usleep(mDebugRegion * 1000);
1636 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001637
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001638 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001639 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001640 continue;
1641 }
1642
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001643 status_t result = display->prepareFrame(*getBE().mHwc);
1644 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001645 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001646 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001647}
1648
Adrian Roos1e1a1282017-11-01 19:05:31 +01001649void SurfaceFlinger::doTracing(const char* where) {
1650 ATRACE_CALL();
1651 ATRACE_NAME(where);
1652 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001653 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001654 }
1655}
1656
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001657void SurfaceFlinger::logLayerStats() {
1658 ATRACE_CALL();
1659 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001660 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001661 if (display->isPrimary()) {
1662 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001663 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001664 }
1665 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001666
1667 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001668 }
1669}
1670
Lloyd Pique074e8122018-07-26 12:57:23 -07001671void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001672{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001673 ATRACE_CALL();
1674 ALOGV("preComposition");
1675
Mathias Agopiancd60f992012-08-16 16:28:27 -07001676 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001677 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique074e8122018-07-26 12:57:23 -07001678 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001679 needExtraInvalidate = true;
1680 }
Robert Carr2047fae2016-11-28 14:09:09 -08001681 });
1682
Mathias Agopiancd60f992012-08-16 16:28:27 -07001683 if (needExtraInvalidate) {
1684 signalLayerUpdate();
1685 }
1686}
1687
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001688void SurfaceFlinger::updateCompositorTiming(
1689 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1690 std::shared_ptr<FenceTime>& presentFenceTime) {
1691 // Update queue of past composite+present times and determine the
1692 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001693 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001694 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001695 while (!getBE().mCompositePresentTimes.empty()) {
1696 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001697 // Cached values should have been updated before calling this method,
1698 // which helps avoid duplicate syscalls.
1699 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1700 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1701 break;
1702 }
1703 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001704 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001705 }
1706
1707 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001708 while (getBE().mCompositePresentTimes.size() > 16) {
1709 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001710 }
1711
Brian Andersond0010582017-03-07 13:20:31 -08001712 setCompositorTimingSnapped(
1713 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1714}
1715
1716void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1717 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001718 // Integer division and modulo round toward 0 not -inf, so we need to
1719 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001720 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001721 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1722 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1723
Brian Andersond0010582017-03-07 13:20:31 -08001724 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1725 if (idealLatency <= 0) {
1726 idealLatency = vsyncInterval;
1727 }
1728
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001729 // Snap the latency to a value that removes scheduling jitter from the
1730 // composition and present times, which often have >1ms of jitter.
1731 // Reducing jitter is important if an app attempts to extrapolate
1732 // something (such as user input) to an accurate diasplay time.
1733 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1734 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001735 nsecs_t bias = vsyncInterval / 2;
1736 int64_t extraVsyncs =
1737 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1738 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1739 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001740
David Sodman99974d22017-11-28 12:04:33 -08001741 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1742 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1743 getBE().mCompositorTiming.interval = vsyncInterval;
1744 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001745}
1746
Lloyd Pique074e8122018-07-26 12:57:23 -07001747void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001748{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001749 ATRACE_CALL();
1750 ALOGV("postComposition");
1751
Brian Anderson3546a3f2016-07-14 11:51:14 -07001752 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001753 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001754 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001755 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001756 }
1757
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001758 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001759 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001760
David Sodman73beded2017-11-15 11:56:06 -08001761 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001762 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001763 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001764 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001765 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001766 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001767 } else {
1768 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1769 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001770
David Sodman73beded2017-11-15 11:56:06 -08001771 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001772 mPreviousPresentFence =
1773 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1774 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001775 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001776
Lloyd Pique41be5d22018-06-21 13:11:48 -07001777 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1778 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001779
Lloyd Pique074e8122018-07-26 12:57:23 -07001780 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001781 // when we started doing work for this frame, but that should be okay
1782 // since updateCompositorTiming has snapping logic.
1783 updateCompositorTiming(
Lloyd Pique074e8122018-07-26 12:57:23 -07001784 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001785 CompositorTiming compositorTiming;
1786 {
David Sodman99974d22017-11-28 12:04:33 -08001787 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1788 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001789 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001790
Robert Carr2047fae2016-11-28 14:09:09 -08001791 mDrawingState.traverseInZOrder([&](Layer* layer) {
1792 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001793 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001794 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001795 recordBufferingStats(layer->getName().string(),
1796 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001797 }
Robert Carr2047fae2016-11-28 14:09:09 -08001798 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001799
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001800 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001801 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001802 enableHardwareVsync();
1803 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001804 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001805 }
1806 }
1807
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001808 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001809 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001810 enableHardwareVsync();
1811 }
1812 }
1813
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001814 if (mAnimCompositionPending) {
1815 mAnimCompositionPending = false;
1816
Brian Anderson4e606e32017-03-16 15:34:57 -07001817 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001818 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001819 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001820 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001821 // The HWC doesn't support present fences, so use the refresh
1822 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001823 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001824 mAnimFrameTracker.setActualPresentTime(presentTime);
1825 }
1826 mAnimFrameTracker.advanceFrame();
1827 }
Dan Stozab90cf072015-03-05 11:05:59 -08001828
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001829 mTimeStats.incrementTotalFrames();
1830 if (mHadClientComposition) {
1831 mTimeStats.incrementClientCompositionFrames();
1832 }
1833
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001834 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001835 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001836 return;
1837 }
1838
1839 nsecs_t currentTime = systemTime();
1840 if (mHasPoweredOff) {
1841 mHasPoweredOff = false;
1842 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001843 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001844 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001845 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1846 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001847 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001848 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001849 }
David Sodman4a36e932017-11-07 14:29:47 -08001850 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001851 }
David Sodman4a36e932017-11-07 14:29:47 -08001852 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001853
1854 {
1855 std::lock_guard lock(mTexturePoolMutex);
1856 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1857 if (refillCount > 0) {
1858 const size_t offset = mTexturePool.size();
1859 mTexturePool.resize(mTexturePoolSize);
1860 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1861 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1862 }
1863 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001864}
1865
1866void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001867 ATRACE_CALL();
1868 ALOGV("rebuildLayerStacks");
1869
Mathias Agopiancd60f992012-08-16 16:28:27 -07001870 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001871 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001872 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001873 mVisibleRegionsDirty = false;
1874 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001875
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001876 for (const auto& pair : mDisplays) {
1877 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001878 Region opaqueRegion;
1879 Region dirtyRegion;
1880 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001881 Vector<sp<Layer>> layersNeedingFences;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001882 const Transform& tr = display->getTransform();
1883 const Rect bounds = display->getBounds();
1884 if (display->isPoweredOn()) {
1885 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001886
Jeff Sharkey76488112017-02-27 14:15:18 -07001887 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001888 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001889 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001890 Region drawRegion(tr.transform(
1891 layer->visibleNonTransparentRegion));
1892 drawRegion.andSelf(bounds);
1893 if (!drawRegion.isEmpty()) {
1894 layersSortedByZ.add(layer);
1895 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001896 // Clear out the HWC layer if this layer was
1897 // previously visible, but no longer is
1898 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001899 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001900 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001901 // WM changes display->layerStack upon sleep/awake.
1902 // Here we make sure we delete the HWC layers even if
1903 // WM changed their layer stack.
1904 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001905 }
1906
1907 // If a layer is not going to get a release fence because
1908 // it is invisible, but it is also going to release its
1909 // old buffer, add it to the list of layers needing
1910 // fences.
1911 if (hwcLayerDestroyed) {
1912 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1913 mLayersWithQueuedFrames.cend(), layer);
1914 if (found != mLayersWithQueuedFrames.cend()) {
1915 layersNeedingFences.add(layer);
1916 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001917 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001918 });
1919 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001920 display->setVisibleLayersSortedByZ(layersSortedByZ);
1921 display->setLayersNeedingFences(layersNeedingFences);
1922 display->undefinedRegion.set(bounds);
1923 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1924 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001925 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001926 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001927}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001928
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001929// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001930// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001931// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001932// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001933// The returned HDR data space is one of
1934// - Dataspace::UNKNOWN
1935// - Dataspace::BT2020_HLG
1936// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001937Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1938 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001939 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001940 *outHdrDataSpace = Dataspace::UNKNOWN;
1941
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001942 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001943 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001944 case Dataspace::V0_SCRGB:
1945 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001946 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001947 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001948 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001949 case Dataspace::BT2020_PQ:
1950 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001951 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001952 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001953 case Dataspace::BT2020_HLG:
1954 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001955 // When there's mixed PQ content and HLG content, we set the HDR
1956 // data space to be BT2020_PQ and convert HLG to PQ.
1957 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1958 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001959 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001960 break;
1961 default:
1962 break;
1963 }
Romain Guy54f154a2017-10-24 21:40:32 +01001964 }
1965
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001966 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001967}
1968
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001969// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001970void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1971 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001972 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1973 *outMode = ColorMode::NATIVE;
1974 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001975 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001976 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001977 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001978
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001979 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001980 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001981
Peiyong Lindfde5112018-06-05 10:58:41 -07001982 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001983 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001984 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001985 if (isHdr) {
1986 bestDataSpace = hdrDataSpace;
1987 }
1988
Chia-I Wu0d711262018-05-21 15:19:35 -07001989 RenderIntent intent;
1990 switch (mDisplayColorSetting) {
1991 case DisplayColorSetting::MANAGED:
1992 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001993 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001994 break;
1995 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001996 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001997 break;
1998 default: // vendor display color setting
1999 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2000 break;
2001 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002002
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002003 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002004}
2005
Lloyd Pique074e8122018-07-26 12:57:23 -07002006void SurfaceFlinger::setUpHWComposer() {
2007 ATRACE_CALL();
2008 ALOGV("setUpHWComposer");
Lloyd Piqueb7d12302018-07-26 12:56:47 -07002009
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002010 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002011 bool dirty = !display->getDirtyRegion(mRepaintEverything).isEmpty();
2012 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2013 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
Jesse Hallb7a05492014-08-14 15:45:06 -07002014
2015 // If nothing has changed (!dirty), don't recompose.
2016 // If something changed, but we don't currently have any visible layers,
2017 // and didn't when we last did a composition, then skip it this time.
2018 // The second rule does two things:
2019 // - When all layers are removed from a display, we'll emit one black
2020 // frame, then nothing more until we get new layers.
2021 // - When a display is created with a private layer stack, we won't
2022 // emit any black frames until a layer is added to the layer stack.
2023 bool mustRecompose = dirty && !(empty && wasEmpty);
2024
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002025 ALOGV_IF(display->isVirtual(), "Display %d: %s composition (%sdirty %sempty %swasEmpty)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002026 display->getId(), mustRecompose ? "doing" : "skipping", dirty ? "+" : "-",
2027 empty ? "+" : "-", wasEmpty ? "+" : "-");
Jesse Hallb7a05492014-08-14 15:45:06 -07002028
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002029 display->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07002030
2031 if (mustRecompose) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002032 display->lastCompositionHadVisibleLayers = !empty;
Jesse Hallb7a05492014-08-14 15:45:06 -07002033 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07002034 }
2035
Lloyd Pique074e8122018-07-26 12:57:23 -07002036 // build the h/w work list
2037 if (CC_UNLIKELY(mGeometryInvalid)) {
2038 mGeometryInvalid = false;
2039 for (const auto& [token, display] : mDisplays) {
2040 const auto displayId = display->getId();
2041 if (displayId >= 0) {
2042 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
2043 for (size_t i = 0; i < currentLayers.size(); i++) {
2044 const auto& layer = currentLayers[i];
2045 if (!layer->hasHwcLayer(displayId)) {
2046 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
2047 layer->forceClientComposition(displayId);
2048 continue;
2049 }
2050 }
2051
2052 layer->setGeometry(display, i);
2053 if (mDebugDisableHWC || mDebugRegion) {
2054 layer->forceClientComposition(displayId);
2055 }
2056 }
2057 }
2058 }
2059 }
2060
2061 // Set the per-frame data
2062 for (const auto& [token, display] : mDisplays) {
2063 const auto displayId = display->getId();
2064 if (displayId < 0) {
2065 continue;
2066 }
2067
2068 if (mDrawingState.colorMatrixChanged) {
2069 display->setColorTransform(mDrawingState.colorMatrix);
2070 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
2071 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %d: %d",
2072 displayId, result);
2073 }
2074 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2075 if (layer->isHdrY410()) {
2076 layer->forceClientComposition(displayId);
2077 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2078 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
2079 !display->hasHDR10Support()) {
2080 layer->forceClientComposition(displayId);
2081 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2082 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
2083 !display->hasHLGSupport()) {
2084 layer->forceClientComposition(displayId);
2085 }
2086
2087 if (layer->getForceClientComposition(displayId)) {
2088 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2089 layer->setCompositionType(displayId, HWC2::Composition::Client);
2090 continue;
2091 }
2092
2093 layer->setPerFrameData(display);
2094 }
2095
2096 if (hasWideColorDisplay) {
2097 ColorMode colorMode;
2098 Dataspace dataSpace;
2099 RenderIntent renderIntent;
2100 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
2101 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
2102 }
2103 }
2104
2105 mDrawingState.colorMatrixChanged = false;
2106
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002107 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002108 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002109 continue;
2110 }
2111
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002112 status_t result = display->prepareFrame(*getBE().mHwc);
2113 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002114 display->getId(), result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002115 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002116}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002117
Mathias Agopiancd60f992012-08-16 16:28:27 -07002118void SurfaceFlinger::doComposition() {
2119 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002120 ALOGV("doComposition");
2121
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002122 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002123 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002124 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002125 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002126 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002127
2128 // repaint the framebuffer (if needed)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002129 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002130
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002131 display->dirtyRegion.clear();
2132 display->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002133 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002134 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002135 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002136}
2137
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002138void SurfaceFlinger::postFramebuffer()
2139{
Mathias Agopian841cde52012-03-01 15:44:37 -08002140 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002141 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002142
Mathias Agopiana44b0412011-10-16 18:46:35 -07002143 const nsecs_t now = systemTime();
2144 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002145
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002146 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002147 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002148 continue;
2149 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07002150 const auto displayId = display->getId();
2151 if (displayId >= 0) {
2152 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002153 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002154 display->onSwapBuffersCompleted();
2155 display->makeCurrent();
2156 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002157 sp<Fence> releaseFence = Fence::NO_FENCE;
2158
Chia-I Wu7b549592017-11-15 09:14:57 -08002159 // The layer buffer from the previous frame (if any) is released
2160 // by HWC only when the release fence from this frame (if any) is
2161 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002162 auto hwcLayer = layer->getHwcLayer(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002163 if (displayId >= 0) {
2164 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
2165 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002166
2167 // If the layer was client composited in the previous frame, we
2168 // need to merge with the previous client target acquire fence.
2169 // Since we do not track that, always merge with the current
2170 // client target acquire fence when it is available, even though
2171 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002172 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002173 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002174 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002175 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002176
David Sodmanb8af7922017-12-21 15:17:55 -08002177 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002178 }
Chia-I Wu83806892017-11-16 10:50:20 -08002179
2180 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002181 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002182 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002183 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002184 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002185 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002186 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002187 }
2188 }
2189
Dominik Laskowski7e045462018-05-30 13:02:02 -07002190 if (displayId >= 0) {
2191 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002192 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002193 }
2194
Mathias Agopiana44b0412011-10-16 18:46:35 -07002195 mLastSwapBufferTime = systemTime() - now;
2196 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002197
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002198 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002199 const auto display = getDefaultDisplayDeviceLocked();
2200 if (display && getHwComposer().isConnected(display->getId())) {
2201 const uint32_t flipCount = display->getPageFlipCount();
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002202 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2203 logFrameStats();
2204 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002205 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002206}
2207
Mathias Agopian87baae12012-07-31 12:38:26 -07002208void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002209{
Mathias Agopian841cde52012-03-01 15:44:37 -08002210 ATRACE_CALL();
2211
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002212 // here we keep a copy of the drawing state (that is the state that's
2213 // going to be overwritten by handleTransactionLocked()) outside of
2214 // mStateLock so that the side-effects of the State assignment
2215 // don't happen with mStateLock held (which can cause deadlocks).
2216 State drawingState(mDrawingState);
2217
Mathias Agopianca4d3602011-05-19 15:38:14 -07002218 Mutex::Autolock _l(mStateLock);
2219 const nsecs_t now = systemTime();
2220 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002221
Mathias Agopianca4d3602011-05-19 15:38:14 -07002222 // Here we're guaranteed that some transaction flags are set
2223 // so we can call handleTransactionLocked() unconditionally.
2224 // We call getTransactionFlags(), which will also clear the flags,
2225 // with mStateLock held to guarantee that mCurrentState won't change
2226 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002227
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002228 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002229 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002230 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002231
Mathias Agopianca4d3602011-05-19 15:38:14 -07002232 mLastTransactionTime = systemTime() - now;
2233 mDebugInTransaction = 0;
2234 invalidateHwcGeometry();
2235 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002236}
2237
Dominik Laskowski7e045462018-05-30 13:02:02 -07002238DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002239 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002240 // Figure out whether the event is for the primary display or an
2241 // external display by matching the Hwc display id against one for a
2242 // connected display. If we did not find a match, we then check what
2243 // displays are not already connected to determine the type. If we don't
2244 // have a connected primary display, we assume the new display is meant to
2245 // be the primary display, and then if we don't have an external display,
2246 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002247 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2248 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002249 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002250 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002251 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002252 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002253 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002254 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002255 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002256 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002257 return DisplayDevice::DISPLAY_EXTERNAL;
2258 }
2259
2260 return DisplayDevice::DISPLAY_ID_INVALID;
2261}
2262
Lloyd Piqueba04e622017-12-14 17:11:26 -08002263void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2264 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002265 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002266 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002267 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002268 continue;
2269 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002270
2271 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2272 ALOGE("External displays are not supported by the vr hardware composer.");
2273 continue;
2274 }
2275
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002276 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002277 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002278 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002279 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002280 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002281
2282 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002283 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002284 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002285 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002286 DisplayDeviceState info;
2287 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002288 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2289 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002290 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002291 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002292 mInterceptor->saveDisplayCreation(info);
2293 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002294 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002295 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002296
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002297 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002298 if (idx >= 0) {
2299 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002300 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002301 mCurrentState.displays.removeItemsAt(idx);
2302 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002303 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002304 }
2305
2306 processDisplayChangesLocked();
2307 }
2308
2309 mPendingHotplugEvents.clear();
2310}
2311
Lloyd Pique99d3da52018-01-22 17:48:03 -08002312sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002313 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002314 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002315 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002316 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002317 HdrCapabilities hdrCapabilities;
2318 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002319
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002320 if (hasWideColorDisplay && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002321 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002322 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002323 if (isWideColorMode(colorMode)) {
2324 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002325 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002326
Dominik Laskowski7e045462018-05-30 13:02:02 -07002327 std::vector<RenderIntent> renderIntents =
2328 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002329 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002330 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002331
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002332 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2333 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2334 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002335
2336 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2337 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2338
2339 /*
2340 * Create our display's surface
2341 */
2342 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2343 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002344 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002345 renderSurface->setNativeWindow(nativeWindow.get());
2346 const int displayWidth = renderSurface->queryWidth();
2347 const int displayHeight = renderSurface->queryHeight();
2348
2349 // Make sure that composition can never be stalled by a virtual display
2350 // consumer that isn't processing buffers fast enough. We have to do this
2351 // in two places:
2352 // * Here, in case the display is composed entirely by HWC.
2353 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2354 // window's swap interval in eglMakeCurrent, so they'll override the
2355 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002356 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002357 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2358 }
2359
2360 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002361 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002362
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002363 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002364 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2365 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2366 displayHeight, hasWideColorGamut, hdrCapabilities,
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002367 supportedPerFrameMetadata, hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002368
2369 if (maxFrameBufferAcquiredBuffers >= 3) {
2370 nativeWindowSurface->preallocateBuffers();
2371 }
2372
2373 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002374 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2375 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002376 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002377 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002378 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002379 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002380 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002381 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002382 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002383 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002384 display->setLayerStack(state.layerStack);
2385 display->setProjection(state.orientation, state.viewport, state.frame);
2386 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002387
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002388 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002389}
2390
Lloyd Pique347200f2017-12-14 17:00:15 -08002391void SurfaceFlinger::processDisplayChangesLocked() {
2392 // here we take advantage of Vector's copy-on-write semantics to
2393 // improve performance by skipping the transaction entirely when
2394 // know that the lists are identical
2395 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2396 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2397 if (!curr.isIdenticalTo(draw)) {
2398 mVisibleRegionsDirty = true;
2399 const size_t cc = curr.size();
2400 size_t dc = draw.size();
2401
2402 // find the displays that were removed
2403 // (ie: in drawing state but not in current state)
2404 // also handle displays that changed
2405 // (ie: displays that are in both lists)
2406 for (size_t i = 0; i < dc;) {
2407 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2408 if (j < 0) {
2409 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002410 // Call makeCurrent() on the primary display so we can
2411 // be sure that nothing associated with this display
2412 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002413 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2414 defaultDisplay->makeCurrent();
2415 }
2416 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2417 display->disconnect(getHwComposer());
2418 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002419 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2420 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2421 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2422 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2423 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002424 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002425 } else {
2426 // this display is in both lists. see if something changed.
2427 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002428 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002429 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2430 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2431 if (state_binder != draw_binder) {
2432 // changing the surface is like destroying and
2433 // recreating the DisplayDevice, so we just remove it
2434 // from the drawing state, so that it get re-added
2435 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002436 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2437 display->disconnect(getHwComposer());
2438 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002439 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002440 mDrawingState.displays.removeItemsAt(i);
2441 dc--;
2442 // at this point we must loop to the next item
2443 continue;
2444 }
2445
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002446 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002447 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002448 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002449 }
2450 if ((state.orientation != draw[i].orientation) ||
2451 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002452 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002453 }
2454 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002455 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002456 }
2457 }
2458 }
2459 ++i;
2460 }
2461
2462 // find displays that were added
2463 // (ie: in current state but not in drawing state)
2464 for (size_t i = 0; i < cc; i++) {
2465 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2466 const DisplayDeviceState& state(curr[i]);
2467
2468 sp<DisplaySurface> dispSurface;
2469 sp<IGraphicBufferProducer> producer;
2470 sp<IGraphicBufferProducer> bqProducer;
2471 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002472 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002473
Dominik Laskowski7e045462018-05-30 13:02:02 -07002474 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002475 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002476 // Virtual displays without a surface are dormant:
2477 // they have external state (layer stack, projection,
2478 // etc.) but no internal state (i.e. a DisplayDevice).
2479 if (state.surface != nullptr) {
2480 // Allow VR composer to use virtual displays.
2481 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2482 int width = 0;
2483 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2484 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2485 int height = 0;
2486 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2487 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2488 int intFormat = 0;
2489 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2490 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002491 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002492
Dominik Laskowski7e045462018-05-30 13:02:02 -07002493 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2494 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002495 }
2496
2497 // TODO: Plumb requested format back up to consumer
2498
2499 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002500 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002501 bqProducer, bqConsumer,
2502 state.displayName);
2503
2504 dispSurface = vds;
2505 producer = vds;
2506 }
2507 } else {
2508 ALOGE_IF(state.surface != nullptr,
2509 "adding a supported display, but rendering "
2510 "surface is provided (%p), ignoring it",
2511 state.surface.get());
2512
Dominik Laskowski7e045462018-05-30 13:02:02 -07002513 displayId = state.type;
2514 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002515 producer = bqProducer;
2516 }
2517
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002518 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002519 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002520 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002521 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002522 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002523 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002524 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2525 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2526 true);
2527 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2528 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2529 true);
2530 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002531 }
2532 }
2533 }
2534 }
2535 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002536
2537 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002538}
2539
Mathias Agopian87baae12012-07-31 12:38:26 -07002540void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002541{
Dan Stoza7dde5992015-05-22 09:51:44 -07002542 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002543 mCurrentState.traverseInZOrder([](Layer* layer) {
2544 layer->notifyAvailableFrames();
2545 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002546
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002547 /*
2548 * Traversal of the children
2549 * (perform the transaction for each of them if needed)
2550 */
2551
Mathias Agopian3559b072012-08-15 13:46:03 -07002552 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002553 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002554 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002555 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002556
2557 const uint32_t flags = layer->doTransaction(0);
2558 if (flags & Layer::eVisibleRegion)
2559 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002560 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002561 }
2562
2563 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002564 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002565 */
2566
Mathias Agopiane57f2922012-08-09 16:29:12 -07002567 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002568 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002569 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002570 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002571
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002572 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002573 // The transform hint might have changed for some layers
2574 // (either because a display has changed, or because a layer
2575 // as changed).
2576 //
2577 // Walk through all the layers in currentLayers,
2578 // and update their transform hint.
2579 //
2580 // If a layer is visible only on a single display, then that
2581 // display is used to calculate the hint, otherwise we use the
2582 // default display.
2583 //
2584 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2585 // the hint is set before we acquire a buffer from the surface texture.
2586 //
2587 // NOTE: layer transactions have taken place already, so we use their
2588 // drawing state. However, SurfaceFlinger's own transaction has not
2589 // happened yet, so we must use the current state layer list
2590 // (soon to become the drawing state list).
2591 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002592 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002593 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002594 bool first = true;
2595 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002596 // NOTE: we rely on the fact that layers are sorted by
2597 // layerStack first (so we don't have to traverse the list
2598 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002599 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002600 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002601 currentlayerStack = layerStack;
2602 // figure out if this layerstack is mirrored
2603 // (more than one display) if so, pick the default display,
2604 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002605 hintDisplay = nullptr;
2606 for (const auto& [token, display] : mDisplays) {
2607 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2608 if (hintDisplay) {
2609 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002610 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002611 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002612 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002613 }
2614 }
2615 }
2616 }
Chet Haase91d25932013-04-11 15:24:55 -07002617
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002618 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002619 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2620 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002621
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002622 // could be null when this layer is using a layerStack
2623 // that is not visible on any display. Also can occur at
2624 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002625 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002626 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002627
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002628 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002629 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002630 if (hintDisplay) {
2631 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002632 }
Robert Carr2047fae2016-11-28 14:09:09 -08002633
2634 first = false;
2635 });
Mathias Agopian84300952012-11-21 16:02:13 -08002636 }
2637
2638
Mathias Agopian3559b072012-08-15 13:46:03 -07002639 /*
2640 * Perform our own transaction if needed
2641 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002642
2643 if (mLayersAdded) {
2644 mLayersAdded = false;
2645 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002646 mVisibleRegionsDirty = true;
2647 }
2648
2649 // some layers might have been removed, so
2650 // we need to update the regions they're exposing.
2651 if (mLayersRemoved) {
2652 mLayersRemoved = false;
2653 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002654 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002655 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002656 // this layer is not visible anymore
2657 // TODO: we could traverse the tree from front to back and
2658 // compute the actual visible region
2659 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002660 Region visibleReg;
2661 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002662 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002663 }
Robert Carr2047fae2016-11-28 14:09:09 -08002664 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002665 }
2666
2667 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002668
2669 updateCursorAsync();
2670}
2671
2672void SurfaceFlinger::updateCursorAsync()
2673{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002674 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002675 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002676 continue;
2677 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002678
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002679 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2680 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002681 }
2682 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002683}
2684
2685void SurfaceFlinger::commitTransaction()
2686{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002687 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002688 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002689 for (const auto& l : mLayersPendingRemoval) {
2690 recordBufferingStats(l->getName().string(),
2691 l->getOccupancyHistory(true));
2692 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002693 }
2694 mLayersPendingRemoval.clear();
2695 }
2696
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002697 // If this transaction is part of a window animation then the next frame
2698 // we composite should be considered an animation as well.
2699 mAnimCompositionPending = mAnimTransactionPending;
2700
Mathias Agopian4fec8732012-06-29 14:12:52 -07002701 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002702 // clear the "changed" flags in current state
2703 mCurrentState.colorMatrixChanged = false;
2704
Robert Carr1f0a16a2016-10-24 16:27:39 -07002705 mDrawingState.traverseInZOrder([](Layer* layer) {
2706 layer->commitChildList();
2707 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002708 mTransactionPending = false;
2709 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002710 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002711}
2712
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002713void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2714 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002715 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002716 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002717
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002718 Region aboveOpaqueLayers;
2719 Region aboveCoveredLayers;
2720 Region dirty;
2721
Mathias Agopian87baae12012-07-31 12:38:26 -07002722 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002723
Robert Carr2047fae2016-11-28 14:09:09 -08002724 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002725 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002726 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002727
Jesse Hall01e29052013-02-19 16:13:35 -08002728 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002729 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002730 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002731 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002732
Mathias Agopianab028732010-03-16 16:41:46 -07002733 /*
2734 * opaqueRegion: area of a surface that is fully opaque.
2735 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002736 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002737
2738 /*
2739 * visibleRegion: area of a surface that is visible on screen
2740 * and not fully transparent. This is essentially the layer's
2741 * footprint minus the opaque regions above it.
2742 * Areas covered by a translucent surface are considered visible.
2743 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002744 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002745
2746 /*
2747 * coveredRegion: area of a surface that is covered by all
2748 * visible regions above it (which includes the translucent areas).
2749 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002750 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002751
Jesse Halla8026d22012-09-25 13:25:04 -07002752 /*
2753 * transparentRegion: area of a surface that is hinted to be completely
2754 * transparent. This is only used to tell when the layer has no visible
2755 * non-transparent regions and can be removed from the layer list. It
2756 * does not affect the visibleRegion of this layer or any layers
2757 * beneath it. The hint may not be correct if apps don't respect the
2758 * SurfaceView restrictions (which, sadly, some don't).
2759 */
2760 Region transparentRegion;
2761
Mathias Agopianab028732010-03-16 16:41:46 -07002762
2763 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002764 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002765 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002766 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002767 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002768 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002769 if (!visibleRegion.isEmpty()) {
2770 // Remove the transparent area from the visible region
2771 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002772 if (tr.preserveRects()) {
2773 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002774 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002775 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002776 // transformation too complex, can't do the
2777 // transparent region optimization.
2778 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002779 }
Mathias Agopianab028732010-03-16 16:41:46 -07002780 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002781
Mathias Agopianab028732010-03-16 16:41:46 -07002782 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002783 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002784 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002785 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2786 // the opaque region is the layer's footprint
2787 opaqueRegion = visibleRegion;
2788 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002789 }
2790 }
2791
Robert Carre5f4f692018-01-12 13:12:28 -08002792 if (visibleRegion.isEmpty()) {
2793 layer->clearVisibilityRegions();
2794 return;
2795 }
2796
Mathias Agopianab028732010-03-16 16:41:46 -07002797 // Clip the covered region to the visible region
2798 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2799
2800 // Update aboveCoveredLayers for next (lower) layer
2801 aboveCoveredLayers.orSelf(visibleRegion);
2802
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002803 // subtract the opaque region covered by the layers above us
2804 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002805
2806 // compute this layer's dirty region
2807 if (layer->contentDirty) {
2808 // we need to invalidate the whole region
2809 dirty = visibleRegion;
2810 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002811 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002812 layer->contentDirty = false;
2813 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002814 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002815 * the exposed region consists of two components:
2816 * 1) what's VISIBLE now and was COVERED before
2817 * 2) what's EXPOSED now less what was EXPOSED before
2818 *
2819 * note that (1) is conservative, we start with the whole
2820 * visible region but only keep what used to be covered by
2821 * something -- which mean it may have been exposed.
2822 *
2823 * (2) handles areas that were not covered by anything but got
2824 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002825 */
Mathias Agopianab028732010-03-16 16:41:46 -07002826 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002827 const Region oldVisibleRegion = layer->visibleRegion;
2828 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002829 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2830 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002831 }
2832 dirty.subtractSelf(aboveOpaqueLayers);
2833
2834 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002835 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002836
Mathias Agopianab028732010-03-16 16:41:46 -07002837 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002838 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002839
Jesse Halla8026d22012-09-25 13:25:04 -07002840 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002841 layer->setVisibleRegion(visibleRegion);
2842 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002843 layer->setVisibleNonTransparentRegion(
2844 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002845 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002846
Mathias Agopian87baae12012-07-31 12:38:26 -07002847 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002848}
2849
Chia-I Wuab0c3192017-08-01 11:29:00 -07002850void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002851 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002852 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2853 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002854 }
2855 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002856}
2857
Dan Stoza6b9454d2014-11-07 16:00:59 -08002858bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002859{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002860 ALOGV("handlePageFlip");
2861
Brian Andersond6927fb2016-07-23 23:37:30 -07002862 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002863
Mathias Agopian4fec8732012-06-29 14:12:52 -07002864 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002865 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002866 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002867
2868 // Store the set of layers that need updates. This set must not change as
2869 // buffers are being latched, as this could result in a deadlock.
2870 // Example: Two producers share the same command stream and:
2871 // 1.) Layer 0 is latched
2872 // 2.) Layer 0 gets a new frame
2873 // 2.) Layer 1 gets a new frame
2874 // 3.) Layer 1 is latched.
2875 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2876 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002877 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002878 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002879 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07002880 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002881 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002882 } else {
2883 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002884 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002885 } else {
2886 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002887 }
Robert Carr2047fae2016-11-28 14:09:09 -08002888 });
2889
Dan Stoza9e56aa02015-11-02 13:00:03 -08002890 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002891 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002892 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002893 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002894 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002895 newDataLatched = true;
2896 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002897 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002898
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002899 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002900
2901 // If we will need to wake up at some time in the future to deal with a
2902 // queued frame that shouldn't be displayed during this vsync period, wake
2903 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002904 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002905 signalLayerUpdate();
2906 }
2907
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002908 // enter boot animation on first buffer latch
2909 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2910 ALOGI("Enter boot animation");
2911 mBootStage = BootStage::BOOTANIMATION;
2912 }
2913
Dan Stoza6b9454d2014-11-07 16:00:59 -08002914 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002915 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002916}
2917
Mathias Agopianad456f92011-01-13 17:53:01 -08002918void SurfaceFlinger::invalidateHwcGeometry()
2919{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002920 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002921}
2922
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002923void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2924 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002925 // We only need to actually compose the display if:
2926 // 1) It is being handled by hardware composer, which may need this to
2927 // keep its virtual display state machine in sync, or
2928 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002929 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002930 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002931 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002932 return;
2933 }
2934
Dan Stoza9e56aa02015-11-02 13:00:03 -08002935 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002936 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002937
2938 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002939 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002940}
2941
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002942bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002943 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002944
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002945 const Region bounds(display->bounds());
2946 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002947 const auto displayId = display->getId();
2948 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002949 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002950
Chia-I Wu8e50e692018-05-04 10:12:37 -07002951 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002952 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002953
Dan Stoza9e56aa02015-11-02 13:00:03 -08002954 if (hasClientComposition) {
2955 ALOGV("hasClientComposition");
2956
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002957 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002958 if (display->hasWideColorGamut()) {
2959 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002960 }
2961 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002962 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002963 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002964
Dominik Laskowski7e045462018-05-30 13:02:02 -07002965 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002966 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2967 HWC2::Capability::SkipClientColorTransform);
2968
Chia-I Wud49d6692018-06-27 07:17:41 +08002969 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002970 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2971 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08002972 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002973 }
2974
Chia-I Wud49d6692018-06-27 07:17:41 +08002975 // The current enhanced saturation matrix is designed to enhance Display P3,
2976 // thus we only apply this matrix when the render intent is not colorimetric
2977 // and the output color space is Display P3.
2978 needsEnhancedColorMatrix =
2979 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2980 outputDataspace == Dataspace::DISPLAY_P3);
2981 if (needsEnhancedColorMatrix) {
2982 colorMatrix *= mEnhancedSaturationMatrix;
2983 }
2984
2985 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002986
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002987 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002988 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002989 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002990 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002991
2992 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002993 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
2994 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
2995 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07002996 }
2997 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002998 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002999
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003000 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003001 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003002 // when using overlays, we assume a fully transparent framebuffer
3003 // NOTE: we could reduce how much we need to clear, for instance
3004 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003005 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003006 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003007 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003008 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003009 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003010 // we're left with the letterbox region
3011 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003012 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003013
3014 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003015 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003016
Mathias Agopianb9494d52012-04-18 02:28:45 -07003017 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003018 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003019 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003020 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003021 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003022 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003023
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003024 if (!display->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07003025 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07003026 // scissor on the main display. It should never be needed
3027 // anyways (though in theory it could since the API allows it).
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003028 const Rect& bounds = display->getBounds();
3029 const Rect& scissor = display->getScissor();
Mathias Agopianf45c5102012-10-24 16:29:17 -07003030 if (scissor != bounds) {
3031 // scissor doesn't match the screen's dimensions, so we
3032 // need to clear everything outside of it and enable
3033 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003034
Mathias Agopianf45c5102012-10-24 16:29:17 -07003035 // enable scissor for this frame
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003036 const uint32_t height = display->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08003037 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07003038 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003039 }
3040 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003041 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003042
Mathias Agopian85d751c2012-08-29 16:59:24 -07003043 /*
3044 * and then, render the layers targeted at the framebuffer
3045 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003046
Dan Stoza9e56aa02015-11-02 13:00:03 -08003047 ALOGV("Rendering client layers");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003048 const Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003049 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003050 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003051 const Region clip(bounds.intersect(
3052 displayTransform.transform(layer->visibleRegion)));
3053 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07003054 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003055 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003056 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003057 case HWC2::Composition::Cursor:
3058 case HWC2::Composition::Device:
3059 case HWC2::Composition::Sideband:
3060 case HWC2::Composition::SolidColor: {
3061 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07003062 if (layer->getClearClientTarget(displayId) && !firstLayer &&
Rajavenu Kyatham2eae6d32018-04-10 12:34:05 +05303063 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3064 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003065 // never clear the very first layer since we're
3066 // guaranteed the FB is already cleared
3067 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003068 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003069 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003070 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003071 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003072 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003073 break;
3074 }
3075 default:
3076 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003077 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003078 } else {
3079 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003080 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003081 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003082 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003083
Chia-I Wud49d6692018-06-27 07:17:41 +08003084 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003085 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003086 }
3087
Mathias Agopianf45c5102012-10-24 16:29:17 -07003088 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003089 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003090 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003091}
3092
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003093void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
3094 const Region& region) const {
3095 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003096 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003097 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003098}
3099
Dan Stoza7d89d062015-04-30 13:29:25 -07003100status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003101 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003102 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003103 const sp<Layer>& lbc,
3104 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003105{
Dan Stoza7d89d062015-04-30 13:29:25 -07003106 // add this layer to the current state list
3107 {
3108 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003109 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003110 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3111 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003112 return NO_MEMORY;
3113 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003114 if (parent == nullptr) {
3115 mCurrentState.layersSortedByZ.add(lbc);
3116 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003117 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003118 ALOGE("addClientLayer called with a removed parent");
3119 return NAME_NOT_FOUND;
3120 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003121 parent->addChild(lbc);
3122 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003123
Yiwei Zhang243b3782018-05-15 17:40:04 -07003124 if (gbc != nullptr) {
3125 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3126 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3127 mMaxGraphicBufferProducerListSize,
3128 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3129 mGraphicBufferProducerList.size(),
3130 mMaxGraphicBufferProducerListSize, mNumLayers);
3131 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003132 mLayersAdded = true;
3133 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003134 }
3135
Mathias Agopian96f08192010-06-02 23:28:45 -07003136 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003137 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003138
Dan Stoza7d89d062015-04-30 13:29:25 -07003139 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003140}
3141
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003142status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003143 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003144 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3145}
Robert Carr7f9b8992017-03-10 11:08:39 -08003146
chaviwca27f252018-02-06 16:46:39 -08003147status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3148 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003149 if (layer->isPendingRemoval()) {
3150 return NO_ERROR;
3151 }
3152
Robert Carr1f0a16a2016-10-24 16:27:39 -07003153 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003154 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003155 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003156 if (topLevelOnly) {
3157 return NO_ERROR;
3158 }
3159
Chia-I Wu98f1c102017-05-30 14:54:08 -07003160 sp<Layer> ancestor = p;
3161 while (ancestor->getParent() != nullptr) {
3162 ancestor = ancestor->getParent();
3163 }
3164 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3165 ALOGE("removeLayer called with a layer whose parent has been removed");
3166 return NAME_NOT_FOUND;
3167 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003168
3169 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003170 } else {
3171 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003172 }
3173
Robert Carr136e2f62017-02-08 17:54:29 -08003174 // As a matter of normal operation, the LayerCleaner will produce a second
3175 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3176 // so we will succeed in promoting it, but it's already been removed
3177 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3178 // otherwise something has gone wrong and we are leaking the layer.
3179 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003180 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3181 layer->getName().string(),
3182 (p != nullptr) ? p->getName().string() : "no-parent");
3183 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003184 } else if (index < 0) {
3185 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003186 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003187
Chia-I Wuc6657022017-08-15 11:18:17 -07003188 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003189 mLayersPendingRemoval.add(layer);
3190 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003191 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003192 setTransactionFlags(eTransactionNeeded);
3193 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003194}
3195
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003196uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003197 return android_atomic_release_load(&mTransactionFlags);
3198}
3199
Mathias Agopian3f844832013-08-07 21:24:32 -07003200uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003201 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3202}
3203
Mathias Agopian3f844832013-08-07 21:24:32 -07003204uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003205 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3206}
3207
3208uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3209 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003210 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003211 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003212 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003213 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003214 }
3215 return old;
3216}
3217
chaviwca27f252018-02-06 16:46:39 -08003218bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3219 for (const ComposerState& state : states) {
3220 // Here we need to check that the interface we're given is indeed
3221 // one of our own. A malicious client could give us a nullptr
3222 // IInterface, or one of its own or even one of our own but a
3223 // different type. All these situations would cause us to crash.
3224 if (state.client == nullptr) {
3225 return true;
3226 }
3227
3228 sp<IBinder> binder = IInterface::asBinder(state.client);
3229 if (binder == nullptr) {
3230 return true;
3231 }
3232
3233 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3234 return true;
3235 }
3236 }
3237 return false;
3238}
3239
Mathias Agopian8b33f032012-07-24 20:43:54 -07003240void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003241 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003242 const Vector<DisplayState>& displays,
3243 uint32_t flags)
3244{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003245 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003246 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003247 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003248
chaviwca27f252018-02-06 16:46:39 -08003249 if (containsAnyInvalidClientState(states)) {
3250 return;
3251 }
3252
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003253 if (flags & eAnimation) {
3254 // For window updates that are part of an animation we must wait for
3255 // previous animation "frames" to be handled.
3256 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003257 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003258 if (CC_UNLIKELY(err != NO_ERROR)) {
3259 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003260 // caller after a few seconds.
3261 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3262 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003263 mAnimTransactionPending = false;
3264 break;
3265 }
3266 }
3267 }
3268
chaviwca27f252018-02-06 16:46:39 -08003269 for (const DisplayState& display : displays) {
3270 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003271 }
3272
chaviwca27f252018-02-06 16:46:39 -08003273 for (const ComposerState& state : states) {
3274 transactionFlags |= setClientStateLocked(state);
3275 }
3276
3277 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3278 // as destroyed should only occur after setting all other states. This is to allow for a
3279 // child re-parent to happen before marking its original parent as destroyed (which would
3280 // then mark the child as destroyed).
3281 for (const ComposerState& state : states) {
3282 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003283 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003284
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003285 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3286 // anyway. This can be used as a flush mechanism for previous async transactions.
3287 // Empty animation transaction can be used to simulate back-pressure, so also force a
3288 // transaction for empty animation transactions.
3289 if (transactionFlags == 0 &&
3290 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003291 transactionFlags = eTransactionNeeded;
3292 }
3293
Mathias Agopian386aa982011-11-07 21:58:03 -08003294 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003295 if (mInterceptor->isEnabled()) {
3296 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003297 }
Irvel468051e2016-06-13 16:44:44 -07003298
Mathias Agopian386aa982011-11-07 21:58:03 -08003299 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003300 const auto start = (flags & eEarlyWakeup)
3301 ? VSyncModulator::TransactionStart::EARLY
3302 : VSyncModulator::TransactionStart::NORMAL;
3303 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003304
3305 // if this is a synchronous transaction, wait for it to take effect
3306 // before returning.
3307 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003308 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003309 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003310 if (flags & eAnimation) {
3311 mAnimTransactionPending = true;
3312 }
3313 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003314 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3315 if (CC_UNLIKELY(err != NO_ERROR)) {
3316 // just in case something goes wrong in SF, return to the
3317 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003318 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3319 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003320 break;
3321 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003322 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003323 }
3324}
3325
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003326uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3327 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3328 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003329
Mathias Agopiane57f2922012-08-09 16:29:12 -07003330 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003331 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3332
3333 const uint32_t what = s.what;
3334 if (what & DisplayState::eSurfaceChanged) {
3335 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3336 state.surface = s.surface;
3337 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003338 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003339 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003340 if (what & DisplayState::eLayerStackChanged) {
3341 if (state.layerStack != s.layerStack) {
3342 state.layerStack = s.layerStack;
3343 flags |= eDisplayTransactionNeeded;
3344 }
3345 }
3346 if (what & DisplayState::eDisplayProjectionChanged) {
3347 if (state.orientation != s.orientation) {
3348 state.orientation = s.orientation;
3349 flags |= eDisplayTransactionNeeded;
3350 }
3351 if (state.frame != s.frame) {
3352 state.frame = s.frame;
3353 flags |= eDisplayTransactionNeeded;
3354 }
3355 if (state.viewport != s.viewport) {
3356 state.viewport = s.viewport;
3357 flags |= eDisplayTransactionNeeded;
3358 }
3359 }
3360 if (what & DisplayState::eDisplaySizeChanged) {
3361 if (state.width != s.width) {
3362 state.width = s.width;
3363 flags |= eDisplayTransactionNeeded;
3364 }
3365 if (state.height != s.height) {
3366 state.height = s.height;
3367 flags |= eDisplayTransactionNeeded;
3368 }
3369 }
3370
Mathias Agopiane57f2922012-08-09 16:29:12 -07003371 return flags;
3372}
3373
Robert Carrd4ae7f32018-06-07 16:10:57 -07003374bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3375 IPCThreadState* ipc = IPCThreadState::self();
3376 const int pid = ipc->getCallingPid();
3377 const int uid = ipc->getCallingUid();
Dan Stozae3344402018-08-20 19:53:42 +00003378
Robert Carrd4ae7f32018-06-07 16:10:57 -07003379 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Dan Stozae3344402018-08-20 19:53:42 +00003380 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003381 return false;
3382 }
3383 return true;
3384}
3385
chaviwca27f252018-02-06 16:46:39 -08003386uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3387 const layer_state_t& s = composerState.state;
3388 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3389
Mathias Agopian13127d82013-03-05 17:47:11 -08003390 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003391 if (layer == nullptr) {
3392 return 0;
3393 }
3394
3395 if (layer->isPendingRemoval()) {
3396 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3397 return 0;
3398 }
3399
3400 uint32_t flags = 0;
3401
3402 const uint32_t what = s.what;
3403 bool geometryAppliesWithResize =
3404 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003405
3406 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3407 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003408 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003409 layer->pushPendingState();
3410 }
3411
chaviw8b3871a2017-11-01 17:41:01 -07003412 if (what & layer_state_t::ePositionChanged) {
3413 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3414 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003415 }
chaviw8b3871a2017-11-01 17:41:01 -07003416 }
3417 if (what & layer_state_t::eLayerChanged) {
3418 // NOTE: index needs to be calculated before we update the state
3419 const auto& p = layer->getParent();
3420 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003421 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003422 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003423 mCurrentState.layersSortedByZ.removeAt(idx);
3424 mCurrentState.layersSortedByZ.add(layer);
3425 // we need traversal (state changed)
3426 // AND transaction (list changed)
3427 flags |= eTransactionNeeded|eTraversalNeeded;
3428 }
chaviw8b3871a2017-11-01 17:41:01 -07003429 } else {
3430 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003431 flags |= eTransactionNeeded|eTraversalNeeded;
3432 }
3433 }
chaviw8b3871a2017-11-01 17:41:01 -07003434 }
3435 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003436 // NOTE: index needs to be calculated before we update the state
3437 const auto& p = layer->getParent();
3438 if (p == nullptr) {
3439 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3440 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3441 mCurrentState.layersSortedByZ.removeAt(idx);
3442 mCurrentState.layersSortedByZ.add(layer);
3443 // we need traversal (state changed)
3444 // AND transaction (list changed)
3445 flags |= eTransactionNeeded|eTraversalNeeded;
3446 }
3447 } else {
3448 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3449 flags |= eTransactionNeeded|eTraversalNeeded;
3450 }
chaviw8b3871a2017-11-01 17:41:01 -07003451 }
3452 }
3453 if (what & layer_state_t::eSizeChanged) {
3454 if (layer->setSize(s.w, s.h)) {
3455 flags |= eTraversalNeeded;
3456 }
3457 }
3458 if (what & layer_state_t::eAlphaChanged) {
3459 if (layer->setAlpha(s.alpha))
3460 flags |= eTraversalNeeded;
3461 }
3462 if (what & layer_state_t::eColorChanged) {
3463 if (layer->setColor(s.color))
3464 flags |= eTraversalNeeded;
3465 }
3466 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003467 // TODO: b/109894387
3468 //
3469 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3470 // rotation. To see the problem observe that if we have a square parent, and a child
3471 // of the same size, then we rotate the child 45 degrees around it's center, the child
3472 // must now be cropped to a non rectangular 8 sided region.
3473 //
3474 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3475 // private API, and the WindowManager only uses rotation in one case, which is on a top
3476 // level layer in which cropping is not an issue.
3477 //
3478 // However given that abuse of rotation matrices could lead to surfaces extending outside
3479 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3480 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3481 // transformations.
3482 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003483 flags |= eTraversalNeeded;
3484 }
3485 if (what & layer_state_t::eTransparentRegionChanged) {
3486 if (layer->setTransparentRegionHint(s.transparentRegion))
3487 flags |= eTraversalNeeded;
3488 }
3489 if (what & layer_state_t::eFlagsChanged) {
3490 if (layer->setFlags(s.flags, s.mask))
3491 flags |= eTraversalNeeded;
3492 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003493 if (what & layer_state_t::eCropChanged_legacy) {
3494 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003495 flags |= eTraversalNeeded;
3496 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003497 if (what & layer_state_t::eFinalCropChanged_legacy) {
3498 if (layer->setFinalCrop_legacy(s.finalCrop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003499 flags |= eTraversalNeeded;
3500 }
3501 if (what & layer_state_t::eLayerStackChanged) {
3502 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3503 // We only allow setting layer stacks for top level layers,
3504 // everything else inherits layer stack from its parent.
3505 if (layer->hasParent()) {
3506 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3507 layer->getName().string());
3508 } else if (idx < 0) {
3509 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3510 "that also does not appear in the top level layer list. Something"
3511 " has gone wrong.", layer->getName().string());
3512 } else if (layer->setLayerStack(s.layerStack)) {
3513 mCurrentState.layersSortedByZ.removeAt(idx);
3514 mCurrentState.layersSortedByZ.add(layer);
3515 // we need traversal (state changed)
3516 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003517 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003518 }
3519 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003520 if (what & layer_state_t::eDeferTransaction_legacy) {
3521 if (s.barrierHandle_legacy != nullptr) {
3522 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3523 } else if (s.barrierGbp_legacy != nullptr) {
3524 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003525 if (authenticateSurfaceTextureLocked(gbp)) {
3526 const auto& otherLayer =
3527 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003528 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003529 } else {
3530 ALOGE("Attempt to defer transaction to to an"
3531 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003532 }
3533 }
chaviw8b3871a2017-11-01 17:41:01 -07003534 // We don't trigger a traversal here because if no other state is
3535 // changed, we don't want this to cause any more work
3536 }
3537 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003538 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003539 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003540 if (!hadParent) {
3541 mCurrentState.layersSortedByZ.remove(layer);
3542 }
chaviw8b3871a2017-11-01 17:41:01 -07003543 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003544 }
chaviw8b3871a2017-11-01 17:41:01 -07003545 }
3546 if (what & layer_state_t::eReparentChildren) {
3547 if (layer->reparentChildren(s.reparentHandle)) {
3548 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003549 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003550 }
chaviw8b3871a2017-11-01 17:41:01 -07003551 if (what & layer_state_t::eDetachChildren) {
3552 layer->detachChildren();
3553 }
3554 if (what & layer_state_t::eOverrideScalingModeChanged) {
3555 layer->setOverrideScalingMode(s.overrideScalingMode);
3556 // We don't trigger a traversal here because if no other state is
3557 // changed, we don't want this to cause any more work
3558 }
Marissa Wall61c58622018-07-18 10:12:20 -07003559 if (what & layer_state_t::eTransformChanged) {
3560 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3561 }
3562 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3563 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3564 flags |= eTraversalNeeded;
3565 }
3566 if (what & layer_state_t::eCropChanged) {
3567 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3568 }
3569 if (what & layer_state_t::eBufferChanged) {
3570 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3571 }
3572 if (what & layer_state_t::eAcquireFenceChanged) {
3573 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3574 }
3575 if (what & layer_state_t::eDataspaceChanged) {
3576 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3577 }
3578 if (what & layer_state_t::eHdrMetadataChanged) {
3579 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3580 }
3581 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3582 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3583 }
3584 if (what & layer_state_t::eApiChanged) {
3585 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3586 }
3587 if (what & layer_state_t::eSidebandStreamChanged) {
3588 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3589 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003590 return flags;
3591}
3592
chaviwca27f252018-02-06 16:46:39 -08003593void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3594 const layer_state_t& state = composerState.state;
3595 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3596
3597 sp<Layer> layer(client->getLayerUser(state.surface));
3598 if (layer == nullptr) {
3599 return;
3600 }
3601
3602 if (layer->isPendingRemoval()) {
3603 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3604 return;
3605 }
3606
3607 if (state.what & layer_state_t::eDestroySurface) {
3608 removeLayerLocked(mStateLock, layer);
3609 }
3610}
3611
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003612status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003613 const String8& name,
3614 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003615 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003616 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003617 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003618{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003619 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003620 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003621 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003622 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003623 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003624
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003625 status_t result = NO_ERROR;
3626
3627 sp<Layer> layer;
3628
Cody Northropbc755282017-03-31 12:00:08 -06003629 String8 uniqueName = getUniqueLayerName(name);
3630
Mathias Agopian3165cc22012-08-08 19:42:09 -07003631 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003632 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003633 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3634 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003635
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003636 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003637 case ISurfaceComposerClient::eFXSurfaceBufferState:
3638 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3639 break;
chaviw13fdc492017-06-27 12:40:18 -07003640 case ISurfaceComposerClient::eFXSurfaceColor:
3641 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003642 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003643 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003644 break;
3645 default:
3646 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003647 break;
3648 }
3649
Dan Stoza7d89d062015-04-30 13:29:25 -07003650 if (result != NO_ERROR) {
3651 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003652 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003653
Chia-I Wuab0c3192017-08-01 11:29:00 -07003654 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3655 // TODO b/64227542
3656 if (windowType == 441731) {
3657 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3658 layer->setPrimaryDisplayOnly();
3659 }
3660
Albert Chaulk479c60c2017-01-27 14:21:34 -05003661 layer->setInfo(windowType, ownerUid);
3662
Robert Carr1f0a16a2016-10-24 16:27:39 -07003663 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003664 if (result != NO_ERROR) {
3665 return result;
3666 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003667 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003668
3669 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003670 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003671}
3672
Cody Northropbc755282017-03-31 12:00:08 -06003673String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3674{
3675 bool matchFound = true;
3676 uint32_t dupeCounter = 0;
3677
3678 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3679 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3680
Dan Stoza436ccf32018-06-21 12:10:12 -07003681 // Grab the state lock since we're accessing mCurrentState
3682 Mutex::Autolock lock(mStateLock);
3683
Cody Northropbc755282017-03-31 12:00:08 -06003684 // Loop over layers until we're sure there is no matching name
3685 while (matchFound) {
3686 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003687 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003688 if (layer->getName() == uniqueName) {
3689 matchFound = true;
3690 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3691 }
3692 });
3693 }
3694
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003695 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3696 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003697
3698 return uniqueName;
3699}
3700
Marissa Wallfd668622018-05-10 10:21:13 -07003701status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3702 uint32_t w, uint32_t h, uint32_t flags,
3703 PixelFormat& format, sp<IBinder>* handle,
3704 sp<IGraphicBufferProducer>* gbp,
3705 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003706 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003707 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003708 case PIXEL_FORMAT_TRANSPARENT:
3709 case PIXEL_FORMAT_TRANSLUCENT:
3710 format = PIXEL_FORMAT_RGBA_8888;
3711 break;
3712 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003713 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003714 break;
3715 }
3716
Marissa Wallfd668622018-05-10 10:21:13 -07003717 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3718 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003719 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003720 *handle = layer->getHandle();
3721 *gbp = layer->getProducer();
3722 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003723 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003724
Marissa Wallfd668622018-05-10 10:21:13 -07003725 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003726 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003727}
3728
Marissa Wall61c58622018-07-18 10:12:20 -07003729status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3730 uint32_t w, uint32_t h, uint32_t flags,
3731 sp<IBinder>* handle, sp<Layer>* outLayer) {
3732 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3733 *handle = layer->getHandle();
3734 *outLayer = layer;
3735
3736 return NO_ERROR;
3737}
3738
chaviw13fdc492017-06-27 12:40:18 -07003739status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003740 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003741 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003742{
chaviw13fdc492017-06-27 12:40:18 -07003743 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003744 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003745 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003746}
3747
Mathias Agopianac9fa422013-02-11 16:40:36 -08003748status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003749{
Robert Carr9524cb32017-02-13 11:32:32 -08003750 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003751 status_t err = NO_ERROR;
3752 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003753 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003754 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003755 err = removeLayer(l);
3756 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3757 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003758 }
3759 return err;
3760}
3761
Mathias Agopian13127d82013-03-05 17:47:11 -08003762status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003763{
Mathias Agopian67106042013-03-14 19:18:13 -07003764 // called by ~LayerCleaner() when all references to the IBinder (handle)
3765 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003766 sp<Layer> l = layer.promote();
3767 if (l == nullptr) {
3768 // The layer has already been removed, carry on
3769 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003770 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003771 // If we have a parent, then we can continue to live as long as it does.
3772 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003773}
3774
Mathias Agopianb60314a2012-04-10 22:09:54 -07003775// ---------------------------------------------------------------------------
3776
Andy McFadden13a082e2012-08-24 10:16:42 -07003777void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003778 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3779 if (!displayToken) return;
3780
Jesse Hall01e29052013-02-19 16:13:35 -08003781 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003782 Vector<ComposerState> state;
3783 Vector<DisplayState> displays;
3784 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003785 d.what = DisplayState::eDisplayProjectionChanged |
3786 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003787 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003788 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003789 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003790 d.frame.makeInvalid();
3791 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003792 d.width = 0;
3793 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003794 displays.add(d);
3795 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003796
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003797 const auto display = getDisplayDevice(displayToken);
3798 if (!display) return;
3799
3800 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3801
3802 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003803 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003804 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003805
Brian Andersond0010582017-03-07 13:20:31 -08003806 // Use phase of 0 since phase is not known.
3807 // Use latency of 0, which will snap to the ideal latency.
3808 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003809}
3810
3811void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003812 // Async since we may be called from the main thread.
3813 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003814}
3815
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003816void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3817 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003818 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003819 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003820
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003821 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003822 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003823 return;
3824 }
3825
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003826 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003827 ALOGW("Trying to set power mode for virtual display");
3828 return;
3829 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003830
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003831 display->setPowerMode(mode);
3832
Lloyd Pique4dccc412018-01-22 17:21:36 -08003833 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003834 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003835 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003836 if (idx < 0) {
3837 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3838 return;
3839 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003840 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003841 }
3842
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003843 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003844 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003845 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003846 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003847 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003848 // FIXME: eventthread only knows about the main display right now
3849 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003850 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003851 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003852
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003853 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003854 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003855 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003856
3857 struct sched_param param = {0};
3858 param.sched_priority = 1;
3859 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3860 ALOGW("Couldn't set SCHED_FIFO on display on");
3861 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003862 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003863 // Turn off the display
3864 struct sched_param param = {0};
3865 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3866 ALOGW("Couldn't set SCHED_OTHER on display off");
3867 }
3868
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003869 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003870 disableHardwareVsync(true); // also cancels any in-progress resync
3871
Mathias Agopiancde87a32012-09-13 14:09:01 -07003872 // FIXME: eventthread only knows about the main display right now
3873 mEventThread->onScreenReleased();
3874 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003875
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003876 getHwComposer().setPowerMode(type, mode);
3877 mVisibleRegionsDirty = true;
3878 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003879 } else if (mode == HWC_POWER_MODE_DOZE ||
3880 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003881 // Update display while dozing
3882 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003883 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003884 // FIXME: eventthread only knows about the main display right now
3885 mEventThread->onScreenAcquired();
3886 resyncToHardwareVsync(true);
3887 }
3888 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3889 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003890 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003891 disableHardwareVsync(true); // also cancels any in-progress resync
3892 // FIXME: eventthread only knows about the main display right now
3893 mEventThread->onScreenReleased();
3894 }
3895 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003896 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003897 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003898 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003899 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003900
3901 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003902}
3903
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003904void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003905 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003906 const auto display = getDisplayDevice(displayToken);
3907 if (!display) {
3908 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3909 displayToken.get());
3910 } else if (display->isVirtual()) {
3911 ALOGW("Attempt to set power mode %d for virtual display", mode);
3912 } else {
3913 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003914 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003915 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003916}
3917
3918// ---------------------------------------------------------------------------
3919
Lloyd Pique755e3192018-01-31 16:46:15 -08003920status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3921 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003922 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003923
Mathias Agopianbd115332013-04-18 16:41:04 -07003924 IPCThreadState* ipc = IPCThreadState::self();
3925 const int pid = ipc->getCallingPid();
3926 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003927
Mathias Agopianbd115332013-04-18 16:41:04 -07003928 if ((uid != AID_SHELL) &&
3929 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003930 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003931 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003932 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003933 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003934 // (this would indicate SF is stuck, but we want to be able to
3935 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003936 status_t err = mStateLock.timedLock(s2ns(1));
3937 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003938 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003939 result.appendFormat(
3940 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3941 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003942 }
3943
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003944 bool dumpAll = true;
3945 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003946 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003947
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003948 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003949 if ((index < numArgs) &&
3950 (args[index] == String16("--list"))) {
3951 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003952 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003953 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003954 }
3955
3956 if ((index < numArgs) &&
3957 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003958 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003959 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003960 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003961 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003962
3963 if ((index < numArgs) &&
3964 (args[index] == String16("--latency-clear"))) {
3965 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003966 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003967 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003968 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003969
3970 if ((index < numArgs) &&
3971 (args[index] == String16("--dispsync"))) {
3972 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07003973 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07003974 dumpAll = false;
3975 }
Dan Stozab90cf072015-03-05 11:05:59 -08003976
3977 if ((index < numArgs) &&
3978 (args[index] == String16("--static-screen"))) {
3979 index++;
3980 dumpStaticScreenStats(result);
3981 dumpAll = false;
3982 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003983
3984 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003985 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003986 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003987 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003988 dumpAll = false;
3989 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003990
3991 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3992 index++;
3993 dumpWideColorInfo(result);
3994 dumpAll = false;
3995 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003996
3997 if ((index < numArgs) &&
3998 (args[index] == String16("--enable-layer-stats"))) {
3999 index++;
4000 mLayerStats.enable();
4001 dumpAll = false;
4002 }
4003
4004 if ((index < numArgs) &&
4005 (args[index] == String16("--disable-layer-stats"))) {
4006 index++;
4007 mLayerStats.disable();
4008 dumpAll = false;
4009 }
4010
4011 if ((index < numArgs) &&
4012 (args[index] == String16("--clear-layer-stats"))) {
4013 index++;
4014 mLayerStats.clear();
4015 dumpAll = false;
4016 }
4017
4018 if ((index < numArgs) &&
4019 (args[index] == String16("--dump-layer-stats"))) {
4020 index++;
4021 mLayerStats.dump(result);
4022 dumpAll = false;
4023 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004024
4025 if ((index < numArgs) &&
4026 (args[index] == String16("--display-identification"))) {
4027 index++;
4028 dumpDisplayIdentificationData(result);
4029 dumpAll = false;
4030 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004031
4032 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4033 index++;
4034 mTimeStats.parseArgs(asProto, args, index, result);
4035 dumpAll = false;
4036 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004037 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004038
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004039 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004040 if (asProto) {
4041 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4042 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4043 } else {
4044 dumpAllLocked(args, index, result);
4045 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004046 }
4047
Mathias Agopian9795c422009-08-26 16:36:26 -07004048 if (locked) {
4049 mStateLock.unlock();
4050 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004051 }
4052 write(fd, result.string(), result.size());
4053 return NO_ERROR;
4054}
4055
Dan Stozac7014012014-02-14 15:03:43 -08004056void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4057 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004058{
Robert Carr2047fae2016-11-28 14:09:09 -08004059 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004060 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004061 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004062}
4063
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004064void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004065 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004066{
4067 String8 name;
4068 if (index < args.size()) {
4069 name = String8(args[index]);
4070 index++;
4071 }
4072
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004073 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4074 getHwComposer().isConnected(displayId)) {
4075 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4076 const nsecs_t period = activeConfig->getVsyncPeriod();
4077 result.appendFormat("%" PRId64 "\n", period);
4078 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004079
4080 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004081 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004082 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004083 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004084 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004085 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004086 }
Robert Carr2047fae2016-11-28 14:09:09 -08004087 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004088 }
4089}
4090
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004091void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004092 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004093{
4094 String8 name;
4095 if (index < args.size()) {
4096 name = String8(args[index]);
4097 index++;
4098 }
4099
Robert Carr2047fae2016-11-28 14:09:09 -08004100 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004101 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004102 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004103 }
Robert Carr2047fae2016-11-28 14:09:09 -08004104 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004105
Svetoslavd85084b2014-03-20 10:28:31 -07004106 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004107}
4108
Jamie Gennis6547ff42013-07-16 20:12:42 -07004109// This should only be called from the main thread. Otherwise it would need
4110// the lock and should use mCurrentState rather than mDrawingState.
4111void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004112 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004113 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004114 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004115
4116 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4117}
4118
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004119void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004120{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004121 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004122
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004123 if (isLayerTripleBufferingDisabled())
4124 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004125
4126 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004127 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004128 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004129 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004130 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4131 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004132 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004133}
4134
Dan Stozab90cf072015-03-05 11:05:59 -08004135void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4136{
4137 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004138 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4139 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004140 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004141 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004142 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4143 b + 1, bucketTimeSec, percent);
4144 }
David Sodman4a36e932017-11-07 14:29:47 -08004145 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004146 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004147 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004148 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004149 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004150}
4151
Dan Stozae77c7662016-05-13 11:37:28 -07004152void SurfaceFlinger::recordBufferingStats(const char* layerName,
4153 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004154 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4155 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004156 for (const auto& segment : history) {
4157 if (!segment.usedThirdBuffer) {
4158 stats.twoBufferTime += segment.totalTime;
4159 }
4160 if (segment.occupancyAverage < 1.0f) {
4161 stats.doubleBufferedTime += segment.totalTime;
4162 } else if (segment.occupancyAverage < 2.0f) {
4163 stats.tripleBufferedTime += segment.totalTime;
4164 }
4165 ++stats.numSegments;
4166 stats.totalTime += segment.totalTime;
4167 }
4168}
4169
Brian Andersond6927fb2016-07-23 23:37:30 -07004170void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4171 result.appendFormat("Layer frame timestamps:\n");
4172
4173 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4174 const size_t count = currentLayers.size();
4175 for (size_t i=0 ; i<count ; i++) {
4176 currentLayers[i]->dumpFrameEvents(result);
4177 }
4178}
4179
Dan Stozae77c7662016-05-13 11:37:28 -07004180void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4181 result.append("Buffering stats:\n");
4182 result.append(" [Layer name] <Active time> <Two buffer> "
4183 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004184 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004185 typedef std::tuple<std::string, float, float, float> BufferTuple;
4186 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004187 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004188 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004189 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004190 if (stats.numSegments == 0) {
4191 continue;
4192 }
4193 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4194 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4195 stats.totalTime;
4196 float doubleBufferRatio = static_cast<float>(
4197 stats.doubleBufferedTime) / stats.totalTime;
4198 float tripleBufferRatio = static_cast<float>(
4199 stats.tripleBufferedTime) / stats.totalTime;
4200 sorted.insert({activeTime, {name, twoBufferRatio,
4201 doubleBufferRatio, tripleBufferRatio}});
4202 }
4203 for (const auto& sortedPair : sorted) {
4204 float activeTime = sortedPair.first;
4205 const BufferTuple& values = sortedPair.second;
4206 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4207 std::get<0>(values).c_str(), activeTime,
4208 std::get<1>(values), std::get<2>(values),
4209 std::get<3>(values));
4210 }
4211 result.append("\n");
4212}
4213
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004214void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004215 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004216 const int32_t displayId = display->getId();
4217 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4218 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004219 continue;
4220 }
4221
Dominik Laskowski7e045462018-05-30 13:02:02 -07004222 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004223 uint8_t port;
4224 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004225 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004226 result.append("no identification data\n");
4227 continue;
4228 }
4229
4230 if (!isEdid(data)) {
4231 result.append("unknown identification data: ");
4232 for (uint8_t byte : data) {
4233 result.appendFormat("%x ", byte);
4234 }
4235 result.append("\n");
4236 continue;
4237 }
4238
4239 const auto edid = parseEdid(data);
4240 if (!edid) {
4241 result.append("invalid EDID: ");
4242 for (uint8_t byte : data) {
4243 result.appendFormat("%x ", byte);
4244 }
4245 result.append("\n");
4246 continue;
4247 }
4248
4249 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4250 result.append(edid->displayName.data(), edid->displayName.length());
4251 result.append("\"\n");
4252 }
4253 result.append("\n");
4254}
4255
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004256void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4257 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004258 result.appendFormat("DisplayColorSetting: %s\n",
4259 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004260
4261 // TODO: print out if wide-color mode is active or not
4262
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004263 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004264 const int32_t displayId = display->getId();
4265 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004266 continue;
4267 }
4268
Dominik Laskowski7e045462018-05-30 13:02:02 -07004269 result.appendFormat("Display %d color modes:\n", displayId);
4270 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004271 for (auto&& mode : modes) {
4272 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4273 }
4274
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004275 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004276 result.appendFormat(" Current color mode: %s (%d)\n",
4277 decodeColorMode(currentMode).c_str(), currentMode);
4278 }
4279 result.append("\n");
4280}
4281
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004282LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004283 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004284 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4285 const State& state = useDrawing ? mDrawingState : mCurrentState;
4286 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004287 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004288 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004289 });
4290
4291 return layersProto;
4292}
4293
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004294LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004295 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004296
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004297 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004298 resolution->set_w(display.getWidth());
4299 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004300
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004301 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4302 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4303 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004304
Dominik Laskowski7e045462018-05-30 13:02:02 -07004305 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004306 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004307 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004308 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004309 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004310 }
4311 });
4312
4313 return layersProto;
4314}
4315
Mathias Agopian74d211a2013-04-22 16:55:35 +02004316void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4317 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004318{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004319 bool colorize = false;
4320 if (index < args.size()
4321 && (args[index] == String16("--color"))) {
4322 colorize = true;
4323 index++;
4324 }
4325
4326 Colorizer colorizer(colorize);
4327
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004328 // figure out if we're stuck somewhere
4329 const nsecs_t now = systemTime();
4330 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4331 const nsecs_t inTransaction(mDebugInTransaction);
4332 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4333 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4334
4335 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004336 * Dump library configuration.
4337 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004338
4339 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004340 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004341 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004342 appendSfConfigString(result);
4343 appendUiConfigString(result);
4344 appendGuiConfigString(result);
4345 result.append("\n");
4346
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004347 result.append("\nDisplay identification data:\n");
4348 dumpDisplayIdentificationData(result);
4349
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004350 result.append("\nWide-Color information:\n");
4351 dumpWideColorInfo(result);
4352
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004353 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004354 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004355 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004356 result.append(SyncFeatures::getInstance().toString());
4357 result.append("\n");
4358
Andy McFadden41d67d72014-04-25 16:58:34 -07004359 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004360 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004361 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004362
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004363 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4364 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004365 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4366 getHwComposer().isConnected(displayId)) {
4367 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004368 result.appendFormat("Display %d: "
4369 "app phase %" PRId64 " ns, "
4370 "sf phase %" PRId64 " ns, "
4371 "early app phase %" PRId64 " ns, "
4372 "early sf phase %" PRId64 " ns, "
4373 "early app gl phase %" PRId64 " ns, "
4374 "early sf gl phase %" PRId64 " ns, "
4375 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4376 displayId,
4377 vsyncPhaseOffsetNs,
4378 sfVsyncPhaseOffsetNs,
4379 appEarlyOffset,
4380 sfEarlyOffset,
4381 appEarlyGlOffset,
4382 sfEarlyOffset,
4383 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004384 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004385 result.append("\n");
4386
Dan Stozab90cf072015-03-05 11:05:59 -08004387 // Dump static screen stats
4388 result.append("\n");
4389 dumpStaticScreenStats(result);
4390 result.append("\n");
4391
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004392 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4393
Dan Stozae77c7662016-05-13 11:37:28 -07004394 dumpBufferingStats(result);
4395
Andy McFadden4803b742012-09-24 19:07:20 -07004396 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004397 * Dump the visible layer list
4398 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004399 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004400 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004401 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4402 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004403 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004404
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004405 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004406 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004407 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004408 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004409
4410 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004411 * Dump Display state
4412 */
4413
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004414 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004415 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004416 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004417 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004418 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004419 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004420 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004421
4422 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004423 * Dump SurfaceFlinger global state
4424 */
4425
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004426 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004427 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004428 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004429
Mathias Agopian888c8222012-08-04 21:10:38 -07004430 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004431 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004432
David Sodmanbc815282017-11-05 18:57:52 -08004433 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004434
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004435 if (display) {
4436 display->undefinedRegion.dump(result, "undefinedRegion");
4437 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4438 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004439 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004440 result.appendFormat(" last eglSwapBuffers() time: %f us\n"
4441 " last transaction time : %f us\n"
4442 " transaction-flags : %08x\n"
4443 " gpu_to_cpu_unsupported : %d\n",
4444 mLastSwapBufferTime / 1000.0, mLastTransactionTime / 1000.0,
4445 mTransactionFlags, !mGpuToCpuSupported);
4446
4447 if (display) {
4448 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4449 result.appendFormat(" refresh-rate : %f fps\n"
4450 " x-dpi : %f\n"
4451 " y-dpi : %f\n",
4452 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4453 activeConfig->getDpiY());
4454 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004455
Mathias Agopian74d211a2013-04-22 16:55:35 +02004456 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004457 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004458
Mathias Agopian74d211a2013-04-22 16:55:35 +02004459 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004460 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004461
4462 /*
4463 * VSYNC state
4464 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004465 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004466 result.append("\n");
4467
4468 /*
4469 * HWC layer minidump
4470 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004471 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004472 const int32_t displayId = display->getId();
4473 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004474 continue;
4475 }
4476
Dominik Laskowski7e045462018-05-30 13:02:02 -07004477 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004478 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004479 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004480 result.append("\n");
4481 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004482
4483 /*
4484 * Dump HWComposer state
4485 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004486 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004487 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004488 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004489 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004490 result.appendFormat(" h/w composer %s\n",
4491 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004492 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004493
4494 /*
4495 * Dump gralloc state
4496 */
4497 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4498 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004499
4500 /*
4501 * Dump VrFlinger state if in use.
4502 */
4503 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4504 result.append("VrFlinger state:\n");
4505 result.append(mVrFlinger->Dump().c_str());
4506 result.append("\n");
4507 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004508}
4509
Dominik Laskowski7e045462018-05-30 13:02:02 -07004510const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004511 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004512 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004513 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004514 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004515 }
4516 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004517
4518 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4519 static const Vector<sp<Layer>> empty;
4520 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004521}
4522
Keun young Park63f165f2012-08-31 10:53:36 -07004523bool SurfaceFlinger::startDdmConnection()
4524{
4525 void* libddmconnection_dso =
4526 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4527 if (!libddmconnection_dso) {
4528 return false;
4529 }
4530 void (*DdmConnection_start)(const char* name);
4531 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004532 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004533 if (!DdmConnection_start) {
4534 dlclose(libddmconnection_dso);
4535 return false;
4536 }
4537 (*DdmConnection_start)(getServiceName());
4538 return true;
4539}
4540
Chia-I Wu28f320b2018-05-03 11:02:56 -07004541void SurfaceFlinger::updateColorMatrixLocked() {
4542 mat4 colorMatrix;
4543 if (mGlobalSaturationFactor != 1.0f) {
4544 // Rec.709 luma coefficients
4545 float3 luminance{0.213f, 0.715f, 0.072f};
4546 luminance *= 1.0f - mGlobalSaturationFactor;
4547 mat4 saturationMatrix = mat4(
4548 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4549 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4550 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4551 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4552 );
4553 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4554 } else {
4555 colorMatrix = mClientColorMatrix * mDaltonizer();
4556 }
4557
4558 if (mCurrentState.colorMatrix != colorMatrix) {
4559 mCurrentState.colorMatrix = colorMatrix;
4560 mCurrentState.colorMatrixChanged = true;
4561 setTransactionFlags(eTransactionNeeded);
4562 }
4563}
4564
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004565status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Dan Stozae3344402018-08-20 19:53:42 +00004566 switch (code) {
Ana Krulecfbe2c002018-08-09 22:32:45 +00004567 case CREATE_CONNECTION:
4568 case CREATE_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004569 case BOOT_FINISHED:
4570 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulecfbe2c002018-08-09 22:32:45 +00004571 case GET_ANIMATION_FRAME_STATS:
Dan Stozae3344402018-08-20 19:53:42 +00004572 case SET_POWER_MODE:
Ana Krulecfbe2c002018-08-09 22:32:45 +00004573 case GET_HDR_CAPABILITIES:
Dan Stozae3344402018-08-20 19:53:42 +00004574 case ENABLE_VSYNC_INJECTIONS:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004575 case INJECT_VSYNC:
Dan Stozae3344402018-08-20 19:53:42 +00004576 {
4577 // codes that require permission check
Robert Carrd4ae7f32018-06-07 16:10:57 -07004578 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4579 IPCThreadState* ipc = IPCThreadState::self();
4580 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4581 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004582 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004583 }
Dan Stozae3344402018-08-20 19:53:42 +00004584 break;
4585 }
4586 /*
4587 * Calling setTransactionState is safe, because you need to have been
4588 * granted a reference to Client* and Handle* to do anything with it.
4589 *
4590 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4591 */
4592 case SET_TRANSACTION_STATE:
4593 case CREATE_SCOPED_CONNECTION:
4594 {
Robert Carr1db73f62016-12-21 12:58:51 -08004595 return OK;
4596 }
Dan Stozae3344402018-08-20 19:53:42 +00004597 case CAPTURE_SCREEN:
4598 {
4599 // codes that require permission check
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004600 IPCThreadState* ipc = IPCThreadState::self();
4601 const int pid = ipc->getCallingPid();
4602 const int uid = ipc->getCallingUid();
Dan Stozae3344402018-08-20 19:53:42 +00004603 if ((uid != AID_GRAPHICS) &&
4604 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4605 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004606 return PERMISSION_DENIED;
4607 }
Dan Stozae3344402018-08-20 19:53:42 +00004608 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004609 }
Dan Stozae3344402018-08-20 19:53:42 +00004610 case CAPTURE_LAYERS: {
chaviwa76b2712017-09-20 12:02:26 -07004611 IPCThreadState* ipc = IPCThreadState::self();
4612 const int pid = ipc->getCallingPid();
4613 const int uid = ipc->getCallingUid();
4614 if ((uid != AID_GRAPHICS) &&
4615 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4616 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4617 return PERMISSION_DENIED;
4618 }
Dan Stozae3344402018-08-20 19:53:42 +00004619 break;
chaviwa76b2712017-09-20 12:02:26 -07004620 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004621 }
Dan Stozae3344402018-08-20 19:53:42 +00004622 return OK;
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004623}
4624
Dan Stozae3344402018-08-20 19:53:42 +00004625status_t SurfaceFlinger::onTransact(
4626 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4627{
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004628 status_t credentialCheck = CheckTransactCodeCredentials(code);
4629 if (credentialCheck != OK) {
4630 return credentialCheck;
4631 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004632
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004633 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4634 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004635 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004636 IPCThreadState* ipc = IPCThreadState::self();
4637 const int uid = ipc->getCallingUid();
4638 if (CC_UNLIKELY(uid != AID_SYSTEM
4639 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004640 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004641 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004642 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004643 return PERMISSION_DENIED;
4644 }
4645 int n;
4646 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004647 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004648 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004649 return NO_ERROR;
4650 case 1002: // SHOW_UPDATES
4651 n = data.readInt32();
4652 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004653 invalidateHwcGeometry();
4654 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004655 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004656 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004657 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004658 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004659 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004660 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004661 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004662 setTransactionFlags(
4663 eTransactionNeeded|
4664 eDisplayTransactionNeeded|
4665 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004666 return NO_ERROR;
4667 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004668 case 1006:{ // send empty update
4669 signalRefresh();
4670 return NO_ERROR;
4671 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004672 case 1008: // toggle use of hw composer
4673 n = data.readInt32();
4674 mDebugDisableHWC = n ? 1 : 0;
4675 invalidateHwcGeometry();
4676 repaintEverything();
4677 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004678 case 1009: // toggle use of transform hint
4679 n = data.readInt32();
4680 mDebugDisableTransformHint = n ? 1 : 0;
4681 invalidateHwcGeometry();
4682 repaintEverything();
4683 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004684 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004685 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004686 reply->writeInt32(0);
4687 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004688 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004689 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004690 return NO_ERROR;
4691 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004692 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004693 if (!display) {
4694 return NAME_NOT_FOUND;
4695 }
4696
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004697 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004698 return NO_ERROR;
4699 }
4700 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004701 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004702 // daltonize
4703 n = data.readInt32();
4704 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004705 case 1:
4706 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4707 break;
4708 case 2:
4709 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4710 break;
4711 case 3:
4712 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4713 break;
4714 default:
4715 mDaltonizer.setType(ColorBlindnessType::None);
4716 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004717 }
4718 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004719 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004720 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004721 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004722 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004723
4724 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004725 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004726 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004727 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004728 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004729 // apply a color matrix
4730 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004731 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004732 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004733 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004734 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004735 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004736 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004737 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004738 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004739 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004740 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004741
4742 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4743 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004744 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004745 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4746 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4747 }
4748
Chia-I Wu28f320b2018-05-03 11:02:56 -07004749 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004750 return NO_ERROR;
4751 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004752 // This is an experimental interface
4753 // Needs to be shifted to proper binder interface when we productize
4754 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004755 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07004756 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004757 return NO_ERROR;
4758 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004759 case 1017: {
4760 n = data.readInt32();
4761 mForceFullDamage = static_cast<bool>(n);
4762 return NO_ERROR;
4763 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004764 case 1018: { // Modify Choreographer's phase offset
4765 n = data.readInt32();
4766 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4767 return NO_ERROR;
4768 }
4769 case 1019: { // Modify SurfaceFlinger's phase offset
4770 n = data.readInt32();
4771 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4772 return NO_ERROR;
4773 }
Irvel468051e2016-06-13 16:44:44 -07004774 case 1020: { // Layer updates interceptor
4775 n = data.readInt32();
4776 if (n) {
4777 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004778 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004779 }
4780 else{
4781 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004782 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004783 }
4784 return NO_ERROR;
4785 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004786 case 1021: { // Disable HWC virtual displays
4787 n = data.readInt32();
4788 mUseHwcVirtualDisplays = !n;
4789 return NO_ERROR;
4790 }
Romain Guy0147a172017-06-01 13:53:56 -07004791 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004792 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004793 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004794
Chia-I Wu28f320b2018-05-03 11:02:56 -07004795 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004796 return NO_ERROR;
4797 }
Romain Guy54f154a2017-10-24 21:40:32 +01004798 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004799 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004800 invalidateHwcGeometry();
4801 repaintEverything();
4802 return NO_ERROR;
4803 }
4804 case 1024: { // Is wide color gamut rendering/color management supported?
4805 reply->writeBool(hasWideColorDisplay);
4806 return NO_ERROR;
4807 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004808 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004809 n = data.readInt32();
4810 if (n) {
4811 ALOGV("LayerTracing enabled");
4812 mTracing.enable();
4813 doTracing("tracing.enable");
4814 reply->writeInt32(NO_ERROR);
4815 } else {
4816 ALOGV("LayerTracing disabled");
4817 status_t err = mTracing.disable();
4818 reply->writeInt32(err);
4819 }
4820 return NO_ERROR;
4821 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004822 case 1026: { // Get layer tracing status
4823 reply->writeBool(mTracing.isEnabled());
4824 return NO_ERROR;
4825 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004826 // Is a DisplayColorSetting supported?
4827 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004828 const auto display = getDefaultDisplayDevice();
4829 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004830 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004831 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004832
4833 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4834 switch (setting) {
4835 case DisplayColorSetting::MANAGED:
4836 reply->writeBool(hasWideColorDisplay);
4837 break;
4838 case DisplayColorSetting::UNMANAGED:
4839 reply->writeBool(true);
4840 break;
4841 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004842 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004843 break;
4844 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004845 reply->writeBool(
4846 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004847 break;
4848 }
4849 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004850 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004851 // Is VrFlinger active?
4852 case 1028: {
4853 Mutex::Autolock _l(mStateLock);
4854 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4855 return NO_ERROR;
4856 }
David Sodman6d46c1e2018-07-13 12:59:48 -07004857 case 1029: {
4858 // Code 1029 is an experimental feature that allows applications to
4859 // simulate a high frequency panel by setting a multiplier and divisor
4860 // on the VSYNC-sf clock. If either the multiplier or divisor are
4861 // 0, then the code will set both to 1 to return the VSYNC-sf clock
4862 // to it's normal frequency.
4863 int multiplier = data.readInt32();
4864 int divisor = data.readInt32();
4865
4866 if ((multiplier == 0) || (divisor == 0)) {
4867 multiplier = 1;
4868 divisor = 1;
4869 }
4870
4871 if ((multiplier == 1) && (divisor == 1)) {
4872 enableHardwareVsync();
4873 } else {
4874 disableHardwareVsync(true);
4875 }
4876 getBE().mHwc->getActiveConfig(DisplayDevice::DISPLAY_PRIMARY)
4877 ->scalePanelFrequency(multiplier, divisor);
4878 mPrimaryDispSync->scalePeriod(multiplier, divisor);
4879
4880 ATRACE_INT("PeriodMultiplier", multiplier);
4881 ATRACE_INT("PeriodDivisor", divisor);
4882 return NO_ERROR;
4883 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004884 }
4885 }
4886 return err;
4887}
4888
Steven Thomas6d8110b2017-08-31 18:24:21 -07004889void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004890 android_atomic_or(1, &mRepaintEverything);
4891 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004892}
4893
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004894// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4895class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004896public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004897 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4898 ~WindowDisconnector() {
4899 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004900 }
4901
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004902private:
4903 ANativeWindow* mWindow;
4904 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004905};
4906
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004907status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4908 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4909 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4910 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004911 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004912 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004913
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004914 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004915
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004916 const auto display = getDisplayDeviceLocked(displayToken);
4917 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004918
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004919 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004920
4921 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004922 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004923 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004924}
4925
4926status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004927 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004928 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004929 ATRACE_CALL();
4930
4931 class LayerRenderArea : public RenderArea {
4932 public:
Robert Carr578038f2018-03-09 12:25:24 -08004933 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4934 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004935 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004936 mLayer(layer),
4937 mCrop(crop),
4938 mFlinger(flinger),
4939 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004940 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004941 Rect getBounds() const override {
4942 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07004943 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07004944 }
Marissa Wall61c58622018-07-18 10:12:20 -07004945 int getHeight() const override {
4946 return mLayer->getActiveHeight(mLayer->getDrawingState());
4947 }
4948 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07004949 bool isSecure() const override { return false; }
4950 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004951 Rect getSourceCrop() const override {
4952 if (mCrop.isEmpty()) {
4953 return getBounds();
4954 } else {
4955 return mCrop;
4956 }
4957 }
Robert Carr578038f2018-03-09 12:25:24 -08004958 class ReparentForDrawing {
4959 public:
4960 const sp<Layer>& oldParent;
4961 const sp<Layer>& newParent;
4962
4963 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4964 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004965 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004966 }
Robert Carr15eae092018-03-23 13:43:53 -07004967 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004968 };
4969
4970 void render(std::function<void()> drawLayers) override {
4971 if (!mChildrenOnly) {
4972 mTransform = mLayer->getTransform().inverse();
4973 drawLayers();
4974 } else {
4975 Rect bounds = getBounds();
4976 screenshotParentLayer =
4977 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4978 bounds.getWidth(), bounds.getHeight(), 0);
4979
4980 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4981 drawLayers();
4982 }
4983 }
chaviwa76b2712017-09-20 12:02:26 -07004984
chaviwa76b2712017-09-20 12:02:26 -07004985 private:
chaviw7206d492017-11-10 16:16:12 -08004986 const sp<Layer> mLayer;
4987 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004988
4989 // In the "childrenOnly" case we reparent the children to a screenshot
4990 // layer which has no properties set and which does not draw.
4991 sp<ContainerLayer> screenshotParentLayer;
4992 Transform mTransform;
4993
4994 SurfaceFlinger* mFlinger;
4995 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004996 };
4997
4998 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4999 auto parent = layerHandle->owner.promote();
5000
chaviw7206d492017-11-10 16:16:12 -08005001 if (parent == nullptr || parent->isPendingRemoval()) {
5002 ALOGE("captureLayers called with a removed parent");
5003 return NAME_NOT_FOUND;
5004 }
5005
Robert Carr578038f2018-03-09 12:25:24 -08005006 const int uid = IPCThreadState::self()->getCallingUid();
5007 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5008 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5009 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5010 return PERMISSION_DENIED;
5011 }
5012
chaviw7206d492017-11-10 16:16:12 -08005013 Rect crop(sourceCrop);
5014 if (sourceCrop.width() <= 0) {
5015 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005016 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005017 }
5018
5019 if (sourceCrop.height() <= 0) {
5020 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005021 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005022 }
5023
5024 int32_t reqWidth = crop.width() * frameScale;
5025 int32_t reqHeight = crop.height() * frameScale;
5026
Robert Carr578038f2018-03-09 12:25:24 -08005027 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005028
Robert Carr578038f2018-03-09 12:25:24 -08005029 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005030 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5031 if (!layer->isVisible()) {
5032 return;
Robert Carr578038f2018-03-09 12:25:24 -08005033 } else if (childrenOnly && layer == parent.get()) {
5034 return;
chaviwa76b2712017-09-20 12:02:26 -07005035 }
5036 visitor(layer);
5037 });
5038 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005039 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005040}
5041
5042status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5043 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005044 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005045 bool useIdentityTransform) {
5046 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005047
Iris Chang7501ed62018-04-30 14:45:42 +08005048 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07005049
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005050 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5051 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5052 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5053 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005054
5055 // This mutex protects syncFd and captureResult for communication of the return values from the
5056 // main thread back to this Binder thread
5057 std::mutex captureMutex;
5058 std::condition_variable captureCondition;
5059 std::unique_lock<std::mutex> captureLock(captureMutex);
5060 int syncFd = -1;
5061 std::optional<status_t> captureResult;
5062
Robert Carr03480e22018-01-04 16:02:06 -08005063 const int uid = IPCThreadState::self()->getCallingUid();
5064 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5065
Dominik Laskowski8c001672018-05-30 16:52:06 -07005066 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005067 // If there is a refresh pending, bug out early and tell the binder thread to try again
5068 // after the refresh.
5069 if (mRefreshPending) {
5070 ATRACE_NAME("Skipping screenshot for now");
5071 std::unique_lock<std::mutex> captureLock(captureMutex);
5072 captureResult = std::make_optional<status_t>(EAGAIN);
5073 captureCondition.notify_one();
5074 return;
5075 }
5076
5077 status_t result = NO_ERROR;
5078 int fd = -1;
5079 {
5080 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005081 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005082 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5083 useIdentityTransform, forSystem, &fd);
5084 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005085 }
5086
5087 {
5088 std::unique_lock<std::mutex> captureLock(captureMutex);
5089 syncFd = fd;
5090 captureResult = std::make_optional<status_t>(result);
5091 captureCondition.notify_one();
5092 }
5093 });
5094
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005095 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005096 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005097 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005098 while (*captureResult == EAGAIN) {
5099 captureResult.reset();
5100 result = postMessageAsync(message);
5101 if (result != NO_ERROR) {
5102 return result;
5103 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005104 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005105 }
5106 result = *captureResult;
5107 }
5108
5109 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005110 sync_wait(syncFd, -1);
5111 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005112 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005113
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005114 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005115}
5116
chaviwa76b2712017-09-20 12:02:26 -07005117void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5118 TraverseLayersFunction traverseLayers, bool yswap,
5119 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005120 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005121
Lloyd Pique144e1162017-12-20 16:44:52 -08005122 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005123
5124 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005125 const auto raWidth = renderArea.getWidth();
5126 const auto raHeight = renderArea.getHeight();
5127
5128 const auto reqWidth = renderArea.getReqWidth();
5129 const auto reqHeight = renderArea.getReqHeight();
5130 Rect sourceCrop = renderArea.getSourceCrop();
5131
Iris Chang7501ed62018-04-30 14:45:42 +08005132 bool filtering = false;
5133 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5134 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5135 static_cast<int32_t>(reqHeight) != raWidth;
5136 } else {
5137 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5138 static_cast<int32_t>(reqHeight) != raHeight;
5139 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005140
Dan Stozac1879002014-05-22 15:59:05 -07005141 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005142 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005143 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005144 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005145 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5146 Transform tr;
5147 uint32_t flags = 0x00;
5148 switch (mPrimaryDisplayOrientation) {
5149 case DisplayState::eOrientation90:
5150 flags = Transform::ROT_90;
5151 break;
5152 case DisplayState::eOrientation180:
5153 flags = Transform::ROT_180;
5154 break;
5155 case DisplayState::eOrientation270:
5156 flags = Transform::ROT_270;
5157 break;
5158 }
5159 tr.set(flags, raWidth, raHeight);
5160 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005161 }
5162
5163 // ensure that sourceCrop is inside screen
5164 if (sourceCrop.left < 0) {
5165 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5166 }
chaviwa76b2712017-09-20 12:02:26 -07005167 if (sourceCrop.right > raWidth) {
5168 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005169 }
5170 if (sourceCrop.top < 0) {
5171 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5172 }
chaviwa76b2712017-09-20 12:02:26 -07005173 if (sourceCrop.bottom > raHeight) {
5174 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005175 }
5176
Chia-I Wu36574d92018-05-16 10:54:36 -07005177 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5178 engine.setOutputDataSpace(Dataspace::SRGB);
5179 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005180
Mathias Agopian180f10d2013-04-10 22:55:41 -07005181 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005182 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005183
Iris Chang7501ed62018-04-30 14:45:42 +08005184 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5185 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5186 // convert hw orientation into flag presentation
5187 // here inverse transform needed
5188 uint8_t hw_rot_90 = 0x00;
5189 uint8_t hw_flip_hv = 0x00;
5190 switch (mPrimaryDisplayOrientation) {
5191 case DisplayState::eOrientation90:
5192 hw_rot_90 = Transform::ROT_90;
5193 hw_flip_hv = Transform::ROT_180;
5194 break;
5195 case DisplayState::eOrientation180:
5196 hw_flip_hv = Transform::ROT_180;
5197 break;
5198 case DisplayState::eOrientation270:
5199 hw_rot_90 = Transform::ROT_90;
5200 break;
5201 }
5202
5203 // transform flags operation
5204 // 1) flip H V if both have ROT_90 flag
5205 // 2) XOR these flags
5206 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5207 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5208 if (rotation_rot_90 & hw_rot_90) {
5209 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5210 }
5211 rotation = static_cast<Transform::orientation_flags>
5212 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5213 }
5214
Mathias Agopian180f10d2013-04-10 22:55:41 -07005215 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005216 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005217 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005218 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005219
chaviw50da5042018-04-09 13:49:37 -07005220 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005221 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005222 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005223
chaviwa76b2712017-09-20 12:02:26 -07005224 traverseLayers([&](Layer* layer) {
5225 if (filtering) layer->setFiltering(true);
David Sodmanca10ed22018-04-16 14:10:25 -07005226 layer->drawNow(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005227 if (filtering) layer->setFiltering(false);
5228 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005229}
5230
chaviwa76b2712017-09-20 12:02:26 -07005231status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5232 TraverseLayersFunction traverseLayers,
5233 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005234 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005235 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005236 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005237 ATRACE_CALL();
5238
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005239 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005240
5241 traverseLayers([&](Layer* layer) {
5242 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5243 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005244
Robert Carr03480e22018-01-04 16:02:06 -08005245 // We allow the system server to take screenshots of secure layers for
5246 // use in situations like the Screen-rotation animation and place
5247 // the impetus on WindowManager to not persist them.
5248 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005249 ALOGW("FB is protected: PERMISSION_DENIED");
5250 return PERMISSION_DENIED;
5251 }
5252
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005253 // this binds the given EGLImage as a framebuffer for the
5254 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005255 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005256 if (bufferBond.getStatus() != NO_ERROR) {
5257 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005258 return INVALID_OPERATION;
5259 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005260
Dan Stozaabcda352017-06-01 14:37:39 -07005261 // this will in fact render into our dequeued buffer
5262 // via an FBO, which means we didn't have to create
5263 // an EGLSurface and therefore we're not
5264 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005265 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005266
Dan Stozaabcda352017-06-01 14:37:39 -07005267 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005268 getRenderEngine().finish();
5269 *outSyncFd = -1;
5270
chaviwa76b2712017-09-20 12:02:26 -07005271 const auto reqWidth = renderArea.getReqWidth();
5272 const auto reqHeight = renderArea.getReqHeight();
5273
Dan Stozaabcda352017-06-01 14:37:39 -07005274 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5275 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005276 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005277 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005278 } else {
5279 base::unique_fd syncFd = getRenderEngine().flush();
5280 if (syncFd < 0) {
5281 getRenderEngine().finish();
5282 }
5283 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005284 }
5285
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005286 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005287}
5288
Mathias Agopiand5556842013-09-19 17:08:37 -07005289void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005290 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005291 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005292 for (size_t y = 0; y < h; y++) {
5293 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5294 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005295 if (p[x] != 0xFF000000) return;
5296 }
5297 }
chaviwa76b2712017-09-20 12:02:26 -07005298 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005299
Robert Carr2047fae2016-11-28 14:09:09 -08005300 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005301 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005302 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005303 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5304 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5305 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5306 static_cast<float>(state.color.a));
5307 i++;
5308 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005309 }
5310}
5311
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005312// ---------------------------------------------------------------------------
5313
Dan Stoza412903f2017-04-27 13:42:17 -07005314void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5315 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005316}
5317
Dan Stoza412903f2017-04-27 13:42:17 -07005318void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5319 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005320}
5321
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005322void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5323 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005324 const LayerVector::Visitor& visitor) {
5325 // We loop through the first level of layers without traversing,
5326 // as we need to interpret min/max layer Z in the top level Z space.
5327 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005328 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005329 continue;
5330 }
5331 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005332 // relative layers are traversed in Layer::traverseInZOrder
5333 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005334 continue;
5335 }
5336 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005337 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005338 return;
5339 }
chaviwa76b2712017-09-20 12:02:26 -07005340 if (!layer->isVisible()) {
5341 return;
5342 }
5343 visitor(layer);
5344 });
5345 }
5346}
5347
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005348}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005349
Lloyd Pique074e8122018-07-26 12:57:23 -07005350
Mathias Agopian3f844832013-08-07 21:24:32 -07005351#if defined(__gl_h_)
5352#error "don't include gl/gl.h in this file"
5353#endif
5354
5355#if defined(__gl2_h_)
5356#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005357#endif