blob: 629c6cafe6770cada93ffb8160a933197e69c9f4 [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 Wu6d844112018-06-27 07:17:41 +080040#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060041#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070043#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080048#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070050
51#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Robert Carr578038f2018-03-09 12:25:24 -080065#include "BufferLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020066#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080067#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ContainerLayer.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070070#include "DispSync.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "DisplayDevice.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070072#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080073#include "EventThread.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"
Chia-I Wu82144eb2018-08-24 15:34:02 -070078#include "Transform.h"
Robert Carr578038f2018-03-09 12:25:24 -080079#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080
Steven Thomasb02664d2017-07-26 18:48:28 -070081#include "DisplayHardware/ComposerHal.h"
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"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085
Mathias Agopianff2ed702013-09-01 21:36:12 -070086#include "Effects/Daltonizer.h"
87
Mathias Agopian875d8e12013-06-07 15:35:48 -070088#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070089#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070090
Jiyong Park4b20c2e2017-01-14 19:45:11 +090091#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080092#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
93#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090094#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090095
chaviw1d044282017-09-27 12:19:28 -070096#include <layerproto/LayerProtoParser.h>
97
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080098#define DISPLAY_COUNT 1
99
Mathias Agopianfee2b462013-07-03 12:34:01 -0700100/*
101 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
102 * black pixels.
103 */
104#define DEBUG_SCREENSHOTS false
105
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800106namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700107
Jaesoo Lee43518572017-01-23 19:03:16 +0900108using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900109using namespace android::hardware::configstore::V1_0;
Peiyong Linfd997e02018-03-28 15:29:00 -0700110using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700111using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700112using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700113using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900114
Steven Thomasb02664d2017-07-26 18:48:28 -0700115namespace {
Chia-I Wu82144eb2018-08-24 15:34:02 -0700116
117#pragma clang diagnostic push
118#pragma clang diagnostic error "-Wswitch-enum"
119
120Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
121 switch (rotation) {
122 case ISurfaceComposer::eRotateNone:
123 return Transform::ROT_0;
124 case ISurfaceComposer::eRotate90:
125 return Transform::ROT_90;
126 case ISurfaceComposer::eRotate180:
127 return Transform::ROT_180;
128 case ISurfaceComposer::eRotate270:
129 return Transform::ROT_270;
130 }
131 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
132 return Transform::ROT_0;
133}
134
135#pragma clang diagnostic pop
136
Steven Thomasb02664d2017-07-26 18:48:28 -0700137class ConditionalLock {
138public:
139 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
140 if (lock) {
141 mMutex.lock();
142 }
143 }
144 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
145private:
146 Mutex& mMutex;
147 bool mLocked;
148};
149} // namespace anonymous
150
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800151// ---------------------------------------------------------------------------
152
Mathias Agopian99b49842011-06-27 16:05:52 -0700153const String16 sHardwareTest("android.permission.HARDWARE_TEST");
154const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
155const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
156const String16 sDump("android.permission.DUMP");
157
158// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800159int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
160int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700161int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700162bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800163uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800164bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800165bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800166int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800167// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600168bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wud63fd942018-08-27 14:38:14 -0700169int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Kalle Raitaa099a242017-01-11 11:17:29 -0800170
171std::string getHwcServiceName() {
172 char value[PROPERTY_VALUE_MAX] = {};
173 property_get("debug.sf.hwc_service_name", value, "default");
174 ALOGI("Using HWComposer service: '%s'", value);
175 return std::string(value);
176}
177
178bool useTrebleTestingOverride() {
179 char value[PROPERTY_VALUE_MAX] = {};
180 property_get("debug.sf.treble_testing_override", value, "false");
181 ALOGI("Treble testing override: '%s'", value);
182 return std::string(value) == "true";
183}
184
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800185std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
186 switch(displayColorSetting) {
187 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700188 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800189 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700190 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800191 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700192 return std::string("Enhanced");
193 default:
194 return std::string("Unknown ") +
195 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800196 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800197}
198
Lloyd Pique09594832018-01-22 17:48:03 -0800199NativeWindowSurface::~NativeWindowSurface() = default;
200
201namespace impl {
202
203class NativeWindowSurface final : public android::NativeWindowSurface {
204public:
205 static std::unique_ptr<android::NativeWindowSurface> create(
206 const sp<IGraphicBufferProducer>& producer) {
207 return std::make_unique<NativeWindowSurface>(producer);
208 }
209
210 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
211 : surface(new Surface(producer, false)) {}
212
213 ~NativeWindowSurface() override = default;
214
215private:
216 sp<ANativeWindow> getNativeWindow() const override { return surface; }
217
218 void preallocateBuffers() override { surface->allocateBuffers(); }
219
220 sp<Surface> surface;
221};
222
223} // namespace impl
224
David Sodmanbc815282017-11-05 18:57:52 -0800225SurfaceFlingerBE::SurfaceFlingerBE()
226 : mHwcServiceName(getHwcServiceName()),
227 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800228 mFrameBuckets(),
229 mTotalTime(0),
230 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800231 mComposerSequenceId(0) {
232}
233
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800234SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800235 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800236 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700237 mTransactionPending(false),
238 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700239 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700240 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700241 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800242 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800243 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800244 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800245 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800246 mAnimCompositionPending(false),
Chia-I Wuad8d8272018-06-26 10:18:18 +0800247 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800248 mDebugRegion(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700249 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700250 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700251 mDebugInSwapBuffers(0),
252 mLastSwapBufferTime(0),
253 mDebugInTransaction(0),
254 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700255 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000256 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700257 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700258 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800259 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800260 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700261 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800262 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique09594832018-01-22 17:48:03 -0800263 mCreateBufferQueue(&BufferQueue::createBufferQueue),
264 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800265
266SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800267 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800268
269 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
270 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
271
272 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
273 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
274
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800275 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
276 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800277
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700278 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
279 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
280
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700281 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
282 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
283
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800284 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
285 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
286
Steven Thomas050b2c82017-03-06 11:45:16 -0800287 // Vr flinger is only enabled on Daydream ready devices.
288 useVrFlinger = getBool< ISurfaceFlingerConfigs,
289 &ISurfaceFlingerConfigs::useVrFlinger>(false);
290
Fabien Sanglard1971b632017-03-10 14:50:03 -0800291 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
292 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
293
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600294 hasWideColorDisplay =
295 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
296
Iris Chang7501ed62018-04-30 14:45:42 +0800297 V1_1::DisplayOrientation primaryDisplayOrientation =
298 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
299 V1_1::DisplayOrientation::ORIENTATION_0);
300
301 switch (primaryDisplayOrientation) {
302 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wud63fd942018-08-27 14:38:14 -0700303 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800304 break;
305 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wud63fd942018-08-27 14:38:14 -0700306 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800307 break;
308 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wud63fd942018-08-27 14:38:14 -0700309 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800310 break;
311 default:
Chia-I Wud63fd942018-08-27 14:38:14 -0700312 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800313 break;
314 }
Chia-I Wud63fd942018-08-27 14:38:14 -0700315 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800316
David Sodman99974d22017-11-28 12:04:33 -0800317 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700318
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800319 // debugging stuff...
320 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700321
Mathias Agopianb4b17302013-03-20 18:36:41 -0700322 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700323 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700324
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800325 property_get("debug.sf.showupdates", value, "0");
326 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700327
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700328 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodsonfb996e92019-02-04 09:36:10 +0000329
330 // DDMS debugging deprecated (b/120782499)
331 property_get("debug.sf.ddms", value, "0");
332 int debugDdms = atoi(value);
333 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700334
335 property_get("debug.sf.disable_backpressure", value, "0");
336 mPropagateBackpressure = !atoi(value);
337 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700338
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800339 property_get("debug.sf.enable_hwc_vds", value, "0");
340 mUseHwcVirtualDisplays = atoi(value);
341 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800342
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800343 property_get("ro.sf.disable_triple_buffer", value, "1");
344 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800345 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700346
Yiwei Zhang243b3782018-05-15 17:40:04 -0700347 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700348 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
349 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
350
Jorim Jaggie203e042018-06-19 15:57:08 +0200351 property_get("debug.sf.early_phase_offset_ns", value, "-1");
352 const int earlySfOffsetNs = atoi(value);
353
354 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
355 const int earlyGlSfOffsetNs = atoi(value);
356
357 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
358 const int earlyAppOffsetNs = atoi(value);
359
360 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
361 const int earlyGlAppOffsetNs = atoi(value);
362
363 const VSyncModulator::Offsets earlyOffsets =
364 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
365 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
366 const VSyncModulator::Offsets earlyGlOffsets =
367 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
368 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
369 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
370 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza2713c302018-03-28 17:07:36 -0700371
Romain Guy11d63f42017-07-20 12:47:14 -0700372 // We should be reading 'persist.sys.sf.color_saturation' here
373 // but since /data may be encrypted, we need to wait until after vold
374 // comes online to attempt to read the property. The property is
375 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800376
377 if (useTrebleTestingOverride()) {
378 // Without the override SurfaceFlinger cannot connect to HIDL
379 // services that are not listed in the manifests. Considered
380 // deriving the setting from the set service name, but it
381 // would be brittle if the name that's not 'default' is used
382 // for production purposes later on.
383 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
384 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800385}
386
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800387void SurfaceFlinger::onFirstRef()
388{
Lloyd Pique9123ae52018-01-22 17:14:00 -0800389 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800390}
391
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800392SurfaceFlinger::~SurfaceFlinger()
393{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800394}
395
Dan Stozac7014012014-02-14 15:03:43 -0800396void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800397{
398 // the window manager died on us. prepare its eulogy.
399
Andy McFadden13a082e2012-08-24 10:16:42 -0700400 // restore initial conditions (default device unblank, etc)
401 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800402
403 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700404 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800405}
406
Robert Carr1db73f62016-12-21 12:58:51 -0800407static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700408 status_t err = client->initCheck();
409 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800410 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800411 }
Robert Carr1db73f62016-12-21 12:58:51 -0800412 return nullptr;
413}
414
415sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
416 return initClient(new Client(this));
417}
418
419sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
420 const sp<IGraphicBufferProducer>& gbp) {
421 if (authenticateSurfaceTexture(gbp) == false) {
422 return nullptr;
423 }
424 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
425 if (layer == nullptr) {
426 return nullptr;
427 }
428
429 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800430}
431
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700432sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
433 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700434{
435 class DisplayToken : public BBinder {
436 sp<SurfaceFlinger> flinger;
437 virtual ~DisplayToken() {
438 // no more references, this display must be terminated
439 Mutex::Autolock _l(flinger->mStateLock);
440 flinger->mCurrentState.displays.removeItem(this);
441 flinger->setTransactionFlags(eDisplayTransactionNeeded);
442 }
443 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700444 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700445 : flinger(flinger) {
446 }
447 };
448
449 sp<BBinder> token = new DisplayToken(this);
450
451 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700452 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700453 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700454 mCurrentState.displays.add(token, info);
Lloyd Pique4d234852018-01-22 17:21:36 -0800455 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700456 return token;
457}
458
Jesse Hall6c913be2013-08-08 12:15:49 -0700459void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
460 Mutex::Autolock _l(mStateLock);
461
462 ssize_t idx = mCurrentState.displays.indexOfKey(display);
463 if (idx < 0) {
464 ALOGW("destroyDisplay: invalid display token");
465 return;
466 }
467
468 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
469 if (!info.isVirtualDisplay()) {
470 ALOGE("destroyDisplay called for non-virtual display");
471 return;
472 }
Lloyd Pique4d234852018-01-22 17:21:36 -0800473 mInterceptor->saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700474 mCurrentState.displays.removeItemsAt(idx);
475 setTransactionFlags(eDisplayTransactionNeeded);
476}
477
Mathias Agopiane57f2922012-08-09 16:29:12 -0700478sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700479 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700480 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800481 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700482 }
Jesse Hall692c7232012-11-08 15:41:56 -0800483 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700484}
485
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800486void SurfaceFlinger::bootFinished()
487{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700488 if (mStartPropertySetThread->join() != NO_ERROR) {
489 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800490 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800491 const nsecs_t now = systemTime();
492 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000493 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700494
495 // wait patiently for the window manager death
496 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700497 mWindowManager = defaultServiceManager()->getService(name);
498 if (mWindowManager != 0) {
499 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700500 }
501
Steven Thomas050b2c82017-03-06 11:45:16 -0800502 if (mVrFlinger) {
503 mVrFlinger->OnBootFinished();
504 }
505
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700506 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700507 // formerly we would just kill the process, but we now ask it to exit so it
508 // can choose where to stop the animation.
509 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700510
511 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
512 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
513 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700514
Thierry Strudel2924d012017-08-14 15:19:37 -0700515 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700516 readPersistentProperties();
Chia-I Wuad8d8272018-06-26 10:18:18 +0800517 mBootStage = BootStage::FINISHED;
Romain Guy11d63f42017-07-20 12:47:14 -0700518 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700519 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800520}
521
Dan Stoza9fdb7e02018-06-21 12:10:12 -0700522uint32_t SurfaceFlinger::getNewTexture() {
523 {
524 std::lock_guard lock(mTexturePoolMutex);
525 if (!mTexturePool.empty()) {
526 uint32_t name = mTexturePool.back();
527 mTexturePool.pop_back();
528 ATRACE_INT("TexturePoolSize", mTexturePool.size());
529 return name;
530 }
531
532 // The pool was too small, so increase it for the future
533 ++mTexturePoolSize;
534 }
535
536 // The pool was empty, so we need to get a new texture name directly using a
537 // blocking call to the main thread
538 uint32_t name = 0;
539 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
540 return name;
541}
542
Mathias Agopian3f844832013-08-07 21:24:32 -0700543void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700544 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800545 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700546 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700547 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800548 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
549 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700550 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700551 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700552 return true;
553 }
554 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700555 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700556}
557
Lloyd Piquee83f9312018-02-01 12:53:17 -0800558class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700559public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700560 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000561 const char* name) :
562 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700563 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700564 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000565 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
566 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700567 mDispSync(dispSync),
568 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700569 mVsyncMutex(),
570 mPhaseOffset(phaseOffset),
571 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700572
Lloyd Piquee83f9312018-02-01 12:53:17 -0800573 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700574
Lloyd Piquee83f9312018-02-01 12:53:17 -0800575 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700576 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700577 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000578 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700579 static_cast<DispSync::Callback*>(this));
580 if (err != NO_ERROR) {
581 ALOGE("error registering vsync callback: %s (%d)",
582 strerror(-err), err);
583 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700584 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700585 } else {
586 status_t err = mDispSync->removeEventListener(
587 static_cast<DispSync::Callback*>(this));
588 if (err != NO_ERROR) {
589 ALOGE("error unregistering vsync callback: %s (%d)",
590 strerror(-err), err);
591 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700592 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700593 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700594 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700595 }
596
Lloyd Piquee83f9312018-02-01 12:53:17 -0800597 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700598 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700599 mCallback = callback;
600 }
601
Lloyd Piquee83f9312018-02-01 12:53:17 -0800602 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700603 Mutex::Autolock lock(mVsyncMutex);
604
605 // Normalize phaseOffset to [0, period)
606 auto period = mDispSync->getPeriod();
607 phaseOffset %= period;
608 if (phaseOffset < 0) {
609 // If we're here, then phaseOffset is in (-period, 0). After this
610 // operation, it will be in (0, period)
611 phaseOffset += period;
612 }
613 mPhaseOffset = phaseOffset;
614
615 // If we're not enabled, we don't need to mess with the listeners
616 if (!mEnabled) {
617 return;
618 }
619
Dan Stoza2713c302018-03-28 17:07:36 -0700620 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
621 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700622 if (err != NO_ERROR) {
Dan Stoza2713c302018-03-28 17:07:36 -0700623 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700624 strerror(-err), err);
625 }
626 }
627
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700628private:
629 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800630 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700631 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700632 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700633 callback = mCallback;
634
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700635 if (mTraceVsync) {
636 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700637 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700638 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700639 }
640
Peiyong Lin566a3b42018-01-09 18:22:43 -0800641 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700642 callback->onVSyncEvent(when);
643 }
644 }
645
Tim Murray4a4e4a22016-04-19 16:29:23 +0000646 const char* const mName;
647
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700648 int mValue;
649
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700650 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700651 const String8 mVsyncOnLabel;
652 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700653
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700654 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700655
656 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800657 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700658
659 Mutex mVsyncMutex; // Protects the following
660 nsecs_t mPhaseOffset;
661 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700662};
663
Lloyd Piquee83f9312018-02-01 12:53:17 -0800664class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700665public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800666 InjectVSyncSource() = default;
667 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700668
Lloyd Piquee83f9312018-02-01 12:53:17 -0800669 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700670 std::lock_guard<std::mutex> lock(mCallbackMutex);
671 mCallback = callback;
672 }
673
Lloyd Piquee83f9312018-02-01 12:53:17 -0800674 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700675 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700676 if (mCallback) {
677 mCallback->onVSyncEvent(when);
678 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700679 }
680
Lloyd Piquee83f9312018-02-01 12:53:17 -0800681 void setVSyncEnabled(bool) override {}
682 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700683
684private:
685 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800686 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700687};
688
Wei Wangf9b05ee2017-07-19 20:59:39 -0700689// Do not call property_set on main thread which will be blocked by init
690// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700691void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700692 ALOGI( "SurfaceFlinger's main thread ready to run. "
693 "Initializing graphics H/W...");
694
Thierry Strudel2924d012017-08-14 15:19:37 -0700695 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900696
Steven Thomasb02664d2017-07-26 18:48:28 -0700697 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800698
Steven Thomasb02664d2017-07-26 18:48:28 -0700699 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800700 mEventThreadSource =
701 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
702 true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800703 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
704 [this]() { resyncWithRateLimit(); },
705 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800706 "appEventThread");
707 mSfEventThreadSource =
708 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
709 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800710
Lloyd Pique24b0a482018-03-09 18:52:26 -0800711 mSFEventThread =
712 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
713 [this]() { resyncWithRateLimit(); },
714 [this](nsecs_t timestamp) {
715 mInterceptor->saveVSyncEvent(timestamp);
716 },
717 "sfEventThread");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800718 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggie203e042018-06-19 15:57:08 +0200719 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800720
Steven Thomasb02664d2017-07-26 18:48:28 -0700721 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800722 getBE().mRenderEngine =
723 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
724 hasWideColorDisplay
725 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
726 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800727 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700728
729 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
730 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800731 getBE().mHwc.reset(
732 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700733 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800734 // Process any initial hotplug and resulting display changes.
735 processDisplayHotplugEventsLocked();
736 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
737 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800738
Lloyd Piquefcd86612017-12-14 17:15:36 -0800739 // make the default display GLContext current so that we can create textures
740 // when creating Layers (which may happens before we render something)
741 getDefaultDisplayDeviceLocked()->makeCurrent();
742
Steven Thomas050b2c82017-03-06 11:45:16 -0800743 if (useVrFlinger) {
744 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700745 // This callback is called from the vr flinger dispatch thread. We
746 // need to call signalTransaction(), which requires holding
747 // mStateLock when we're not on the main thread. Acquiring
748 // mStateLock from the vr flinger dispatch thread might trigger a
749 // deadlock in surface flinger (see b/66916578), so post a message
750 // to be handled on the main thread instead.
751 sp<LambdaMessage> message = new LambdaMessage([=]() {
752 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
753 mVrFlingerRequestsDisplay = requestDisplay;
754 signalTransaction();
755 });
756 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800757 };
David Sodman105b7dc2017-11-04 20:28:14 -0700758 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
759 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800760 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800761 if (!mVrFlinger) {
762 ALOGE("Failed to start vrflinger");
763 }
764 }
765
Lloyd Pique0c3a8832018-01-22 17:31:47 -0800766 mEventControlThread = std::make_unique<impl::EventControlThread>(
767 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700768
Mathias Agopian92a979a2012-08-02 18:32:23 -0700769 // initialize our drawing state
770 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700771
Andy McFadden13a082e2012-08-24 10:16:42 -0700772 // set initial conditions (e.g. unblank default device)
773 initializeDisplays();
774
David Sodmanbc815282017-11-05 18:57:52 -0800775 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700776
Wei Wangf9b05ee2017-07-19 20:59:39 -0700777 // Inform native graphics APIs whether the present timestamp is supported:
778 if (getHwComposer().hasCapability(
779 HWC2::Capability::PresentFenceIsNotReliable)) {
780 mStartPropertySetThread = new StartPropertySetThread(false);
781 } else {
782 mStartPropertySetThread = new StartPropertySetThread(true);
783 }
784
785 if (mStartPropertySetThread->Start() != NO_ERROR) {
786 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800787 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800788
Chia-I Wu6d844112018-06-27 07:17:41 +0800789 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
790 // is used to saturate legacy sRGB content. However, to make sure the same color under
791 // Display P3 will be saturated to the same color, we intentionally break the API spec
792 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
793 // such saturation matrix on Display P3 is understood fully, the API should always return
794 // identify matrix.
795 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800796 Dataspace::SRGB_LINEAR);
797
Chia-I Wu6d844112018-06-27 07:17:41 +0800798 // we will apply this on Display P3.
799 if (mEnhancedSaturationMatrix != mat4()) {
800 ColorSpace srgb(ColorSpace::sRGB());
801 ColorSpace displayP3(ColorSpace::DisplayP3());
802 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
803 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
804 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
805 }
806
Dan Stoza9e56aa02015-11-02 13:00:03 -0800807 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700808}
809
Romain Guy11d63f42017-07-20 12:47:14 -0700810void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700811 Mutex::Autolock _l(mStateLock);
812
Romain Guy11d63f42017-07-20 12:47:14 -0700813 char value[PROPERTY_VALUE_MAX];
814
815 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800816 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700817 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800818 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100819
820 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700821 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700822}
823
Mathias Agopiana67e4182012-06-19 17:26:12 -0700824void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800825 // Start boot animation service by setting a property mailbox
826 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700827 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800828 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700829 if (mStartPropertySetThread->join() != NO_ERROR) {
830 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800831 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700832}
833
Mathias Agopian875d8e12013-06-07 15:35:48 -0700834size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800835 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700836}
837
Mathias Agopian875d8e12013-06-07 15:35:48 -0700838size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800839 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700840}
841
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800842// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800843
Jamie Gennis582270d2011-08-17 18:19:00 -0700844bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800845 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800846 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800847 return authenticateSurfaceTextureLocked(bufferProducer);
848}
849
850bool SurfaceFlinger::authenticateSurfaceTextureLocked(
851 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800852 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800853 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800854}
855
Brian Anderson6b376712017-04-04 10:51:39 -0700856status_t SurfaceFlinger::getSupportedFrameTimestamps(
857 std::vector<FrameEvent>* outSupported) const {
858 *outSupported = {
859 FrameEvent::REQUESTED_PRESENT,
860 FrameEvent::ACQUIRE,
861 FrameEvent::LATCH,
862 FrameEvent::FIRST_REFRESH_START,
863 FrameEvent::LAST_REFRESH_START,
864 FrameEvent::GPU_COMPOSITION_DONE,
865 FrameEvent::DEQUEUE_READY,
866 FrameEvent::RELEASE,
867 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700868 ConditionalLock _l(mStateLock,
869 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700870 if (!getHwComposer().hasCapability(
871 HWC2::Capability::PresentFenceIsNotReliable)) {
872 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
873 }
874 return NO_ERROR;
875}
876
Dan Stoza7f7da322014-05-02 15:26:25 -0700877status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
878 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800879 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700880 return BAD_VALUE;
881 }
882
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500883 if (!display.get())
884 return NAME_NOT_FOUND;
885
Jesse Hall692c7232012-11-08 15:41:56 -0800886 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700887 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800888 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700889 type = i;
890 break;
891 }
892 }
893
894 if (type < 0) {
895 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700896 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700897
Mathias Agopian8b736f12012-08-13 17:54:26 -0700898 // TODO: Not sure if display density should handled by SF any longer
899 class Density {
900 static int getDensityFromProperty(char const* propName) {
901 char property[PROPERTY_VALUE_MAX];
902 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800903 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700904 density = atoi(property);
905 }
906 return density;
907 }
908 public:
909 static int getEmuDensity() {
910 return getDensityFromProperty("qemu.sf.lcd_density"); }
911 static int getBuildDensity() {
912 return getDensityFromProperty("ro.sf.lcd_density"); }
913 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700914
Dan Stoza7f7da322014-05-02 15:26:25 -0700915 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700916
Steven Thomas6d8110b2017-08-31 18:24:21 -0700917 ConditionalLock _l(mStateLock,
918 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800919 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700920 DisplayInfo info = DisplayInfo();
921
Dan Stoza9e56aa02015-11-02 13:00:03 -0800922 float xdpi = hwConfig->getDpiX();
923 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700924
925 if (type == DisplayDevice::DISPLAY_PRIMARY) {
926 // The density of the device is provided by a build property
927 float density = Density::getBuildDensity() / 160.0f;
928 if (density == 0) {
929 // the build doesn't provide a density -- this is wrong!
930 // use xdpi instead
931 ALOGE("ro.sf.lcd_density must be defined as a build property");
932 density = xdpi / 160.0f;
933 }
934 if (Density::getEmuDensity()) {
935 // if "qemu.sf.lcd_density" is specified, it overrides everything
936 xdpi = ydpi = density = Density::getEmuDensity();
937 density /= 160.0f;
938 }
939 info.density = density;
940
941 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700942 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800943 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700944 } else {
945 // TODO: where should this value come from?
946 static const int TV_DENSITY = 213;
947 info.density = TV_DENSITY / 160.0f;
948 info.orientation = 0;
949 }
950
Dan Stoza9e56aa02015-11-02 13:00:03 -0800951 info.w = hwConfig->getWidth();
952 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700953 info.xdpi = xdpi;
954 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800955 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900956 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800957
Andy McFadden91b2ca82014-06-13 14:04:23 -0700958 // This is how far in advance a buffer must be queued for
959 // presentation at a given time. If you want a buffer to appear
960 // on the screen at time N, you must submit the buffer before
961 // (N - presentationDeadline).
962 //
963 // Normally it's one full refresh period (to give SF a chance to
964 // latch the buffer), but this can be reduced by configuring a
965 // DispSync offset. Any additional delays introduced by the hardware
966 // composer or panel must be accounted for here.
967 //
968 // We add an additional 1ms to allow for processing time and
969 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800970 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800971 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700972
973 // All non-virtual displays are currently considered secure.
974 info.secure = true;
975
Iris Chang7501ed62018-04-30 14:45:42 +0800976 if (type == DisplayDevice::DISPLAY_PRIMARY &&
Chia-I Wud63fd942018-08-27 14:38:14 -0700977 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800978 std::swap(info.w, info.h);
979 }
980
Michael Wright28f24d02016-07-12 13:30:53 -0700981 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700982 }
983
Dan Stoza7f7da322014-05-02 15:26:25 -0700984 return NO_ERROR;
985}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700986
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800987status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700988 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800989 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700990 return BAD_VALUE;
991 }
992
993 // FIXME for now we always return stats for the primary display
994 memset(stats, 0, sizeof(*stats));
995 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
996 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
997 return NO_ERROR;
998}
999
Yiwei Zhang1d465af2018-08-21 15:15:42 -07001000status_t SurfaceFlinger::getDisplayViewport(const sp<IBinder>& display, Rect* outViewport) {
1001 if (outViewport == nullptr || display.get() == nullptr) {
1002 return BAD_VALUE;
1003 }
1004
1005 sp<const DisplayDevice> device(getDisplayDevice(display));
1006 if (device == nullptr) {
1007 return BAD_VALUE;
1008 }
1009
1010 *outViewport = device->getViewport();
1011
1012 return NO_ERROR;
1013}
1014
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001015int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08001016 if (display == nullptr) {
1017 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +08001018 return BAD_VALUE;
1019 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001020
1021 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -08001022 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -07001023 return device->getActiveConfig();
1024 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001025
Dan Stoza24a42e92015-03-09 10:04:11 -07001026 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -07001027}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001028
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001029void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
1030 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
1031 this);
1032 int32_t type = hw->getDisplayType();
1033 int currentMode = hw->getActiveConfig();
1034
1035 if (mode == currentMode) {
1036 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
1037 return;
1038 }
1039
1040 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1041 ALOGW("Trying to set config for virtual display");
1042 return;
1043 }
1044
1045 hw->setActiveConfig(mode);
1046 getHwComposer().setActiveConfig(type, mode);
1047}
1048
1049status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
1050 class MessageSetActiveConfig: public MessageBase {
1051 SurfaceFlinger& mFlinger;
1052 sp<IBinder> mDisplay;
1053 int mMode;
1054 public:
1055 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
1056 int mode) :
1057 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1058 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -07001059 Vector<DisplayInfo> configs;
1060 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -07001061 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -07001062 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -07001063 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -07001064 return true;
Michael Lentine7306c672014-07-30 13:00:37 -07001065 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001066 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08001067 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001068 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07001069 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001070 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
1071 ALOGW("Attempt to set active config = %d for virtual display",
1072 mMode);
1073 } else {
1074 mFlinger.setActiveConfigInternal(hw, mMode);
1075 }
1076 return true;
1077 }
1078 };
1079 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
1080 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -07001081 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001082}
Michael Wright28f24d02016-07-12 13:30:53 -07001083status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001084 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001085 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
1086 return BAD_VALUE;
1087 }
1088
1089 if (!display.get()) {
1090 return NAME_NOT_FOUND;
1091 }
1092
1093 int32_t type = NAME_NOT_FOUND;
1094 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
1095 if (display == mBuiltinDisplays[i]) {
1096 type = i;
1097 break;
1098 }
1099 }
1100
1101 if (type < 0) {
1102 return type;
1103 }
1104
Peiyong Lina52f0292018-03-14 17:26:31 -07001105 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001106 {
1107 ConditionalLock _l(mStateLock,
1108 std::this_thread::get_id() != mMainThreadId);
1109 modes = getHwComposer().getColorModes(type);
1110 }
Michael Wright28f24d02016-07-12 13:30:53 -07001111 outColorModes->clear();
1112 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1113
1114 return NO_ERROR;
1115}
1116
Peiyong Lina52f0292018-03-14 17:26:31 -07001117ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001118 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -07001119 if (device != nullptr) {
1120 return device->getActiveColorMode();
1121 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001122 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001123}
1124
1125void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001126 ColorMode mode, Dataspace dataSpace,
1127 RenderIntent renderIntent) {
Michael Wright28f24d02016-07-12 13:30:53 -07001128 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -07001129 ColorMode currentMode = hw->getActiveColorMode();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001130 Dataspace currentDataSpace = hw->getCompositionDataSpace();
Peiyong Lin38e9a562018-04-10 16:24:20 -07001131 RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001132
Peiyong Lin38e9a562018-04-10 16:24:20 -07001133 if (mode == currentMode && dataSpace == currentDataSpace &&
1134 renderIntent == currentRenderIntent) {
1135 return;
1136 }
1137
1138 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1139 ALOGW("Trying to set config for virtual display");
1140 return;
1141 }
1142
1143 hw->setActiveColorMode(mode);
1144 hw->setCompositionDataSpace(dataSpace);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001145 hw->setActiveRenderIntent(renderIntent);
1146 getHwComposer().setActiveColorMode(type, mode, renderIntent);
1147
1148 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1149 decodeColorMode(mode).c_str(), mode,
1150 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1151 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001152}
1153
1154
1155status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001156 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001157 class MessageSetActiveColorMode: public MessageBase {
1158 SurfaceFlinger& mFlinger;
1159 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001160 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001161 public:
1162 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001163 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001164 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1165 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001166 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001167 mFlinger.getDisplayColorModes(mDisplay, &modes);
1168 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001169 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001170 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1171 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001172 return true;
1173 }
1174 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1175 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001176 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1177 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001178 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001179 ALOGW("Attempt to set active color mode %s %d for virtual display",
1180 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001181 } else {
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001182 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN,
1183 RenderIntent::COLORIMETRIC);
Michael Wright28f24d02016-07-12 13:30:53 -07001184 }
1185 return true;
1186 }
1187 };
1188 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1189 postMessageSync(msg);
1190 return NO_ERROR;
1191}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001192
Svetoslavd85084b2014-03-20 10:28:31 -07001193status_t SurfaceFlinger::clearAnimationFrameStats() {
1194 Mutex::Autolock _l(mStateLock);
1195 mAnimFrameTracker.clearStats();
1196 return NO_ERROR;
1197}
1198
1199status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1200 Mutex::Autolock _l(mStateLock);
1201 mAnimFrameTracker.getStats(outStats);
1202 return NO_ERROR;
1203}
1204
Dan Stozac4f471e2016-03-24 09:31:08 -07001205status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1206 HdrCapabilities* outCapabilities) const {
1207 Mutex::Autolock _l(mStateLock);
1208
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001209 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001210 if (displayDevice == nullptr) {
1211 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1212 return BAD_VALUE;
1213 }
1214
Peiyong Linfb069302018-04-25 14:34:31 -07001215 // At this point the DisplayDeivce should already be set up,
1216 // meaning the luminance information is already queried from
1217 // hardware composer and stored properly.
1218 const HdrCapabilities& capabilities = displayDevice->getHdrCapabilities();
1219 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1220 capabilities.getDesiredMaxLuminance(),
1221 capabilities.getDesiredMaxAverageLuminance(),
1222 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001223
1224 return NO_ERROR;
1225}
1226
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001227status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001228 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1229 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001230
Chia-I Wu90f669f2017-10-05 14:24:41 -07001231 if (mInjectVSyncs == enable) {
1232 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001233 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001234
1235 if (enable) {
1236 ALOGV("VSync Injections enabled");
1237 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001238 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001239 mInjectorEventThread = std::make_unique<
1240 impl::EventThread>(mVSyncInjector.get(),
1241 [this]() { resyncWithRateLimit(); },
1242 impl::EventThread::InterceptVSyncsCallback(),
1243 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001244 }
Lloyd Pique9123ae52018-01-22 17:14:00 -08001245 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001246 } else {
1247 ALOGV("VSync Injections disabled");
Lloyd Pique9123ae52018-01-22 17:14:00 -08001248 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001249 }
1250
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001251 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001252 });
1253 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001254 return NO_ERROR;
1255}
1256
1257status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001258 Mutex::Autolock _l(mStateLock);
1259
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001260 if (!mInjectVSyncs) {
1261 ALOGE("VSync Injections not enabled");
1262 return BAD_VALUE;
1263 }
1264 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1265 ALOGV("Injecting VSync inside SurfaceFlinger");
1266 mVSyncInjector->onInjectSyncEvent(when);
1267 }
1268 return NO_ERROR;
1269}
1270
Lloyd Pique755e3192018-01-31 16:46:15 -08001271status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1272 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001273 IPCThreadState* ipc = IPCThreadState::self();
1274 const int pid = ipc->getCallingPid();
1275 const int uid = ipc->getCallingUid();
1276 if ((uid != AID_SHELL) &&
1277 !PermissionCache::checkPermission(sDump, pid, uid)) {
1278 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1279 return PERMISSION_DENIED;
1280 }
1281
1282 // Try to acquire a lock for 1s, fail gracefully
1283 const status_t err = mStateLock.timedLock(s2ns(1));
1284 const bool locked = (err == NO_ERROR);
1285 if (!locked) {
1286 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1287 return TIMED_OUT;
1288 }
1289
1290 outLayers->clear();
1291 mCurrentState.traverseInZOrder([&](Layer* layer) {
1292 outLayers->push_back(layer->getLayerDebugInfo());
1293 });
1294
1295 mStateLock.unlock();
1296 return NO_ERROR;
1297}
1298
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001299// ----------------------------------------------------------------------------
1300
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001301sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1302 ISurfaceComposer::VsyncSource vsyncSource) {
1303 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1304 return mSFEventThread->createEventConnection();
1305 } else {
1306 return mEventThread->createEventConnection();
1307 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001308}
1309
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001310// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001311
1312void SurfaceFlinger::waitForEvent() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001313 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001314}
1315
1316void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001317 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001318}
1319
1320void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001321 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001322}
1323
1324void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001325 mRefreshPending = true;
Lloyd Pique9123ae52018-01-22 17:14:00 -08001326 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001327}
1328
1329status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001330 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001331 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001332}
1333
1334status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001335 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001336 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001337 if (res == NO_ERROR) {
1338 msg->wait();
1339 }
1340 return res;
1341}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001342
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001343void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001344 do {
1345 waitForEvent();
1346 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001347}
1348
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001349void SurfaceFlinger::enableHardwareVsync() {
1350 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001351 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001352 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001353 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1354 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001355 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001356 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001357}
1358
Jesse Hall948fe0c2013-10-14 12:56:09 -07001359void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001360 Mutex::Autolock _l(mHWVsyncLock);
1361
Jesse Hall948fe0c2013-10-14 12:56:09 -07001362 if (makeAvailable) {
1363 mHWVsyncAvailable = true;
1364 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001365 // Hardware vsync is not currently available, so abort the resync
1366 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001367 return;
1368 }
1369
David Sodman105b7dc2017-11-04 20:28:14 -07001370 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001371 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001372
1373 mPrimaryDispSync.reset();
1374 mPrimaryDispSync.setPeriod(period);
1375
1376 if (!mPrimaryHWVsyncEnabled) {
1377 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001378 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1379 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001380 mPrimaryHWVsyncEnabled = true;
1381 }
1382}
1383
Jesse Hall948fe0c2013-10-14 12:56:09 -07001384void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001385 Mutex::Autolock _l(mHWVsyncLock);
1386 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001387 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1388 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001389 mPrimaryDispSync.endResync();
1390 mPrimaryHWVsyncEnabled = false;
1391 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001392 if (makeUnavailable) {
1393 mHWVsyncAvailable = false;
1394 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001395}
1396
Tim Murray4a4e4a22016-04-19 16:29:23 +00001397void SurfaceFlinger::resyncWithRateLimit() {
1398 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001399
1400 // No explicit locking is needed here since EventThread holds a lock while calling this method
1401 static nsecs_t sLastResyncAttempted = 0;
1402 const nsecs_t now = systemTime();
1403 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001404 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001405 }
Dan Stoza57164302017-05-08 14:03:54 -07001406 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001407}
1408
Steven Thomasb02664d2017-07-26 18:48:28 -07001409void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1410 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001411 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001412 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001413 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001414 return;
1415 }
1416
1417 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001418 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001419 return;
1420 }
1421
Jamie Gennisd1700752013-10-14 12:22:52 -07001422 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001423
Jamie Gennisd1700752013-10-14 12:22:52 -07001424 { // Scope for the lock
1425 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001426 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001427 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001428 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001429 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001430
1431 if (needsHwVsync) {
1432 enableHardwareVsync();
1433 } else {
1434 disableHardwareVsync(false);
1435 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001436}
1437
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001438void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001439 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1440 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001441}
1442
Lloyd Pique715a2c12017-12-14 17:18:08 -08001443void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1444 HWC2::Connection connection) {
1445 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1446 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001447
Lloyd Piqueba04e622017-12-14 17:11:26 -08001448 // Ignore events that do not have the right sequenceId.
1449 if (sequenceId != getBE().mComposerSequenceId) {
1450 return;
1451 }
1452
Steven Thomasb02664d2017-07-26 18:48:28 -07001453 // Only lock if we're not on the main thread. This function is normally
1454 // called on a hwbinder thread, but for the primary display it's called on
1455 // the main thread with the state lock already held, so don't attempt to
1456 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001457 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001458
Lloyd Pique715a2c12017-12-14 17:18:08 -08001459 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001460
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001461 if (std::this_thread::get_id() == mMainThreadId) {
1462 // Process all pending hot plug events immediately if we are on the main thread.
1463 processDisplayHotplugEventsLocked();
1464 }
1465
Lloyd Piqueba04e622017-12-14 17:11:26 -08001466 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001467}
1468
Steven Thomasb02664d2017-07-26 18:48:28 -07001469void SurfaceFlinger::onRefreshReceived(int sequenceId,
1470 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001471 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001472 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001473 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001474 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001475 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001476}
1477
Dan Stoza9e56aa02015-11-02 13:00:03 -08001478void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001479 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001480 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001481 getHwComposer().setVsyncEnabled(disp,
1482 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001483}
1484
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001485// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001486void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001487 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001488 // Clear the drawing state so that the logic inside of
1489 // handleTransactionLocked will fire. It will determine the delta between
1490 // mCurrentState and mDrawingState and re-apply all changes when we make the
1491 // transition.
1492 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001493 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001494 mDisplays.clear();
1495}
1496
Steven Thomas050b2c82017-03-06 11:45:16 -08001497void SurfaceFlinger::updateVrFlinger() {
1498 if (!mVrFlinger)
1499 return;
1500 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001501 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001502 return;
1503 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001504
David Sodman105b7dc2017-11-04 20:28:14 -07001505 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001506 ALOGE("Vr flinger is only supported for remote hardware composer"
1507 " service connections. Ignoring request to transition to vr"
1508 " flinger.");
1509 mVrFlingerRequestsDisplay = false;
1510 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001511 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001512
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001513 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001514
Steven Thomasb02664d2017-07-26 18:48:28 -07001515 int currentDisplayPowerMode = getDisplayDeviceLocked(
1516 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001517
Steven Thomasb02664d2017-07-26 18:48:28 -07001518 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001519 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001520 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001521
Steven Thomasb02664d2017-07-26 18:48:28 -07001522 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001523 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001524 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1525 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001526 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001527
David Sodman105b7dc2017-11-04 20:28:14 -07001528 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1529 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001530
1531 if (vrFlingerRequestsDisplay) {
1532 mVrFlinger->GrantDisplayOwnership();
1533 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001534 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001535 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001536
1537 mVisibleRegionsDirty = true;
1538 invalidateHwcGeometry();
1539
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001540 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001541 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1542 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1543 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001544
Steven Thomasb02664d2017-07-26 18:48:28 -07001545 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001546 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001547 const nsecs_t period = activeConfig->getVsyncPeriod();
1548 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001549
Steven Thomasb02664d2017-07-26 18:48:28 -07001550 // Use phase of 0 since phase is not known.
1551 // Use latency of 0, which will snap to the ideal latency.
1552 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001553
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001554 android_atomic_or(1, &mRepaintEverything);
1555 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001556}
1557
Mathias Agopian4fec8732012-06-29 14:12:52 -07001558void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001559 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001560 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001561 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001562 bool frameMissed = !mHadClientComposition &&
1563 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001564 (mPreviousPresentFence->getSignalTime() ==
1565 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001566 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001567 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001568 mTimeStats.incrementMissedFrames();
1569 if (mPropagateBackpressure) {
1570 signalLayerUpdate();
1571 break;
1572 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001573 }
Dan Stoza50182882016-07-08 12:02:20 -07001574
Steven Thomas050b2c82017-03-06 11:45:16 -08001575 // Now that we're going to make it to the handleMessageTransaction()
1576 // call below it's safe to call updateVrFlinger(), which will
1577 // potentially trigger a display handoff.
1578 updateVrFlinger();
1579
Dan Stoza6b9454d2014-11-07 16:00:59 -08001580 bool refreshNeeded = handleMessageTransaction();
1581 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001582 refreshNeeded |= mRepaintEverything;
Chia-I Wuad8d8272018-06-26 10:18:18 +08001583 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001584 // Signal a refresh if a transaction modified the window state,
1585 // a new buffer was latched, or if HWC has requested a full
1586 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001587 signalRefresh();
1588 }
1589 break;
1590 }
1591 case MessageQueue::REFRESH: {
1592 handleMessageRefresh();
1593 break;
1594 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001595 }
1596}
1597
Dan Stoza6b9454d2014-11-07 16:00:59 -08001598bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001599 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001600 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001601 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001602 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001603 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001604 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001605}
1606
Dan Stoza6b9454d2014-11-07 16:00:59 -08001607bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001608 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001609 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001610}
1611
1612void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001613 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001614
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001615 mRefreshPending = false;
1616
Pablo Ceballos40845df2016-01-25 17:41:15 -08001617 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001618
Brian Andersond6927fb2016-07-23 23:37:30 -07001619 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001620 rebuildLayerStacks();
1621 setUpHWComposer();
1622 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001623 doTracing("handleRefresh");
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001624 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001625 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001626 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001627
David Sodman105b7dc2017-11-04 20:28:14 -07001628 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001629
1630 mHadClientComposition = false;
1631 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1632 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1633 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001634 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001635 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001636 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001637
Dan Stoza9e56aa02015-11-02 13:00:03 -08001638 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001639}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001640
Mathias Agopiancd60f992012-08-16 16:28:27 -07001641void SurfaceFlinger::doDebugFlashRegions()
1642{
1643 // is debugging enabled
1644 if (CC_LIKELY(!mDebugRegion))
1645 return;
1646
1647 const bool repaintEverything = mRepaintEverything;
1648 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1649 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001650 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001651 // transform the dirty region into this screen's coordinate space
1652 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1653 if (!dirtyRegion.isEmpty()) {
1654 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001655 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001656
1657 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001658 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001659 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001660 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1661
Mathias Agopianda27af92012-09-13 18:17:13 -07001662 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001663 }
1664 }
1665 }
1666
1667 postFramebuffer();
1668
1669 if (mDebugRegion > 1) {
1670 usleep(mDebugRegion * 1000);
1671 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001672
Dan Stoza9e56aa02015-11-02 13:00:03 -08001673 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001674 auto& displayDevice = mDisplays[displayId];
1675 if (!displayDevice->isDisplayOn()) {
1676 continue;
1677 }
1678
David Sodman105b7dc2017-11-04 20:28:14 -07001679 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1680 ALOGE_IF(result != NO_ERROR,
1681 "prepareFrame for display %zd failed:"
1682 " %d (%s)",
1683 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001684 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001685}
1686
Adrian Roos1e1a1282017-11-01 19:05:31 +01001687void SurfaceFlinger::doTracing(const char* where) {
1688 ATRACE_CALL();
1689 ATRACE_NAME(where);
1690 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001691 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001692 }
1693}
1694
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001695void SurfaceFlinger::logLayerStats() {
1696 ATRACE_CALL();
1697 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1698 int32_t hwcId = -1;
1699 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1700 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1701 if (displayDevice->isPrimary()) {
1702 hwcId = displayDevice->getHwcDisplayId();
1703 break;
1704 }
1705 }
1706 if (hwcId < 0) {
1707 ALOGE("LayerStats: Hmmm, no primary display?");
1708 return;
1709 }
1710 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1711 }
1712}
1713
Brian Andersond6927fb2016-07-23 23:37:30 -07001714void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001715{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001716 ATRACE_CALL();
1717 ALOGV("preComposition");
1718
Mathias Agopiancd60f992012-08-16 16:28:27 -07001719 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001720 mDrawingState.traverseInZOrder([&](Layer* layer) {
1721 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001722 needExtraInvalidate = true;
1723 }
Robert Carr2047fae2016-11-28 14:09:09 -08001724 });
1725
Mathias Agopiancd60f992012-08-16 16:28:27 -07001726 if (needExtraInvalidate) {
1727 signalLayerUpdate();
1728 }
1729}
1730
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001731void SurfaceFlinger::updateCompositorTiming(
1732 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1733 std::shared_ptr<FenceTime>& presentFenceTime) {
1734 // Update queue of past composite+present times and determine the
1735 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001736 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001737 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001738 while (!getBE().mCompositePresentTimes.empty()) {
1739 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001740 // Cached values should have been updated before calling this method,
1741 // which helps avoid duplicate syscalls.
1742 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1743 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1744 break;
1745 }
1746 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001747 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001748 }
1749
1750 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001751 while (getBE().mCompositePresentTimes.size() > 16) {
1752 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001753 }
1754
Brian Andersond0010582017-03-07 13:20:31 -08001755 setCompositorTimingSnapped(
1756 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1757}
1758
1759void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1760 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001761 // Integer division and modulo round toward 0 not -inf, so we need to
1762 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001763 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001764 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1765 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1766
Brian Andersond0010582017-03-07 13:20:31 -08001767 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1768 if (idealLatency <= 0) {
1769 idealLatency = vsyncInterval;
1770 }
1771
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001772 // Snap the latency to a value that removes scheduling jitter from the
1773 // composition and present times, which often have >1ms of jitter.
1774 // Reducing jitter is important if an app attempts to extrapolate
1775 // something (such as user input) to an accurate diasplay time.
1776 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1777 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001778 nsecs_t bias = vsyncInterval / 2;
1779 int64_t extraVsyncs =
1780 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1781 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1782 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001783
David Sodman99974d22017-11-28 12:04:33 -08001784 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1785 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1786 getBE().mCompositorTiming.interval = vsyncInterval;
1787 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001788}
1789
1790void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001791{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001792 ATRACE_CALL();
1793 ALOGV("postComposition");
1794
Brian Anderson3546a3f2016-07-14 11:51:14 -07001795 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001796 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001797 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001798 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001799 }
1800
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001801 // |mStateLock| not needed as we are on the main thread
1802 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001803
David Sodman73beded2017-11-15 11:56:06 -08001804 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001805 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001806 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001807 glCompositionDoneFenceTime =
1808 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001809 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001810 } else {
1811 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1812 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001813
David Sodman73beded2017-11-15 11:56:06 -08001814 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001815 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001816 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001817 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001818
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001819 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1820 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1821
1822 // We use the refreshStartTime which might be sampled a little later than
1823 // when we started doing work for this frame, but that should be okay
1824 // since updateCompositorTiming has snapping logic.
1825 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001826 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001827 CompositorTiming compositorTiming;
1828 {
David Sodman99974d22017-11-28 12:04:33 -08001829 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1830 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001831 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001832
Robert Carr2047fae2016-11-28 14:09:09 -08001833 mDrawingState.traverseInZOrder([&](Layer* layer) {
1834 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001835 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001836 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001837 recordBufferingStats(layer->getName().string(),
1838 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001839 }
Robert Carr2047fae2016-11-28 14:09:09 -08001840 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001841
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001842 if (presentFenceTime->isValid()) {
1843 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001844 enableHardwareVsync();
1845 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001846 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001847 }
1848 }
1849
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001850 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001851 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001852 enableHardwareVsync();
1853 }
1854 }
1855
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001856 if (mAnimCompositionPending) {
1857 mAnimCompositionPending = false;
1858
Brian Anderson4e606e32017-03-16 15:34:57 -07001859 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001860 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001861 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001862 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001863 // The HWC doesn't support present fences, so use the refresh
1864 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001865 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001866 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001867 mAnimFrameTracker.setActualPresentTime(presentTime);
1868 }
1869 mAnimFrameTracker.advanceFrame();
1870 }
Dan Stozab90cf072015-03-05 11:05:59 -08001871
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001872 mTimeStats.incrementTotalFrames();
1873 if (mHadClientComposition) {
1874 mTimeStats.incrementClientCompositionFrames();
1875 }
1876
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001877 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1878 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001879 return;
1880 }
1881
1882 nsecs_t currentTime = systemTime();
1883 if (mHasPoweredOff) {
1884 mHasPoweredOff = false;
1885 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001886 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001887 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001888 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1889 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001890 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001891 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001892 }
David Sodman4a36e932017-11-07 14:29:47 -08001893 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001894 }
David Sodman4a36e932017-11-07 14:29:47 -08001895 getBE().mLastSwapTime = currentTime;
Dan Stoza9fdb7e02018-06-21 12:10:12 -07001896
1897 {
1898 std::lock_guard lock(mTexturePoolMutex);
1899 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1900 if (refillCount > 0) {
1901 const size_t offset = mTexturePool.size();
1902 mTexturePool.resize(mTexturePoolSize);
1903 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1904 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1905 }
1906 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001907}
1908
1909void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001910 ATRACE_CALL();
1911 ALOGV("rebuildLayerStacks");
1912
Mathias Agopiancd60f992012-08-16 16:28:27 -07001913 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001914 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001915 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001916 mVisibleRegionsDirty = false;
1917 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001918
Jeff Sharkey76488112017-02-27 14:15:18 -07001919 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1920 Region opaqueRegion;
1921 Region dirtyRegion;
1922 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001923 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001924 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1925 const Transform& tr(displayDevice->getTransform());
1926 const Rect bounds(displayDevice->getBounds());
1927 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001928 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001929
Jeff Sharkey76488112017-02-27 14:15:18 -07001930 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001931 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001932 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1933 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001934 Region drawRegion(tr.transform(
1935 layer->visibleNonTransparentRegion));
1936 drawRegion.andSelf(bounds);
1937 if (!drawRegion.isEmpty()) {
1938 layersSortedByZ.add(layer);
1939 } else {
1940 // Clear out the HWC layer if this layer was
1941 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001942 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001943 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001944 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001945 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001946 // WM changes displayDevice->layerStack upon sleep/awake.
1947 // Here we make sure we delete the HWC layers even if
1948 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001949 hwcLayerDestroyed = layer->destroyHwcLayer(
1950 displayDevice->getHwcDisplayId());
1951 }
1952
1953 // If a layer is not going to get a release fence because
1954 // it is invisible, but it is also going to release its
1955 // old buffer, add it to the list of layers needing
1956 // fences.
1957 if (hwcLayerDestroyed) {
1958 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1959 mLayersWithQueuedFrames.cend(), layer);
1960 if (found != mLayersWithQueuedFrames.cend()) {
1961 layersNeedingFences.add(layer);
1962 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001963 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001964 });
1965 }
1966 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001967 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001968 displayDevice->undefinedRegion.set(bounds);
1969 displayDevice->undefinedRegion.subtractSelf(
1970 tr.transform(opaqueRegion));
1971 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001972 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001973 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001974}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001975
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001976// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001977// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001978// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001979// - Dataspace::DISPLAY_P3
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001980// The returned HDR data space is one of
1981// - Dataspace::UNKNOWN
1982// - Dataspace::BT2020_HLG
1983// - Dataspace::BT2020_PQ
1984Dataspace SurfaceFlinger::getBestDataspace(
1985 const sp<const DisplayDevice>& displayDevice, Dataspace* outHdrDataSpace) const {
1986 Dataspace bestDataSpace = Dataspace::SRGB;
1987 *outHdrDataSpace = Dataspace::UNKNOWN;
1988
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001989 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu1b6bafc2018-05-22 12:03:00 -07001990 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001991 case Dataspace::V0_SCRGB:
1992 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001993 case Dataspace::DISPLAY_P3:
Chia-I Wu0607fbe2018-05-18 10:59:36 -07001994 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001995 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001996 case Dataspace::BT2020_PQ:
1997 case Dataspace::BT2020_ITU_PQ:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001998 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001999 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002000 case Dataspace::BT2020_HLG:
2001 case Dataspace::BT2020_ITU_HLG:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002002 // When there's mixed PQ content and HLG content, we set the HDR
2003 // data space to be BT2020_PQ and convert HLG to PQ.
2004 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2005 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002006 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002007 break;
2008 default:
2009 break;
2010 }
Romain Guy54f154a2017-10-24 21:40:32 +01002011 }
2012
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002013 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002014}
2015
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002016// Pick the ColorMode / Dataspace for the display device.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002017void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002018 ColorMode* outMode, Dataspace* outDataSpace,
2019 RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002020 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2021 *outMode = ColorMode::NATIVE;
2022 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002023 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002024 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002025 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002026
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002027 Dataspace hdrDataSpace;
2028 Dataspace bestDataSpace = getBestDataspace(displayDevice, &hdrDataSpace);
2029
Peiyong Lin3c6b7ef2018-06-05 10:58:41 -07002030 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002031 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lin3c6b7ef2018-06-05 10:58:41 -07002032 !displayDevice->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002033 if (isHdr) {
2034 bestDataSpace = hdrDataSpace;
2035 }
2036
Chia-I Wu0d711262018-05-21 15:19:35 -07002037 RenderIntent intent;
2038 switch (mDisplayColorSetting) {
2039 case DisplayColorSetting::MANAGED:
2040 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002041 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002042 break;
2043 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002044 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002045 break;
2046 default: // vendor display color setting
2047 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2048 break;
2049 }
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002050
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002051 displayDevice->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002052}
2053
Mathias Agopiancd60f992012-08-16 16:28:27 -07002054void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002055 ATRACE_CALL();
2056 ALOGV("setUpHWComposer");
2057
Jesse Hall028dc8f2013-08-20 16:35:32 -07002058 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07002059 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07002060 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
2061 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
2062
2063 // If nothing has changed (!dirty), don't recompose.
2064 // If something changed, but we don't currently have any visible layers,
2065 // and didn't when we last did a composition, then skip it this time.
2066 // The second rule does two things:
2067 // - When all layers are removed from a display, we'll emit one black
2068 // frame, then nothing more until we get new layers.
2069 // - When a display is created with a private layer stack, we won't
2070 // emit any black frames until a layer is added to the layer stack.
2071 bool mustRecompose = dirty && !(empty && wasEmpty);
2072
2073 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2074 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
2075 mustRecompose ? "doing" : "skipping",
2076 dirty ? "+" : "-",
2077 empty ? "+" : "-",
2078 wasEmpty ? "+" : "-");
2079
Dan Stoza71433162014-02-04 16:22:36 -08002080 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07002081
2082 if (mustRecompose) {
2083 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
2084 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07002085 }
2086
Dan Stoza9e56aa02015-11-02 13:00:03 -08002087 // build the h/w work list
2088 if (CC_UNLIKELY(mGeometryInvalid)) {
2089 mGeometryInvalid = false;
2090 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2091 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
2092 const auto hwcId = displayDevice->getHwcDisplayId();
2093 if (hwcId >= 0) {
2094 const Vector<sp<Layer>>& currentLayers(
2095 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08002096 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002097 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08002098 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07002099 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002100 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002101 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07002102 }
2103 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07002104
Robert Carrae060832016-11-28 10:51:00 -08002105 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002106 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002107 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07002108 }
2109 }
2110 }
2111 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002112 }
Riley Andrews03414a12014-07-01 14:22:59 -07002113
Dan Stoza9e56aa02015-11-02 13:00:03 -08002114 // Set the per-frame data
2115 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2116 auto& displayDevice = mDisplays[displayId];
2117 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002118
Dan Stoza9e56aa02015-11-02 13:00:03 -08002119 if (hwcId < 0) {
2120 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07002121 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07002122 if (mDrawingState.colorMatrixChanged) {
2123 displayDevice->setColorTransform(mDrawingState.colorMatrix);
2124 status_t result = getBE().mHwc->setColorTransform(hwcId, mDrawingState.colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002125 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2126 "display %zd: %d", displayId, result);
2127 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002128 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu07376a92018-06-05 15:46:58 -07002129 if (layer->isHdrY410()) {
2130 layer->forceClientComposition(hwcId);
2131 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2132 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002133 !displayDevice->hasHDR10Support()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002134 layer->forceClientComposition(hwcId);
Chia-I Wu07376a92018-06-05 15:46:58 -07002135 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2136 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Peiyong Linf59a7192018-04-25 11:19:31 -07002137 !displayDevice->hasHLGSupport()) {
2138 layer->forceClientComposition(hwcId);
2139 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002140
chaviwc9232ed2017-11-14 15:31:15 -08002141 if (layer->getForceClientComposition(hwcId)) {
2142 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2143 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2144 continue;
2145 }
2146
Dan Stoza9e56aa02015-11-02 13:00:03 -08002147 layer->setPerFrameData(displayDevice);
2148 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002149
2150 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002151 ColorMode colorMode;
2152 Dataspace dataSpace;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002153 RenderIntent renderIntent;
2154 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
2155 setActiveColorModeInternal(displayDevice, colorMode, dataSpace, renderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002156 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002157 }
2158
Chia-I Wu28f320b2018-05-03 11:02:56 -07002159 mDrawingState.colorMatrixChanged = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002160
Dan Stoza9e56aa02015-11-02 13:00:03 -08002161 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002162 auto& displayDevice = mDisplays[displayId];
2163 if (!displayDevice->isDisplayOn()) {
2164 continue;
2165 }
2166
David Sodman105b7dc2017-11-04 20:28:14 -07002167 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002168 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2169 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002170 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002171}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002172
Mathias Agopiancd60f992012-08-16 16:28:27 -07002173void SurfaceFlinger::doComposition() {
2174 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002175 ALOGV("doComposition");
2176
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002177 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002178 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002179 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002180 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002181 // transform the dirty region into this screen's coordinate space
2182 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002183
2184 // repaint the framebuffer (if needed)
2185 doDisplayComposition(hw, dirtyRegion);
2186
Mathias Agopiancd60f992012-08-16 16:28:27 -07002187 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002188 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002189 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002190 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002191 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002192}
2193
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002194void SurfaceFlinger::postFramebuffer()
2195{
Mathias Agopian841cde52012-03-01 15:44:37 -08002196 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002197 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002198
Mathias Agopiana44b0412011-10-16 18:46:35 -07002199 const nsecs_t now = systemTime();
2200 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002201
Dan Stoza9e56aa02015-11-02 13:00:03 -08002202 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2203 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002204 if (!displayDevice->isDisplayOn()) {
2205 continue;
2206 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002207 const auto hwcId = displayDevice->getHwcDisplayId();
2208 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002209 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002210 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002211 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002212 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002213 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu99b46192018-06-21 15:52:50 +08002214 sp<Fence> releaseFence = Fence::NO_FENCE;
2215
Chia-I Wu7b549592017-11-15 09:14:57 -08002216 // The layer buffer from the previous frame (if any) is released
2217 // by HWC only when the release fence from this frame (if any) is
2218 // signaled. Always get the release fence from HWC first.
2219 auto hwcLayer = layer->getHwcLayer(hwcId);
Chia-I Wu99b46192018-06-21 15:52:50 +08002220 if (hwcId >= 0) {
2221 releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
2222 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002223
2224 // If the layer was client composited in the previous frame, we
2225 // need to merge with the previous client target acquire fence.
2226 // Since we do not track that, always merge with the current
2227 // client target acquire fence when it is available, even though
2228 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002229 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002230 releaseFence = Fence::merge("LayerRelease", releaseFence,
2231 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002232 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002233
Dan Stoza9e56aa02015-11-02 13:00:03 -08002234 layer->onLayerDisplayed(releaseFence);
2235 }
Chia-I Wu83806892017-11-16 10:50:20 -08002236
2237 // We've got a list of layers needing fences, that are disjoint with
2238 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2239 // supply them with the present fence.
2240 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002241 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002242 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2243 layer->onLayerDisplayed(presentFence);
2244 }
2245 }
2246
Dan Stoza9e56aa02015-11-02 13:00:03 -08002247 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002248 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002249 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002250 }
2251
Mathias Agopiana44b0412011-10-16 18:46:35 -07002252 mLastSwapBufferTime = systemTime() - now;
2253 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002254
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002255 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002256 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2257 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2258 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2259 logFrameStats();
2260 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002261 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002262}
2263
Mathias Agopian87baae12012-07-31 12:38:26 -07002264void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002265{
Mathias Agopian841cde52012-03-01 15:44:37 -08002266 ATRACE_CALL();
2267
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002268 // here we keep a copy of the drawing state (that is the state that's
2269 // going to be overwritten by handleTransactionLocked()) outside of
2270 // mStateLock so that the side-effects of the State assignment
2271 // don't happen with mStateLock held (which can cause deadlocks).
2272 State drawingState(mDrawingState);
2273
Mathias Agopianca4d3602011-05-19 15:38:14 -07002274 Mutex::Autolock _l(mStateLock);
2275 const nsecs_t now = systemTime();
2276 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002277
Mathias Agopianca4d3602011-05-19 15:38:14 -07002278 // Here we're guaranteed that some transaction flags are set
2279 // so we can call handleTransactionLocked() unconditionally.
2280 // We call getTransactionFlags(), which will also clear the flags,
2281 // with mStateLock held to guarantee that mCurrentState won't change
2282 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002283
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002284 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002285 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002286 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002287
Mathias Agopianca4d3602011-05-19 15:38:14 -07002288 mLastTransactionTime = systemTime() - now;
2289 mDebugInTransaction = 0;
2290 invalidateHwcGeometry();
2291 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002292}
2293
Lloyd Pique715a2c12017-12-14 17:18:08 -08002294DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique09594832018-01-22 17:48:03 -08002295 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002296 // Figure out whether the event is for the primary display or an
2297 // external display by matching the Hwc display id against one for a
2298 // connected display. If we did not find a match, we then check what
2299 // displays are not already connected to determine the type. If we don't
2300 // have a connected primary display, we assume the new display is meant to
2301 // be the primary display, and then if we don't have an external display,
2302 // we assume it is that.
2303 const auto primaryDisplayId =
2304 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2305 const auto externalDisplayId =
2306 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2307 if (primaryDisplayId && primaryDisplayId == display) {
2308 return DisplayDevice::DISPLAY_PRIMARY;
2309 } else if (externalDisplayId && externalDisplayId == display) {
2310 return DisplayDevice::DISPLAY_EXTERNAL;
2311 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2312 return DisplayDevice::DISPLAY_PRIMARY;
2313 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2314 return DisplayDevice::DISPLAY_EXTERNAL;
2315 }
2316
2317 return DisplayDevice::DISPLAY_ID_INVALID;
2318}
2319
Lloyd Piqueba04e622017-12-14 17:11:26 -08002320void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2321 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002322 auto displayType = determineDisplayType(event.display, event.connection);
2323 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2324 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2325 continue;
2326 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002327
2328 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2329 ALOGE("External displays are not supported by the vr hardware composer.");
2330 continue;
2331 }
2332
Lloyd Pique715a2c12017-12-14 17:18:08 -08002333 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002334
2335 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002336 if (!mBuiltinDisplays[displayType].get()) {
2337 ALOGV("Creating built in display %d", displayType);
2338 mBuiltinDisplays[displayType] = new BBinder();
2339 // All non-virtual displays are currently considered secure.
2340 DisplayDeviceState info(displayType, true);
2341 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2342 "Built-in Screen" : "External Screen";
2343 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4d234852018-01-22 17:21:36 -08002344 mInterceptor->saveDisplayCreation(info);
Steven Thomas3bed0522018-03-20 15:40:48 -07002345 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002346 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002347 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002348
Lloyd Piquefcd86612017-12-14 17:15:36 -08002349 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2350 if (idx >= 0) {
2351 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4d234852018-01-22 17:21:36 -08002352 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002353 mCurrentState.displays.removeItemsAt(idx);
2354 }
2355 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002356 }
2357
2358 processDisplayChangesLocked();
2359 }
2360
2361 mPendingHotplugEvents.clear();
2362}
2363
Lloyd Pique09594832018-01-22 17:48:03 -08002364sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2365 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2366 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002367 bool hasWideColorGamut = false;
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002368 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu99b46192018-06-21 15:52:50 +08002369 HdrCapabilities hdrCapabilities;
2370 int32_t supportedPerFrameMetadata = 0;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002371
Chia-I Wu99b46192018-06-21 15:52:50 +08002372 if (hasWideColorDisplay && hwcId >= 0) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002373 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique09594832018-01-22 17:48:03 -08002374 for (ColorMode colorMode : modes) {
2375 switch (colorMode) {
2376 case ColorMode::DISPLAY_P3:
2377 case ColorMode::ADOBE_RGB:
2378 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002379 hasWideColorGamut = true;
Lloyd Pique09594832018-01-22 17:48:03 -08002380 break;
2381 default:
2382 break;
2383 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002384
2385 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2386 colorMode);
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002387 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique09594832018-01-22 17:48:03 -08002388 }
2389 }
2390
Chia-I Wu99b46192018-06-21 15:52:50 +08002391 if (hwcId >= 0) {
2392 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
2393 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(hwcId);
2394 }
Lloyd Pique09594832018-01-22 17:48:03 -08002395
2396 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2397 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2398
2399 /*
2400 * Create our display's surface
2401 */
2402 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2403 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2404 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2405 renderSurface->setNativeWindow(nativeWindow.get());
2406 const int displayWidth = renderSurface->queryWidth();
2407 const int displayHeight = renderSurface->queryHeight();
2408
2409 // Make sure that composition can never be stalled by a virtual display
2410 // consumer that isn't processing buffers fast enough. We have to do this
2411 // in two places:
2412 // * Here, in case the display is composed entirely by HWC.
2413 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2414 // window's swap interval in eglMakeCurrent, so they'll override the
2415 // interval we set here.
2416 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2417 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2418 }
2419
Chia-I Wu690a76f2018-08-27 14:38:23 -07002420 const int displayInstallOrientation = state.type == DisplayDevice::DISPLAY_PRIMARY ?
2421 primaryDisplayOrientation : DisplayState::eOrientationDefault;
2422
Lloyd Pique09594832018-01-22 17:48:03 -08002423 // virtual displays are always considered enabled
2424 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2425 : HWC_POWER_MODE_OFF;
2426
2427 sp<DisplayDevice> hw =
2428 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2429 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Chia-I Wu690a76f2018-08-27 14:38:23 -07002430 displayInstallOrientation, hasWideColorGamut, hdrCapabilities,
Chia-I Wu99b46192018-06-21 15:52:50 +08002431 supportedPerFrameMetadata, hwcColorModes, initialPowerMode);
Lloyd Pique09594832018-01-22 17:48:03 -08002432
2433 if (maxFrameBufferAcquiredBuffers >= 3) {
2434 nativeWindowSurface->preallocateBuffers();
2435 }
2436
2437 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002438 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2439 if (hasWideColorGamut) {
Lloyd Pique09594832018-01-22 17:48:03 -08002440 defaultColorMode = ColorMode::SRGB;
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002441 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique09594832018-01-22 17:48:03 -08002442 }
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002443 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace,
2444 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002445 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
2446 hw->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
2447 }
Lloyd Pique09594832018-01-22 17:48:03 -08002448 hw->setLayerStack(state.layerStack);
2449 hw->setProjection(state.orientation, state.viewport, state.frame);
2450 hw->setDisplayName(state.displayName);
2451
2452 return hw;
2453}
2454
Lloyd Pique347200f2017-12-14 17:00:15 -08002455void SurfaceFlinger::processDisplayChangesLocked() {
2456 // here we take advantage of Vector's copy-on-write semantics to
2457 // improve performance by skipping the transaction entirely when
2458 // know that the lists are identical
2459 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2460 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2461 if (!curr.isIdenticalTo(draw)) {
2462 mVisibleRegionsDirty = true;
2463 const size_t cc = curr.size();
2464 size_t dc = draw.size();
2465
2466 // find the displays that were removed
2467 // (ie: in drawing state but not in current state)
2468 // also handle displays that changed
2469 // (ie: displays that are in both lists)
2470 for (size_t i = 0; i < dc;) {
2471 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2472 if (j < 0) {
2473 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002474 // Call makeCurrent() on the primary display so we can
2475 // be sure that nothing associated with this display
2476 // is current.
2477 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2478 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2479 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2480 if (hw != nullptr) hw->disconnect(getHwComposer());
2481 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2482 mEventThread->onHotplugReceived(draw[i].type, false);
2483 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002484 } else {
2485 // this display is in both lists. see if something changed.
2486 const DisplayDeviceState& state(curr[j]);
2487 const wp<IBinder>& display(curr.keyAt(j));
2488 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2489 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2490 if (state_binder != draw_binder) {
2491 // changing the surface is like destroying and
2492 // recreating the DisplayDevice, so we just remove it
2493 // from the drawing state, so that it get re-added
2494 // below.
2495 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2496 if (hw != nullptr) hw->disconnect(getHwComposer());
2497 mDisplays.removeItem(display);
2498 mDrawingState.displays.removeItemsAt(i);
2499 dc--;
2500 // at this point we must loop to the next item
2501 continue;
2502 }
2503
2504 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2505 if (disp != nullptr) {
2506 if (state.layerStack != draw[i].layerStack) {
2507 disp->setLayerStack(state.layerStack);
2508 }
2509 if ((state.orientation != draw[i].orientation) ||
2510 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2511 disp->setProjection(state.orientation, state.viewport, state.frame);
2512 }
2513 if (state.width != draw[i].width || state.height != draw[i].height) {
2514 disp->setDisplaySize(state.width, state.height);
2515 }
2516 }
2517 }
2518 ++i;
2519 }
2520
2521 // find displays that were added
2522 // (ie: in current state but not in drawing state)
2523 for (size_t i = 0; i < cc; i++) {
2524 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2525 const DisplayDeviceState& state(curr[i]);
2526
2527 sp<DisplaySurface> dispSurface;
2528 sp<IGraphicBufferProducer> producer;
2529 sp<IGraphicBufferProducer> bqProducer;
2530 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002531 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002532
2533 int32_t hwcId = -1;
2534 if (state.isVirtualDisplay()) {
2535 // Virtual displays without a surface are dormant:
2536 // they have external state (layer stack, projection,
2537 // etc.) but no internal state (i.e. a DisplayDevice).
2538 if (state.surface != nullptr) {
2539 // Allow VR composer to use virtual displays.
2540 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2541 int width = 0;
2542 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2543 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2544 int height = 0;
2545 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2546 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2547 int intFormat = 0;
2548 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2549 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002550 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002551
2552 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2553 }
2554
2555 // TODO: Plumb requested format back up to consumer
2556
2557 sp<VirtualDisplaySurface> vds =
2558 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2559 bqProducer, bqConsumer,
2560 state.displayName);
2561
2562 dispSurface = vds;
2563 producer = vds;
2564 }
2565 } else {
2566 ALOGE_IF(state.surface != nullptr,
2567 "adding a supported display, but rendering "
2568 "surface is provided (%p), ignoring it",
2569 state.surface.get());
2570
2571 hwcId = state.type;
2572 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2573 producer = bqProducer;
2574 }
2575
2576 const wp<IBinder>& display(curr.keyAt(i));
2577 if (dispSurface != nullptr) {
Lloyd Pique09594832018-01-22 17:48:03 -08002578 mDisplays.add(display,
2579 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2580 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002581 if (!state.isVirtualDisplay()) {
2582 mEventThread->onHotplugReceived(state.type, true);
2583 }
2584 }
2585 }
2586 }
2587 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002588
2589 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002590}
2591
Mathias Agopian87baae12012-07-31 12:38:26 -07002592void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002593{
Dan Stoza7dde5992015-05-22 09:51:44 -07002594 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002595 mCurrentState.traverseInZOrder([](Layer* layer) {
2596 layer->notifyAvailableFrames();
2597 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002598
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002599 /*
2600 * Traversal of the children
2601 * (perform the transaction for each of them if needed)
2602 */
2603
Mathias Agopian3559b072012-08-15 13:46:03 -07002604 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002605 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002606 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002607 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002608
2609 const uint32_t flags = layer->doTransaction(0);
2610 if (flags & Layer::eVisibleRegion)
2611 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002612 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002613 }
2614
2615 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002616 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002617 */
2618
Mathias Agopiane57f2922012-08-09 16:29:12 -07002619 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002620 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002621 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002622 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002623
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002624 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002625 // The transform hint might have changed for some layers
2626 // (either because a display has changed, or because a layer
2627 // as changed).
2628 //
2629 // Walk through all the layers in currentLayers,
2630 // and update their transform hint.
2631 //
2632 // If a layer is visible only on a single display, then that
2633 // display is used to calculate the hint, otherwise we use the
2634 // default display.
2635 //
2636 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2637 // the hint is set before we acquire a buffer from the surface texture.
2638 //
2639 // NOTE: layer transactions have taken place already, so we use their
2640 // drawing state. However, SurfaceFlinger's own transaction has not
2641 // happened yet, so we must use the current state layer list
2642 // (soon to become the drawing state list).
2643 //
2644 sp<const DisplayDevice> disp;
2645 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002646 bool first = true;
2647 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002648 // NOTE: we rely on the fact that layers are sorted by
2649 // layerStack first (so we don't have to traverse the list
2650 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002651 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002652 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002653 currentlayerStack = layerStack;
2654 // figure out if this layerstack is mirrored
2655 // (more than one display) if so, pick the default display,
2656 // if not, pick the only display it's on.
2657 disp.clear();
2658 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2659 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002660 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002661 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002662 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002663 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002664 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002665 break;
2666 }
2667 }
2668 }
2669 }
Chet Haase91d25932013-04-11 15:24:55 -07002670
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002671 if (disp == nullptr) {
2672 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2673 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002674
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002675 // could be null when this layer is using a layerStack
2676 // that is not visible on any display. Also can occur at
2677 // screen off/on times.
2678 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002679 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002680
2681 // disp can be null if there is no display available at all to get
2682 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002683 if (disp != nullptr) {
2684 layer->updateTransformHint(disp);
2685 }
Robert Carr2047fae2016-11-28 14:09:09 -08002686
2687 first = false;
2688 });
Mathias Agopian84300952012-11-21 16:02:13 -08002689 }
2690
2691
Mathias Agopian3559b072012-08-15 13:46:03 -07002692 /*
2693 * Perform our own transaction if needed
2694 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002695
2696 if (mLayersAdded) {
2697 mLayersAdded = false;
2698 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002699 mVisibleRegionsDirty = true;
2700 }
2701
2702 // some layers might have been removed, so
2703 // we need to update the regions they're exposing.
2704 if (mLayersRemoved) {
2705 mLayersRemoved = false;
2706 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002707 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002708 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002709 // this layer is not visible anymore
2710 // TODO: we could traverse the tree from front to back and
2711 // compute the actual visible region
2712 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002713 Region visibleReg;
2714 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002715 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002716 }
Robert Carr2047fae2016-11-28 14:09:09 -08002717 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002718 }
2719
2720 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002721
2722 updateCursorAsync();
2723}
2724
2725void SurfaceFlinger::updateCursorAsync()
2726{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002727 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2728 auto& displayDevice = mDisplays[displayId];
2729 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002730 continue;
2731 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002732
2733 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2734 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002735 }
2736 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002737}
2738
2739void SurfaceFlinger::commitTransaction()
2740{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002741 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002742 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002743 for (const auto& l : mLayersPendingRemoval) {
2744 recordBufferingStats(l->getName().string(),
2745 l->getOccupancyHistory(true));
2746 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002747 }
2748 mLayersPendingRemoval.clear();
2749 }
2750
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002751 // If this transaction is part of a window animation then the next frame
2752 // we composite should be considered an animation as well.
2753 mAnimCompositionPending = mAnimTransactionPending;
2754
Mathias Agopian4fec8732012-06-29 14:12:52 -07002755 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002756 // clear the "changed" flags in current state
2757 mCurrentState.colorMatrixChanged = false;
2758
Robert Carr1f0a16a2016-10-24 16:27:39 -07002759 mDrawingState.traverseInZOrder([](Layer* layer) {
2760 layer->commitChildList();
2761 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002762 mTransactionPending = false;
2763 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002764 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002765}
2766
Chia-I Wuab0c3192017-08-01 11:29:00 -07002767void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002768 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002769{
Mathias Agopian841cde52012-03-01 15:44:37 -08002770 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002771 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002772
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002773 Region aboveOpaqueLayers;
2774 Region aboveCoveredLayers;
2775 Region dirty;
2776
Mathias Agopian87baae12012-07-31 12:38:26 -07002777 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002778
Robert Carr2047fae2016-11-28 14:09:09 -08002779 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002780 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002781 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002782
Jesse Hall01e29052013-02-19 16:13:35 -08002783 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002784 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002785 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002786
Mathias Agopianab028732010-03-16 16:41:46 -07002787 /*
2788 * opaqueRegion: area of a surface that is fully opaque.
2789 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002790 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002791
2792 /*
2793 * visibleRegion: area of a surface that is visible on screen
2794 * and not fully transparent. This is essentially the layer's
2795 * footprint minus the opaque regions above it.
2796 * Areas covered by a translucent surface are considered visible.
2797 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002798 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002799
2800 /*
2801 * coveredRegion: area of a surface that is covered by all
2802 * visible regions above it (which includes the translucent areas).
2803 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002804 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002805
Jesse Halla8026d22012-09-25 13:25:04 -07002806 /*
2807 * transparentRegion: area of a surface that is hinted to be completely
2808 * transparent. This is only used to tell when the layer has no visible
2809 * non-transparent regions and can be removed from the layer list. It
2810 * does not affect the visibleRegion of this layer or any layers
2811 * beneath it. The hint may not be correct if apps don't respect the
2812 * SurfaceView restrictions (which, sadly, some don't).
2813 */
2814 Region transparentRegion;
2815
Mathias Agopianab028732010-03-16 16:41:46 -07002816
2817 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002818 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002819 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002820 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002821 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002822 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002823 if (!visibleRegion.isEmpty()) {
2824 // Remove the transparent area from the visible region
2825 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002826 if (tr.preserveRects()) {
2827 // transform the transparent region
2828 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002829 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002830 // transformation too complex, can't do the
2831 // transparent region optimization.
2832 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002833 }
Mathias Agopianab028732010-03-16 16:41:46 -07002834 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002835
Mathias Agopianab028732010-03-16 16:41:46 -07002836 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002837 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002838 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002839 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2840 // the opaque region is the layer's footprint
2841 opaqueRegion = visibleRegion;
2842 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002843 }
2844 }
2845
Robert Carre5f4f692018-01-12 13:12:28 -08002846 if (visibleRegion.isEmpty()) {
2847 layer->clearVisibilityRegions();
2848 return;
2849 }
2850
Mathias Agopianab028732010-03-16 16:41:46 -07002851 // Clip the covered region to the visible region
2852 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2853
2854 // Update aboveCoveredLayers for next (lower) layer
2855 aboveCoveredLayers.orSelf(visibleRegion);
2856
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002857 // subtract the opaque region covered by the layers above us
2858 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002859
2860 // compute this layer's dirty region
2861 if (layer->contentDirty) {
2862 // we need to invalidate the whole region
2863 dirty = visibleRegion;
2864 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002865 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002866 layer->contentDirty = false;
2867 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002868 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002869 * the exposed region consists of two components:
2870 * 1) what's VISIBLE now and was COVERED before
2871 * 2) what's EXPOSED now less what was EXPOSED before
2872 *
2873 * note that (1) is conservative, we start with the whole
2874 * visible region but only keep what used to be covered by
2875 * something -- which mean it may have been exposed.
2876 *
2877 * (2) handles areas that were not covered by anything but got
2878 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002879 */
Mathias Agopianab028732010-03-16 16:41:46 -07002880 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002881 const Region oldVisibleRegion = layer->visibleRegion;
2882 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002883 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2884 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002885 }
2886 dirty.subtractSelf(aboveOpaqueLayers);
2887
2888 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002889 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002890
Mathias Agopianab028732010-03-16 16:41:46 -07002891 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002892 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002893
Jesse Halla8026d22012-09-25 13:25:04 -07002894 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002895 layer->setVisibleRegion(visibleRegion);
2896 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002897 layer->setVisibleNonTransparentRegion(
2898 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002899 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002900
Mathias Agopian87baae12012-07-31 12:38:26 -07002901 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002902}
2903
Chia-I Wuab0c3192017-08-01 11:29:00 -07002904void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002905 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002906 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002907 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002908 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002909 }
2910 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002911}
2912
Dan Stoza6b9454d2014-11-07 16:00:59 -08002913bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002914{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002915 ALOGV("handlePageFlip");
2916
Brian Andersond6927fb2016-07-23 23:37:30 -07002917 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002918
Mathias Agopian4fec8732012-06-29 14:12:52 -07002919 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002920 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002921 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002922
2923 // Store the set of layers that need updates. This set must not change as
2924 // buffers are being latched, as this could result in a deadlock.
2925 // Example: Two producers share the same command stream and:
2926 // 1.) Layer 0 is latched
2927 // 2.) Layer 0 gets a new frame
2928 // 2.) Layer 1 gets a new frame
2929 // 3.) Layer 1 is latched.
2930 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2931 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002932 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002933 if (layer->hasQueuedFrame()) {
2934 frameQueued = true;
2935 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002936 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002937 } else {
2938 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002939 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002940 } else {
2941 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002942 }
Robert Carr2047fae2016-11-28 14:09:09 -08002943 });
2944
Dan Stoza9e56aa02015-11-02 13:00:03 -08002945 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002946 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002947 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002948 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002949 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002950 newDataLatched = true;
2951 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002952 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002953
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002954 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002955
2956 // If we will need to wake up at some time in the future to deal with a
2957 // queued frame that shouldn't be displayed during this vsync period, wake
2958 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002959 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002960 signalLayerUpdate();
2961 }
2962
Chia-I Wuad8d8272018-06-26 10:18:18 +08002963 // enter boot animation on first buffer latch
2964 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2965 ALOGI("Enter boot animation");
2966 mBootStage = BootStage::BOOTANIMATION;
2967 }
2968
Dan Stoza6b9454d2014-11-07 16:00:59 -08002969 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002970 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002971}
2972
Mathias Agopianad456f92011-01-13 17:53:01 -08002973void SurfaceFlinger::invalidateHwcGeometry()
2974{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002975 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002976}
2977
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002978
Fabien Sanglard830b8472016-11-30 16:35:58 -08002979void SurfaceFlinger::doDisplayComposition(
2980 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002981 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002982{
Dan Stoza71433162014-02-04 16:22:36 -08002983 // We only need to actually compose the display if:
2984 // 1) It is being handled by hardware composer, which may need this to
2985 // keep its virtual display state machine in sync, or
2986 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002987 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002988 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002989 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002990 return;
2991 }
2992
Dan Stoza9e56aa02015-11-02 13:00:03 -08002993 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002994 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002995
2996 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002997 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002998}
2999
Chia-I Wub02087d2017-11-09 10:19:54 -08003000bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07003001{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003002 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003003
Chia-I Wub02087d2017-11-09 10:19:54 -08003004 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07003005 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003006 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003007 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003008 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003009
Chia-I Wu8e50e692018-05-04 10:12:37 -07003010 bool applyColorMatrix = false;
Chia-I Wu6d844112018-06-27 07:17:41 +08003011 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003012
Dan Stoza9e56aa02015-11-02 13:00:03 -08003013 if (hasClientComposition) {
3014 ALOGV("hasClientComposition");
3015
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003016 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003017 if (displayDevice->hasWideColorGamut()) {
3018 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003019 }
3020 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003021 getBE().mRenderEngine->setDisplayMaxLuminance(
3022 displayDevice->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003023
Chia-I Wu8e50e692018-05-04 10:12:37 -07003024 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
3025 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3026 HWC2::Capability::SkipClientColorTransform);
3027
Chia-I Wu6d844112018-06-27 07:17:41 +08003028 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003029 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3030 if (applyColorMatrix) {
Chia-I Wu6d844112018-06-27 07:17:41 +08003031 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003032 }
3033
Chia-I Wu6d844112018-06-27 07:17:41 +08003034 // The current enhanced saturation matrix is designed to enhance Display P3,
3035 // thus we only apply this matrix when the render intent is not colorimetric
3036 // and the output color space is Display P3.
3037 needsEnhancedColorMatrix =
Chia-I Wu0d711262018-05-21 15:19:35 -07003038 (displayDevice->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
Chia-I Wu6d844112018-06-27 07:17:41 +08003039 outputDataspace == Dataspace::DISPLAY_P3);
3040 if (needsEnhancedColorMatrix) {
3041 colorMatrix *= mEnhancedSaturationMatrix;
3042 }
3043
3044 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003045
Chia-I Wu7f402902017-11-09 12:51:10 -08003046 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003047 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003048 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08003049 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003050
3051 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08003052 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07003053 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
3054 }
3055 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003056 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003057
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003058 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003059 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003060 // when using overlays, we assume a fully transparent framebuffer
3061 // NOTE: we could reduce how much we need to clear, for instance
3062 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003063 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003064 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003065 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003066 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003067 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003068 // we're left with the letterbox region
3069 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08003070 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07003071
3072 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08003073 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07003074
Mathias Agopianb9494d52012-04-18 02:28:45 -07003075 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003076 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003077 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08003078 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003079 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003080 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003081
Yiwei Zhangcf39b7b2018-08-22 13:59:12 -07003082 const Rect& bounds(displayDevice->getBounds());
3083 const Rect& scissor(displayDevice->getScissor());
3084 if (scissor != bounds) {
3085 // scissor doesn't match the screen's dimensions, so we
3086 // need to clear everything outside of it and enable
3087 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003088
Yiwei Zhangcf39b7b2018-08-22 13:59:12 -07003089 // enable scissor for this frame
3090 const uint32_t height = displayDevice->getHeight();
3091 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
3092 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003093 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003094 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003095
Mathias Agopian85d751c2012-08-29 16:59:24 -07003096 /*
3097 * and then, render the layers targeted at the framebuffer
3098 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003099
Dan Stoza9e56aa02015-11-02 13:00:03 -08003100 ALOGV("Rendering client layers");
3101 const Transform& displayTransform = displayDevice->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003102 bool firstLayer = true;
3103 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3104 const Region clip(bounds.intersect(
3105 displayTransform.transform(layer->visibleRegion)));
3106 ALOGV("Layer: %s", layer->getName().string());
3107 ALOGV(" Composition type: %s",
3108 to_string(layer->getCompositionType(hwcId)).c_str());
3109 if (!clip.isEmpty()) {
3110 switch (layer->getCompositionType(hwcId)) {
3111 case HWC2::Composition::Cursor:
3112 case HWC2::Composition::Device:
3113 case HWC2::Composition::Sideband:
3114 case HWC2::Composition::SolidColor: {
3115 const Layer::State& state(layer->getDrawingState());
3116 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
3117 layer->isOpaque(state) && (state.color.a == 1.0f)
3118 && hasClientComposition) {
3119 // never clear the very first layer since we're
3120 // guaranteed the FB is already cleared
3121 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003122 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003123 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003124 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003125 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003126 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003127 break;
3128 }
3129 default:
3130 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003131 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003132 } else {
3133 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003134 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003135 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003136 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003137
Chia-I Wu6d844112018-06-27 07:17:41 +08003138 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003139 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003140 }
3141
Mathias Agopianf45c5102012-10-24 16:29:17 -07003142 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003143 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003144 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003145}
3146
Fabien Sanglard830b8472016-11-30 16:35:58 -08003147void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3148 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003149 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003150 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003151}
3152
Dan Stoza7d89d062015-04-30 13:29:25 -07003153status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003154 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003155 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003156 const sp<Layer>& lbc,
3157 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003158{
Dan Stoza7d89d062015-04-30 13:29:25 -07003159 // add this layer to the current state list
3160 {
3161 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003162 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003163 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3164 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003165 return NO_MEMORY;
3166 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003167 if (parent == nullptr) {
3168 mCurrentState.layersSortedByZ.add(lbc);
3169 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003170 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003171 ALOGE("addClientLayer called with a removed parent");
3172 return NAME_NOT_FOUND;
3173 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003174 parent->addChild(lbc);
3175 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003176
Yiwei Zhang243b3782018-05-15 17:40:04 -07003177 if (gbc != nullptr) {
3178 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3179 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3180 mMaxGraphicBufferProducerListSize,
3181 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3182 mGraphicBufferProducerList.size(),
3183 mMaxGraphicBufferProducerListSize, mNumLayers);
3184 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003185 mLayersAdded = true;
3186 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003187 }
3188
Mathias Agopian96f08192010-06-02 23:28:45 -07003189 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003190 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003191
Dan Stoza7d89d062015-04-30 13:29:25 -07003192 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003193}
3194
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003195status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003196 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003197 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3198}
Robert Carr7f9b8992017-03-10 11:08:39 -08003199
chaviwca27f252018-02-06 16:46:39 -08003200status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3201 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003202 if (layer->isPendingRemoval()) {
3203 return NO_ERROR;
3204 }
3205
Robert Carr1f0a16a2016-10-24 16:27:39 -07003206 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003207 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003208 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003209 if (topLevelOnly) {
3210 return NO_ERROR;
3211 }
3212
Chia-I Wu98f1c102017-05-30 14:54:08 -07003213 sp<Layer> ancestor = p;
3214 while (ancestor->getParent() != nullptr) {
3215 ancestor = ancestor->getParent();
3216 }
3217 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3218 ALOGE("removeLayer called with a layer whose parent has been removed");
3219 return NAME_NOT_FOUND;
3220 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003221
3222 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003223 } else {
3224 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003225 }
3226
Robert Carr136e2f62017-02-08 17:54:29 -08003227 // As a matter of normal operation, the LayerCleaner will produce a second
3228 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3229 // so we will succeed in promoting it, but it's already been removed
3230 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3231 // otherwise something has gone wrong and we are leaking the layer.
3232 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003233 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3234 layer->getName().string(),
3235 (p != nullptr) ? p->getName().string() : "no-parent");
3236 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003237 } else if (index < 0) {
3238 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003239 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003240
Chia-I Wuc6657022017-08-15 11:18:17 -07003241 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003242 mLayersPendingRemoval.add(layer);
3243 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003244 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003245 setTransactionFlags(eTransactionNeeded);
3246 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003247}
3248
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003249uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003250 return android_atomic_release_load(&mTransactionFlags);
3251}
3252
Mathias Agopian3f844832013-08-07 21:24:32 -07003253uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003254 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3255}
3256
Mathias Agopian3f844832013-08-07 21:24:32 -07003257uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza2713c302018-03-28 17:07:36 -07003258 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3259}
3260
3261uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3262 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003263 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza2713c302018-03-28 17:07:36 -07003264 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003265 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003266 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003267 }
3268 return old;
3269}
3270
chaviwca27f252018-02-06 16:46:39 -08003271bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3272 for (const ComposerState& state : states) {
3273 // Here we need to check that the interface we're given is indeed
3274 // one of our own. A malicious client could give us a nullptr
3275 // IInterface, or one of its own or even one of our own but a
3276 // different type. All these situations would cause us to crash.
3277 if (state.client == nullptr) {
3278 return true;
3279 }
3280
3281 sp<IBinder> binder = IInterface::asBinder(state.client);
3282 if (binder == nullptr) {
3283 return true;
3284 }
3285
3286 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3287 return true;
3288 }
3289 }
3290 return false;
3291}
3292
Mathias Agopian8b33f032012-07-24 20:43:54 -07003293void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003294 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003295 const Vector<DisplayState>& displays,
3296 uint32_t flags)
3297{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003298 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003299 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003300 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003301
chaviwca27f252018-02-06 16:46:39 -08003302 if (containsAnyInvalidClientState(states)) {
3303 return;
3304 }
3305
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003306 if (flags & eAnimation) {
3307 // For window updates that are part of an animation we must wait for
3308 // previous animation "frames" to be handled.
3309 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003310 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003311 if (CC_UNLIKELY(err != NO_ERROR)) {
3312 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003313 // caller after a few seconds.
3314 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3315 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003316 mAnimTransactionPending = false;
3317 break;
3318 }
3319 }
3320 }
3321
chaviwca27f252018-02-06 16:46:39 -08003322 for (const DisplayState& display : displays) {
3323 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003324 }
3325
chaviwca27f252018-02-06 16:46:39 -08003326 for (const ComposerState& state : states) {
3327 transactionFlags |= setClientStateLocked(state);
3328 }
3329
3330 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3331 // as destroyed should only occur after setting all other states. This is to allow for a
3332 // child re-parent to happen before marking its original parent as destroyed (which would
3333 // then mark the child as destroyed).
3334 for (const ComposerState& state : states) {
3335 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003336 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003337
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003338 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3339 // anyway. This can be used as a flush mechanism for previous async transactions.
3340 // Empty animation transaction can be used to simulate back-pressure, so also force a
3341 // transaction for empty animation transactions.
3342 if (transactionFlags == 0 &&
3343 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003344 transactionFlags = eTransactionNeeded;
3345 }
3346
Mathias Agopian386aa982011-11-07 21:58:03 -08003347 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003348 if (mInterceptor->isEnabled()) {
3349 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003350 }
Irvel468051e2016-06-13 16:44:44 -07003351
Mathias Agopian386aa982011-11-07 21:58:03 -08003352 // this triggers the transaction
Dan Stoza2713c302018-03-28 17:07:36 -07003353 const auto start = (flags & eEarlyWakeup)
3354 ? VSyncModulator::TransactionStart::EARLY
3355 : VSyncModulator::TransactionStart::NORMAL;
3356 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003357
3358 // if this is a synchronous transaction, wait for it to take effect
3359 // before returning.
3360 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003361 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003362 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003363 if (flags & eAnimation) {
3364 mAnimTransactionPending = true;
3365 }
3366 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003367 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3368 if (CC_UNLIKELY(err != NO_ERROR)) {
3369 // just in case something goes wrong in SF, return to the
3370 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003371 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3372 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003373 break;
3374 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003375 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003376 }
3377}
3378
Mathias Agopiane57f2922012-08-09 16:29:12 -07003379uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3380{
Jesse Hall9a143922012-10-04 16:29:19 -07003381 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3382 if (dpyIdx < 0)
3383 return 0;
3384
Mathias Agopiane57f2922012-08-09 16:29:12 -07003385 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003386 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003387 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003388 const uint32_t what = s.what;
3389 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003390 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003391 disp.surface = s.surface;
3392 flags |= eDisplayTransactionNeeded;
3393 }
3394 }
3395 if (what & DisplayState::eLayerStackChanged) {
3396 if (disp.layerStack != s.layerStack) {
3397 disp.layerStack = s.layerStack;
3398 flags |= eDisplayTransactionNeeded;
3399 }
3400 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003401 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003402 if (disp.orientation != s.orientation) {
3403 disp.orientation = s.orientation;
3404 flags |= eDisplayTransactionNeeded;
3405 }
3406 if (disp.frame != s.frame) {
3407 disp.frame = s.frame;
3408 flags |= eDisplayTransactionNeeded;
3409 }
3410 if (disp.viewport != s.viewport) {
3411 disp.viewport = s.viewport;
3412 flags |= eDisplayTransactionNeeded;
3413 }
3414 }
Michael Lentine47e45402014-07-18 15:34:25 -07003415 if (what & DisplayState::eDisplaySizeChanged) {
3416 if (disp.width != s.width) {
3417 disp.width = s.width;
3418 flags |= eDisplayTransactionNeeded;
3419 }
3420 if (disp.height != s.height) {
3421 disp.height = s.height;
3422 flags |= eDisplayTransactionNeeded;
3423 }
3424 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003425 }
3426 return flags;
3427}
3428
Robert Carrd4ae7f32018-06-07 16:10:57 -07003429bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3430 IPCThreadState* ipc = IPCThreadState::self();
3431 const int pid = ipc->getCallingPid();
3432 const int uid = ipc->getCallingUid();
3433
3434 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3435 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3436 return false;
3437 }
3438 return true;
3439}
3440
chaviwca27f252018-02-06 16:46:39 -08003441uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3442 const layer_state_t& s = composerState.state;
3443 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3444
Mathias Agopian13127d82013-03-05 17:47:11 -08003445 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003446 if (layer == nullptr) {
3447 return 0;
3448 }
3449
3450 if (layer->isPendingRemoval()) {
3451 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3452 return 0;
3453 }
3454
3455 uint32_t flags = 0;
3456
3457 const uint32_t what = s.what;
3458 bool geometryAppliesWithResize =
3459 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003460
3461 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3462 // pending state will also be deferred.
3463 if (what & layer_state_t::eDeferTransaction) {
3464 layer->pushPendingState();
3465 }
3466
chaviw8b3871a2017-11-01 17:41:01 -07003467 if (what & layer_state_t::ePositionChanged) {
3468 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3469 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003470 }
chaviw8b3871a2017-11-01 17:41:01 -07003471 }
3472 if (what & layer_state_t::eLayerChanged) {
3473 // NOTE: index needs to be calculated before we update the state
3474 const auto& p = layer->getParent();
3475 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003476 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003477 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003478 mCurrentState.layersSortedByZ.removeAt(idx);
3479 mCurrentState.layersSortedByZ.add(layer);
3480 // we need traversal (state changed)
3481 // AND transaction (list changed)
3482 flags |= eTransactionNeeded|eTraversalNeeded;
3483 }
chaviw8b3871a2017-11-01 17:41:01 -07003484 } else {
3485 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003486 flags |= eTransactionNeeded|eTraversalNeeded;
3487 }
3488 }
chaviw8b3871a2017-11-01 17:41:01 -07003489 }
3490 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003491 // NOTE: index needs to be calculated before we update the state
3492 const auto& p = layer->getParent();
3493 if (p == nullptr) {
3494 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3495 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3496 mCurrentState.layersSortedByZ.removeAt(idx);
3497 mCurrentState.layersSortedByZ.add(layer);
3498 // we need traversal (state changed)
3499 // AND transaction (list changed)
3500 flags |= eTransactionNeeded|eTraversalNeeded;
3501 }
3502 } else {
3503 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3504 flags |= eTransactionNeeded|eTraversalNeeded;
3505 }
chaviw8b3871a2017-11-01 17:41:01 -07003506 }
3507 }
3508 if (what & layer_state_t::eSizeChanged) {
3509 if (layer->setSize(s.w, s.h)) {
3510 flags |= eTraversalNeeded;
3511 }
3512 }
3513 if (what & layer_state_t::eAlphaChanged) {
3514 if (layer->setAlpha(s.alpha))
3515 flags |= eTraversalNeeded;
3516 }
3517 if (what & layer_state_t::eColorChanged) {
3518 if (layer->setColor(s.color))
3519 flags |= eTraversalNeeded;
3520 }
3521 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003522 // TODO: b/109894387
3523 //
3524 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3525 // rotation. To see the problem observe that if we have a square parent, and a child
3526 // of the same size, then we rotate the child 45 degrees around it's center, the child
3527 // must now be cropped to a non rectangular 8 sided region.
3528 //
3529 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3530 // private API, and the WindowManager only uses rotation in one case, which is on a top
3531 // level layer in which cropping is not an issue.
3532 //
3533 // However given that abuse of rotation matrices could lead to surfaces extending outside
3534 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3535 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3536 // transformations.
3537 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003538 flags |= eTraversalNeeded;
3539 }
3540 if (what & layer_state_t::eTransparentRegionChanged) {
3541 if (layer->setTransparentRegionHint(s.transparentRegion))
3542 flags |= eTraversalNeeded;
3543 }
3544 if (what & layer_state_t::eFlagsChanged) {
3545 if (layer->setFlags(s.flags, s.mask))
3546 flags |= eTraversalNeeded;
3547 }
3548 if (what & layer_state_t::eCropChanged) {
3549 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3550 flags |= eTraversalNeeded;
3551 }
3552 if (what & layer_state_t::eFinalCropChanged) {
3553 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3554 flags |= eTraversalNeeded;
3555 }
3556 if (what & layer_state_t::eLayerStackChanged) {
3557 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3558 // We only allow setting layer stacks for top level layers,
3559 // everything else inherits layer stack from its parent.
3560 if (layer->hasParent()) {
3561 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3562 layer->getName().string());
3563 } else if (idx < 0) {
3564 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3565 "that also does not appear in the top level layer list. Something"
3566 " has gone wrong.", layer->getName().string());
3567 } else if (layer->setLayerStack(s.layerStack)) {
3568 mCurrentState.layersSortedByZ.removeAt(idx);
3569 mCurrentState.layersSortedByZ.add(layer);
3570 // we need traversal (state changed)
3571 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003572 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003573 }
3574 }
3575 if (what & layer_state_t::eDeferTransaction) {
3576 if (s.barrierHandle != nullptr) {
3577 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3578 } else if (s.barrierGbp != nullptr) {
3579 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3580 if (authenticateSurfaceTextureLocked(gbp)) {
3581 const auto& otherLayer =
3582 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3583 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3584 } else {
3585 ALOGE("Attempt to defer transaction to to an"
3586 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003587 }
3588 }
chaviw8b3871a2017-11-01 17:41:01 -07003589 // We don't trigger a traversal here because if no other state is
3590 // changed, we don't want this to cause any more work
3591 }
3592 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003593 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003594 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003595 if (!hadParent) {
3596 mCurrentState.layersSortedByZ.remove(layer);
3597 }
chaviw8b3871a2017-11-01 17:41:01 -07003598 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003599 }
chaviw8b3871a2017-11-01 17:41:01 -07003600 }
3601 if (what & layer_state_t::eReparentChildren) {
3602 if (layer->reparentChildren(s.reparentHandle)) {
3603 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003604 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003605 }
chaviw8b3871a2017-11-01 17:41:01 -07003606 if (what & layer_state_t::eDetachChildren) {
3607 layer->detachChildren();
3608 }
3609 if (what & layer_state_t::eOverrideScalingModeChanged) {
3610 layer->setOverrideScalingMode(s.overrideScalingMode);
3611 // We don't trigger a traversal here because if no other state is
3612 // changed, we don't want this to cause any more work
3613 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003614 return flags;
3615}
3616
chaviwca27f252018-02-06 16:46:39 -08003617void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3618 const layer_state_t& state = composerState.state;
3619 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3620
3621 sp<Layer> layer(client->getLayerUser(state.surface));
3622 if (layer == nullptr) {
3623 return;
3624 }
3625
3626 if (layer->isPendingRemoval()) {
3627 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3628 return;
3629 }
3630
3631 if (state.what & layer_state_t::eDestroySurface) {
3632 removeLayerLocked(mStateLock, layer);
3633 }
3634}
3635
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003636status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003637 const String8& name,
3638 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003639 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliuccd34842018-03-14 12:26:23 -07003640 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003641 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003642{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003643 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003644 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003645 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003646 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003647 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003648
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003649 status_t result = NO_ERROR;
3650
3651 sp<Layer> layer;
3652
Cody Northropbc755282017-03-31 12:00:08 -06003653 String8 uniqueName = getUniqueLayerName(name);
3654
Mathias Agopian3165cc22012-08-08 19:42:09 -07003655 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3656 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003657 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003658 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003659 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003660
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003661 break;
chaviw13fdc492017-06-27 12:40:18 -07003662 case ISurfaceComposerClient::eFXSurfaceColor:
3663 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003664 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003665 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003666 break;
Robert Carrd6f70352018-08-13 13:05:17 -07003667 case ISurfaceComposerClient::eFXSurfaceContainer:
3668 result = createContainerLayer(client,
3669 uniqueName, w, h, flags,
3670 handle, &layer);
3671 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003672 default:
3673 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003674 break;
3675 }
3676
Dan Stoza7d89d062015-04-30 13:29:25 -07003677 if (result != NO_ERROR) {
3678 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003679 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003680
Chia-I Wuab0c3192017-08-01 11:29:00 -07003681 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3682 // TODO b/64227542
3683 if (windowType == 441731) {
3684 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3685 layer->setPrimaryDisplayOnly();
3686 }
3687
Albert Chaulk479c60c2017-01-27 14:21:34 -05003688 layer->setInfo(windowType, ownerUid);
3689
Robert Carr1f0a16a2016-10-24 16:27:39 -07003690 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003691 if (result != NO_ERROR) {
3692 return result;
3693 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003694 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003695
3696 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003697 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003698}
3699
Cody Northropbc755282017-03-31 12:00:08 -06003700String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3701{
3702 bool matchFound = true;
3703 uint32_t dupeCounter = 0;
3704
3705 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3706 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3707
Dan Stoza9fdb7e02018-06-21 12:10:12 -07003708 // Grab the state lock since we're accessing mCurrentState
3709 Mutex::Autolock lock(mStateLock);
3710
Cody Northropbc755282017-03-31 12:00:08 -06003711 // Loop over layers until we're sure there is no matching name
3712 while (matchFound) {
3713 matchFound = false;
Dan Stoza9fdb7e02018-06-21 12:10:12 -07003714 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003715 if (layer->getName() == uniqueName) {
3716 matchFound = true;
3717 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3718 }
3719 });
3720 }
3721
3722 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3723
3724 return uniqueName;
3725}
3726
David Sodman0c69cad2017-08-21 12:12:51 -07003727status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003728 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3729 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003730{
3731 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003732 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003733 case PIXEL_FORMAT_TRANSPARENT:
3734 case PIXEL_FORMAT_TRANSLUCENT:
3735 format = PIXEL_FORMAT_RGBA_8888;
3736 break;
3737 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003738 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003739 break;
3740 }
3741
David Sodman0c69cad2017-08-21 12:12:51 -07003742 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3743 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003744 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003745 *handle = layer->getHandle();
3746 *gbp = layer->getProducer();
3747 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003748 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003749
David Sodman0c69cad2017-08-21 12:12:51 -07003750 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003751 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003752}
3753
chaviw13fdc492017-06-27 12:40:18 -07003754status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003755 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003756 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003757{
chaviw13fdc492017-06-27 12:40:18 -07003758 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003759 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003760 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003761}
3762
Robert Carrd6f70352018-08-13 13:05:17 -07003763status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3764 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3765 sp<IBinder>* handle, sp<Layer>* outLayer)
3766{
3767 *outLayer = new ContainerLayer(this, client, name, w, h, flags);
3768 *handle = (*outLayer)->getHandle();
3769 return NO_ERROR;
3770}
3771
3772
Mathias Agopianac9fa422013-02-11 16:40:36 -08003773status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003774{
Robert Carr9524cb32017-02-13 11:32:32 -08003775 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003776 status_t err = NO_ERROR;
3777 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003778 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003779 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003780 err = removeLayer(l);
3781 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3782 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003783 }
3784 return err;
3785}
3786
Mathias Agopian13127d82013-03-05 17:47:11 -08003787status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003788{
Mathias Agopian67106042013-03-14 19:18:13 -07003789 // called by ~LayerCleaner() when all references to the IBinder (handle)
3790 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003791 sp<Layer> l = layer.promote();
3792 if (l == nullptr) {
3793 // The layer has already been removed, carry on
3794 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003795 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003796 // If we have a parent, then we can continue to live as long as it does.
3797 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003798}
3799
Mathias Agopianb60314a2012-04-10 22:09:54 -07003800// ---------------------------------------------------------------------------
3801
Andy McFadden13a082e2012-08-24 10:16:42 -07003802void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003803 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003804 Vector<ComposerState> state;
3805 Vector<DisplayState> displays;
3806 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003807 d.what = DisplayState::eDisplayProjectionChanged |
3808 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003809 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003810 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003811 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003812 d.frame.makeInvalid();
3813 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003814 d.width = 0;
3815 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003816 displays.add(d);
3817 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003818 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3819 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003820
David Sodman105b7dc2017-11-04 20:28:14 -07003821 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003822 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003823 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003824
Brian Andersond0010582017-03-07 13:20:31 -08003825 // Use phase of 0 since phase is not known.
3826 // Use latency of 0, which will snap to the ideal latency.
3827 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003828}
3829
3830void SurfaceFlinger::initializeDisplays() {
3831 class MessageScreenInitialized : public MessageBase {
3832 SurfaceFlinger* flinger;
3833 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003834 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003835 virtual bool handler() {
3836 flinger->onInitializeDisplays();
3837 return true;
3838 }
3839 };
3840 sp<MessageBase> msg = new MessageScreenInitialized(this);
3841 postMessageAsync(msg); // we may be called from main thread, use async message
3842}
3843
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003844void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003845 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003846 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3847 this);
3848 int32_t type = hw->getDisplayType();
3849 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003850
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003851 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003852 return;
3853 }
3854
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003855 hw->setPowerMode(mode);
3856 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3857 ALOGW("Trying to set power mode for virtual display");
3858 return;
3859 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003860
Lloyd Pique4d234852018-01-22 17:21:36 -08003861 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003862 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003863 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3864 if (idx < 0) {
3865 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3866 return;
3867 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003868 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003869 }
3870
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003871 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003872 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003873 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003874 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3875 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003876 // FIXME: eventthread only knows about the main display right now
3877 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003878 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003879 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003880
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003881 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003882 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003883 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003884
3885 struct sched_param param = {0};
3886 param.sched_priority = 1;
3887 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3888 ALOGW("Couldn't set SCHED_FIFO on display on");
3889 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003890 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003891 // Turn off the display
3892 struct sched_param param = {0};
3893 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3894 ALOGW("Couldn't set SCHED_OTHER on display off");
3895 }
3896
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003897 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3898 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003899 disableHardwareVsync(true); // also cancels any in-progress resync
3900
Mathias Agopiancde87a32012-09-13 14:09:01 -07003901 // FIXME: eventthread only knows about the main display right now
3902 mEventThread->onScreenReleased();
3903 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003904
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003905 getHwComposer().setPowerMode(type, mode);
3906 mVisibleRegionsDirty = true;
3907 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003908 } else if (mode == HWC_POWER_MODE_DOZE ||
3909 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003910 // Update display while dozing
3911 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003912 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3913 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003914 // FIXME: eventthread only knows about the main display right now
3915 mEventThread->onScreenAcquired();
3916 resyncToHardwareVsync(true);
3917 }
3918 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3919 // Leave display going to doze
3920 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3921 disableHardwareVsync(true); // also cancels any in-progress resync
3922 // FIXME: eventthread only knows about the main display right now
3923 mEventThread->onScreenReleased();
3924 }
3925 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003926 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003927 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003928 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003929 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003930 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003931}
3932
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003933void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3934 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003935 SurfaceFlinger& mFlinger;
3936 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003937 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003938 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003939 MessageSetPowerMode(SurfaceFlinger& flinger,
3940 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3941 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003942 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003943 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003944 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003945 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003946 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003947 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003948 ALOGW("Attempt to set power mode = %d for virtual display",
3949 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003950 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003951 mFlinger.setPowerModeInternal(
3952 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003953 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003954 return true;
3955 }
3956 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003957 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003958 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003959}
3960
3961// ---------------------------------------------------------------------------
3962
Lloyd Pique755e3192018-01-31 16:46:15 -08003963status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3964 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003965 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003966
Mathias Agopianbd115332013-04-18 16:41:04 -07003967 IPCThreadState* ipc = IPCThreadState::self();
3968 const int pid = ipc->getCallingPid();
3969 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003970
Mathias Agopianbd115332013-04-18 16:41:04 -07003971 if ((uid != AID_SHELL) &&
3972 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003973 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003974 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003975 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003976 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003977 // (this would indicate SF is stuck, but we want to be able to
3978 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003979 status_t err = mStateLock.timedLock(s2ns(1));
3980 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003981 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003982 result.appendFormat(
3983 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3984 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003985 }
3986
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003987 bool dumpAll = true;
3988 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003989 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003990
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003991 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003992 if ((index < numArgs) &&
3993 (args[index] == String16("--list"))) {
3994 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003995 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003996 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003997 }
3998
3999 if ((index < numArgs) &&
4000 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004001 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004002 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004003 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004004 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004005
4006 if ((index < numArgs) &&
4007 (args[index] == String16("--latency-clear"))) {
4008 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004009 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004010 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004011 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004012
4013 if ((index < numArgs) &&
4014 (args[index] == String16("--dispsync"))) {
4015 index++;
4016 mPrimaryDispSync.dump(result);
4017 dumpAll = false;
4018 }
Dan Stozab90cf072015-03-05 11:05:59 -08004019
4020 if ((index < numArgs) &&
4021 (args[index] == String16("--static-screen"))) {
4022 index++;
4023 dumpStaticScreenStats(result);
4024 dumpAll = false;
4025 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004026
4027 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004028 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004029 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004030 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004031 dumpAll = false;
4032 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004033
4034 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4035 index++;
4036 dumpWideColorInfo(result);
4037 dumpAll = false;
4038 }
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004039
4040 if ((index < numArgs) &&
4041 (args[index] == String16("--enable-layer-stats"))) {
4042 index++;
4043 mLayerStats.enable();
4044 dumpAll = false;
4045 }
4046
4047 if ((index < numArgs) &&
4048 (args[index] == String16("--disable-layer-stats"))) {
4049 index++;
4050 mLayerStats.disable();
4051 dumpAll = false;
4052 }
4053
4054 if ((index < numArgs) &&
4055 (args[index] == String16("--clear-layer-stats"))) {
4056 index++;
4057 mLayerStats.clear();
4058 dumpAll = false;
4059 }
4060
4061 if ((index < numArgs) &&
4062 (args[index] == String16("--dump-layer-stats"))) {
4063 index++;
4064 mLayerStats.dump(result);
4065 dumpAll = false;
4066 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07004067
4068 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4069 index++;
4070 mTimeStats.parseArgs(asProto, args, index, result);
4071 dumpAll = false;
4072 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004073 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004074
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004075 if (dumpAll) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07004076 if (asProto) {
4077 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4078 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4079 } else {
4080 dumpAllLocked(args, index, result);
4081 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004082 }
4083
Mathias Agopian9795c422009-08-26 16:36:26 -07004084 if (locked) {
4085 mStateLock.unlock();
4086 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004087 }
4088 write(fd, result.string(), result.size());
4089 return NO_ERROR;
4090}
4091
Dan Stozac7014012014-02-14 15:03:43 -08004092void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4093 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004094{
Robert Carr2047fae2016-11-28 14:09:09 -08004095 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004096 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004097 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004098}
4099
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004100void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004101 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004102{
4103 String8 name;
4104 if (index < args.size()) {
4105 name = String8(args[index]);
4106 index++;
4107 }
4108
David Sodman105b7dc2017-11-04 20:28:14 -07004109 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004110 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08004111 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004112
4113 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004114 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004115 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004116 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004117 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004118 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004119 }
Robert Carr2047fae2016-11-28 14:09:09 -08004120 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004121 }
4122}
4123
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004124void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004125 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004126{
4127 String8 name;
4128 if (index < args.size()) {
4129 name = String8(args[index]);
4130 index++;
4131 }
4132
Robert Carr2047fae2016-11-28 14:09:09 -08004133 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004134 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004135 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004136 }
Robert Carr2047fae2016-11-28 14:09:09 -08004137 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004138
Svetoslavd85084b2014-03-20 10:28:31 -07004139 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004140}
4141
Jamie Gennis6547ff42013-07-16 20:12:42 -07004142// This should only be called from the main thread. Otherwise it would need
4143// the lock and should use mCurrentState rather than mDrawingState.
4144void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004145 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004146 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004147 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004148
4149 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4150}
4151
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004152void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004153{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004154 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004155
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004156 if (isLayerTripleBufferingDisabled())
4157 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004158
4159 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004160 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004161 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004162 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004163 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4164 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004165 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004166}
4167
Dan Stozab90cf072015-03-05 11:05:59 -08004168void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4169{
4170 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004171 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4172 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004173 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004174 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004175 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4176 b + 1, bucketTimeSec, percent);
4177 }
David Sodman4a36e932017-11-07 14:29:47 -08004178 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004179 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004180 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004181 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004182 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004183}
4184
Dan Stozae77c7662016-05-13 11:37:28 -07004185void SurfaceFlinger::recordBufferingStats(const char* layerName,
4186 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004187 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4188 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004189 for (const auto& segment : history) {
4190 if (!segment.usedThirdBuffer) {
4191 stats.twoBufferTime += segment.totalTime;
4192 }
4193 if (segment.occupancyAverage < 1.0f) {
4194 stats.doubleBufferedTime += segment.totalTime;
4195 } else if (segment.occupancyAverage < 2.0f) {
4196 stats.tripleBufferedTime += segment.totalTime;
4197 }
4198 ++stats.numSegments;
4199 stats.totalTime += segment.totalTime;
4200 }
4201}
4202
Brian Andersond6927fb2016-07-23 23:37:30 -07004203void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4204 result.appendFormat("Layer frame timestamps:\n");
4205
4206 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4207 const size_t count = currentLayers.size();
4208 for (size_t i=0 ; i<count ; i++) {
4209 currentLayers[i]->dumpFrameEvents(result);
4210 }
4211}
4212
Dan Stozae77c7662016-05-13 11:37:28 -07004213void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4214 result.append("Buffering stats:\n");
4215 result.append(" [Layer name] <Active time> <Two buffer> "
4216 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004217 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004218 typedef std::tuple<std::string, float, float, float> BufferTuple;
4219 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004220 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004221 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004222 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004223 if (stats.numSegments == 0) {
4224 continue;
4225 }
4226 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4227 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4228 stats.totalTime;
4229 float doubleBufferRatio = static_cast<float>(
4230 stats.doubleBufferedTime) / stats.totalTime;
4231 float tripleBufferRatio = static_cast<float>(
4232 stats.tripleBufferedTime) / stats.totalTime;
4233 sorted.insert({activeTime, {name, twoBufferRatio,
4234 doubleBufferRatio, tripleBufferRatio}});
4235 }
4236 for (const auto& sortedPair : sorted) {
4237 float activeTime = sortedPair.first;
4238 const BufferTuple& values = sortedPair.second;
4239 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4240 std::get<0>(values).c_str(), activeTime,
4241 std::get<1>(values), std::get<2>(values),
4242 std::get<3>(values));
4243 }
4244 result.append("\n");
4245}
4246
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004247void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4248 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004249 result.appendFormat("DisplayColorSetting: %s\n",
4250 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004251
4252 // TODO: print out if wide-color mode is active or not
4253
4254 for (size_t d = 0; d < mDisplays.size(); d++) {
4255 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4256 int32_t hwcId = displayDevice->getHwcDisplayId();
4257 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4258 continue;
4259 }
4260
4261 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004262 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004263 for (auto&& mode : modes) {
4264 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4265 }
4266
Peiyong Lina52f0292018-03-14 17:26:31 -07004267 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004268 result.appendFormat(" Current color mode: %s (%d)\n",
4269 decodeColorMode(currentMode).c_str(), currentMode);
4270 }
4271 result.append("\n");
4272}
4273
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004274LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004275 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004276 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4277 const State& state = useDrawing ? mDrawingState : mCurrentState;
4278 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004279 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004280 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004281 });
4282
4283 return layersProto;
4284}
4285
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004286LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4287 LayersProto layersProto;
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004288 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004289
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004290 SizeProto* resolution = layersProto.mutable_resolution();
4291 resolution->set_w(displayDevice->getWidth());
4292 resolution->set_h(displayDevice->getHeight());
4293
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004294 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4295 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4296 layersProto.set_global_transform(
4297 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4298
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004299 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004300 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004301 LayerProto* layerProto = layersProto.add_layers();
4302 layer->writeToProto(layerProto, hwcId);
4303 }
4304 });
4305
4306 return layersProto;
4307}
4308
Mathias Agopian74d211a2013-04-22 16:55:35 +02004309void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4310 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004311{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004312 bool colorize = false;
4313 if (index < args.size()
4314 && (args[index] == String16("--color"))) {
4315 colorize = true;
4316 index++;
4317 }
4318
4319 Colorizer colorizer(colorize);
4320
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004321 // figure out if we're stuck somewhere
4322 const nsecs_t now = systemTime();
4323 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4324 const nsecs_t inTransaction(mDebugInTransaction);
4325 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4326 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4327
4328 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004329 * Dump library configuration.
4330 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004331
4332 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004333 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004334 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004335 appendSfConfigString(result);
4336 appendUiConfigString(result);
4337 appendGuiConfigString(result);
4338 result.append("\n");
4339
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004340 result.append("\nWide-Color information:\n");
4341 dumpWideColorInfo(result);
4342
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004343 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004344 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004345 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004346 result.append(SyncFeatures::getInstance().toString());
4347 result.append("\n");
4348
David Sodman105b7dc2017-11-04 20:28:14 -07004349 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004350
Andy McFadden41d67d72014-04-25 16:58:34 -07004351 colorizer.bold(result);
4352 result.append("DispSync configuration: ");
4353 colorizer.reset(result);
Jorim Jaggie203e042018-06-19 15:57:08 +02004354 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4355 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
4356 result.appendFormat(
4357 "app phase %" PRId64 " ns, "
4358 "sf phase %" PRId64 " ns, "
4359 "early app phase %" PRId64 " ns, "
4360 "early sf phase %" PRId64 " ns, "
4361 "early app gl phase %" PRId64 " ns, "
4362 "early sf gl phase %" PRId64 " ns, "
4363 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4364 vsyncPhaseOffsetNs,
4365 sfVsyncPhaseOffsetNs,
4366 appEarlyOffset,
4367 sfEarlyOffset,
4368 appEarlyGlOffset,
4369 sfEarlyOffset,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004370 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004371 result.append("\n");
4372
Dan Stozab90cf072015-03-05 11:05:59 -08004373 // Dump static screen stats
4374 result.append("\n");
4375 dumpStaticScreenStats(result);
4376 result.append("\n");
4377
Dan Stozae77c7662016-05-13 11:37:28 -07004378 dumpBufferingStats(result);
4379
Andy McFadden4803b742012-09-24 19:07:20 -07004380 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004381 * Dump the visible layer list
4382 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004383 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004384 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004385 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4386 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004387 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004388
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004389 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004390 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004391 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004392 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004393
4394 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004395 * Dump Display state
4396 */
4397
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004398 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004399 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004400 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004401 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4402 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004403 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004404 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004405 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004406
4407 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004408 * Dump SurfaceFlinger global state
4409 */
4410
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004411 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004412 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004413 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004414
Mathias Agopian888c8222012-08-04 21:10:38 -07004415 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004416 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004417
David Sodmanbc815282017-11-05 18:57:52 -08004418 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004419
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004420 if (hw) {
4421 hw->undefinedRegion.dump(result, "undefinedRegion");
4422 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4423 hw->getOrientation(), hw->isDisplayOn());
4424 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004425 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004426 " last eglSwapBuffers() time: %f us\n"
4427 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004428 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004429 " refresh-rate : %f fps\n"
4430 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004431 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004432 " gpu_to_cpu_unsupported : %d\n"
4433 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004434 mLastSwapBufferTime/1000.0,
4435 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004436 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004437 1e9 / activeConfig->getVsyncPeriod(),
4438 activeConfig->getDpiX(),
4439 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004440 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004441
Mathias Agopian74d211a2013-04-22 16:55:35 +02004442 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004443 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004444
Mathias Agopian74d211a2013-04-22 16:55:35 +02004445 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004446 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004447
4448 /*
4449 * VSYNC state
4450 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004451 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004452 result.append("\n");
4453
4454 /*
Yichi Chen738966b2018-09-15 14:51:18 +08004455 * Tracing state
4456 */
4457 mTracing.dump(result);
4458 result.append("\n");
4459
4460 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004461 * HWC layer minidump
4462 */
4463 for (size_t d = 0; d < mDisplays.size(); d++) {
4464 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4465 int32_t hwcId = displayDevice->getHwcDisplayId();
4466 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4467 continue;
4468 }
4469
4470 result.appendFormat("Display %d HWC layers:\n", hwcId);
4471 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004472 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004473 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004474 });
Dan Stozae22aec72016-08-01 13:20:59 -07004475 result.append("\n");
4476 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004477
4478 /*
4479 * Dump HWComposer state
4480 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004481 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004482 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004483 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004484 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004485 result.appendFormat(" h/w composer %s\n",
4486 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004487 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004488
4489 /*
4490 * Dump gralloc state
4491 */
4492 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4493 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004494
4495 /*
4496 * Dump VrFlinger state if in use.
4497 */
4498 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4499 result.append("VrFlinger state:\n");
4500 result.append(mVrFlinger->Dump().c_str());
4501 result.append("\n");
4502 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004503}
4504
Mathias Agopian13127d82013-03-05 17:47:11 -08004505const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004506SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004507 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004508 wp<IBinder> dpy;
4509 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4510 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4511 dpy = mDisplays.keyAt(i);
4512 break;
4513 }
4514 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004515 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004516 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4517 // Just use the primary display so we have something to return
4518 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4519 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004520 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004521}
4522
Chia-I Wu28f320b2018-05-03 11:02:56 -07004523void SurfaceFlinger::updateColorMatrixLocked() {
4524 mat4 colorMatrix;
4525 if (mGlobalSaturationFactor != 1.0f) {
4526 // Rec.709 luma coefficients
4527 float3 luminance{0.213f, 0.715f, 0.072f};
4528 luminance *= 1.0f - mGlobalSaturationFactor;
4529 mat4 saturationMatrix = mat4(
4530 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4531 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4532 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4533 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4534 );
4535 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4536 } else {
4537 colorMatrix = mClientColorMatrix * mDaltonizer();
4538 }
4539
4540 if (mCurrentState.colorMatrix != colorMatrix) {
4541 mCurrentState.colorMatrix = colorMatrix;
4542 mCurrentState.colorMatrixChanged = true;
4543 setTransactionFlags(eTransactionNeeded);
4544 }
4545}
4546
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004547status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004548 switch (code) {
4549 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004550 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004551 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004552 case CLEAR_ANIMATION_FRAME_STATS:
4553 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004554 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004555 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004556 case ENABLE_VSYNC_INJECTIONS:
4557 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004558 {
4559 // codes that require permission check
Robert Carrd4ae7f32018-06-07 16:10:57 -07004560 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4561 IPCThreadState* ipc = IPCThreadState::self();
4562 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4563 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004564 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004565 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004566 break;
4567 }
Robert Carr1db73f62016-12-21 12:58:51 -08004568 /*
4569 * Calling setTransactionState is safe, because you need to have been
4570 * granted a reference to Client* and Handle* to do anything with it.
4571 *
4572 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4573 */
4574 case SET_TRANSACTION_STATE:
4575 case CREATE_SCOPED_CONNECTION:
4576 {
4577 return OK;
4578 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004579 case CAPTURE_SCREEN:
4580 {
4581 // codes that require permission check
4582 IPCThreadState* ipc = IPCThreadState::self();
4583 const int pid = ipc->getCallingPid();
4584 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004585 if ((uid != AID_GRAPHICS) &&
4586 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004587 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004588 return PERMISSION_DENIED;
4589 }
4590 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004591 }
chaviwa76b2712017-09-20 12:02:26 -07004592 case CAPTURE_LAYERS: {
4593 IPCThreadState* ipc = IPCThreadState::self();
4594 const int pid = ipc->getCallingPid();
4595 const int uid = ipc->getCallingUid();
4596 if ((uid != AID_GRAPHICS) &&
4597 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4598 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4599 return PERMISSION_DENIED;
4600 }
4601 break;
4602 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004603 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004604 return OK;
4605}
4606
4607status_t SurfaceFlinger::onTransact(
4608 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4609{
4610 status_t credentialCheck = CheckTransactCodeCredentials(code);
4611 if (credentialCheck != OK) {
4612 return credentialCheck;
4613 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004614
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004615 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4616 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004617 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004618 IPCThreadState* ipc = IPCThreadState::self();
4619 const int uid = ipc->getCallingUid();
4620 if (CC_UNLIKELY(uid != AID_SYSTEM
4621 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004622 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004623 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004624 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004625 return PERMISSION_DENIED;
4626 }
4627 int n;
4628 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004629 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004630 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004631 return NO_ERROR;
4632 case 1002: // SHOW_UPDATES
4633 n = data.readInt32();
4634 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004635 invalidateHwcGeometry();
4636 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004637 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004638 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004639 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004640 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004641 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004642 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004643 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004644 setTransactionFlags(
4645 eTransactionNeeded|
4646 eDisplayTransactionNeeded|
4647 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004648 return NO_ERROR;
4649 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004650 case 1006:{ // send empty update
4651 signalRefresh();
4652 return NO_ERROR;
4653 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004654 case 1008: // toggle use of hw composer
4655 n = data.readInt32();
4656 mDebugDisableHWC = n ? 1 : 0;
4657 invalidateHwcGeometry();
4658 repaintEverything();
4659 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004660 case 1009: // toggle use of transform hint
4661 n = data.readInt32();
4662 mDebugDisableTransformHint = n ? 1 : 0;
4663 invalidateHwcGeometry();
4664 repaintEverything();
4665 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004666 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004667 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004668 reply->writeInt32(0);
4669 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004670 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004671 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004672 return NO_ERROR;
4673 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004674 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004675 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004676 return NO_ERROR;
4677 }
4678 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004679 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004680 // daltonize
4681 n = data.readInt32();
4682 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004683 case 1:
4684 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4685 break;
4686 case 2:
4687 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4688 break;
4689 case 3:
4690 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4691 break;
4692 default:
4693 mDaltonizer.setType(ColorBlindnessType::None);
4694 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004695 }
4696 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004697 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004698 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004699 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004700 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004701
4702 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004703 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004704 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004705 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004706 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004707 // apply a color matrix
4708 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004709 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004710 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004711 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004712 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004713 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004714 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004715 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004716 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004717 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004718 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004719
4720 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4721 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004722 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004723 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4724 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4725 }
4726
Chia-I Wu28f320b2018-05-03 11:02:56 -07004727 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004728 return NO_ERROR;
4729 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004730 // This is an experimental interface
4731 // Needs to be shifted to proper binder interface when we productize
4732 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004733 n = data.readInt32();
4734 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004735 return NO_ERROR;
4736 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004737 case 1017: {
4738 n = data.readInt32();
4739 mForceFullDamage = static_cast<bool>(n);
4740 return NO_ERROR;
4741 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004742 case 1018: { // Modify Choreographer's phase offset
4743 n = data.readInt32();
4744 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4745 return NO_ERROR;
4746 }
4747 case 1019: { // Modify SurfaceFlinger's phase offset
4748 n = data.readInt32();
4749 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4750 return NO_ERROR;
4751 }
Irvel468051e2016-06-13 16:44:44 -07004752 case 1020: { // Layer updates interceptor
4753 n = data.readInt32();
4754 if (n) {
4755 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004756 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004757 }
4758 else{
4759 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004760 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004761 }
4762 return NO_ERROR;
4763 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004764 case 1021: { // Disable HWC virtual displays
4765 n = data.readInt32();
4766 mUseHwcVirtualDisplays = !n;
4767 return NO_ERROR;
4768 }
Romain Guy0147a172017-06-01 13:53:56 -07004769 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004770 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004771 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004772
Chia-I Wu28f320b2018-05-03 11:02:56 -07004773 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004774 return NO_ERROR;
4775 }
Romain Guy54f154a2017-10-24 21:40:32 +01004776 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004777 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004778 invalidateHwcGeometry();
4779 repaintEverything();
4780 return NO_ERROR;
4781 }
4782 case 1024: { // Is wide color gamut rendering/color management supported?
4783 reply->writeBool(hasWideColorDisplay);
4784 return NO_ERROR;
4785 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004786 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004787 n = data.readInt32();
4788 if (n) {
Yichi Chen738966b2018-09-15 14:51:18 +08004789 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004790 mTracing.enable();
4791 doTracing("tracing.enable");
4792 reply->writeInt32(NO_ERROR);
4793 } else {
Yichi Chen738966b2018-09-15 14:51:18 +08004794 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004795 status_t err = mTracing.disable();
4796 reply->writeInt32(err);
4797 }
4798 return NO_ERROR;
4799 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004800 case 1026: { // Get layer tracing status
4801 reply->writeBool(mTracing.isEnabled());
4802 return NO_ERROR;
4803 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004804 // Is a DisplayColorSetting supported?
4805 case 1027: {
Chia-I Wu0d711262018-05-21 15:19:35 -07004806 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
4807 if (!hw) {
4808 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004809 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004810
4811 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4812 switch (setting) {
4813 case DisplayColorSetting::MANAGED:
4814 reply->writeBool(hasWideColorDisplay);
4815 break;
4816 case DisplayColorSetting::UNMANAGED:
4817 reply->writeBool(true);
4818 break;
4819 case DisplayColorSetting::ENHANCED:
4820 reply->writeBool(hw->hasRenderIntent(RenderIntent::ENHANCE));
4821 break;
4822 default: // vendor display color setting
4823 reply->writeBool(hw->hasRenderIntent(static_cast<RenderIntent>(setting)));
4824 break;
4825 }
4826 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004827 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004828 }
4829 }
4830 return err;
4831}
4832
Steven Thomas6d8110b2017-08-31 18:24:21 -07004833void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004834 android_atomic_or(1, &mRepaintEverything);
4835 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004836}
4837
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004838// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4839class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004840public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004841 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4842 ~WindowDisconnector() {
4843 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004844 }
4845
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004846private:
4847 ANativeWindow* mWindow;
4848 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004849};
4850
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004851status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4852 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4853 int32_t minLayerZ, int32_t maxLayerZ,
4854 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004855 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004856 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004857
chaviwa76b2712017-09-20 12:02:26 -07004858 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4859
Chia-I Wu82144eb2018-08-24 15:34:02 -07004860 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
4861
Chia-I Wu946e37e2018-08-23 12:55:44 -07004862 sp<DisplayDevice> device;
4863 {
4864 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004865
Chia-I Wu946e37e2018-08-23 12:55:44 -07004866 device = getDisplayDeviceLocked(display);
4867 if (!device) return BAD_VALUE;
4868
Chia-I Wu6df54002018-08-28 12:57:23 -07004869 // set the requested width/height to the logical display viewport size
4870 // by default
4871 if (reqWidth == 0 || reqHeight == 0) {
4872 reqWidth = uint32_t(device->getViewport().width());
4873 reqHeight = uint32_t(device->getViewport().height());
Chia-I Wu946e37e2018-08-23 12:55:44 -07004874 }
Yiwei Zhangf4e02872018-08-20 16:42:23 -07004875 }
4876
Chia-I Wu82144eb2018-08-24 15:34:02 -07004877 DisplayRenderArea renderArea(device, sourceCrop, reqWidth, reqHeight, renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07004878
4879 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4880 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004881 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004882}
4883
4884status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004885 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004886 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004887 ATRACE_CALL();
4888
4889 class LayerRenderArea : public RenderArea {
4890 public:
Robert Carr578038f2018-03-09 12:25:24 -08004891 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4892 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
Chia-I Wu07f190f2018-08-23 13:44:43 -07004893 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004894 mLayer(layer),
4895 mCrop(crop),
Chia-I Wu75dcd902018-08-28 11:01:44 -07004896 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08004897 mFlinger(flinger),
4898 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004899 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004900 Rect getBounds() const override {
4901 const Layer::State& layerState(mLayer->getDrawingState());
4902 return Rect(layerState.active.w, layerState.active.h);
4903 }
4904 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4905 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4906 bool isSecure() const override { return false; }
Chia-I Wu75dcd902018-08-28 11:01:44 -07004907 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004908 Rect getSourceCrop() const override {
4909 if (mCrop.isEmpty()) {
4910 return getBounds();
4911 } else {
4912 return mCrop;
4913 }
4914 }
Robert Carr578038f2018-03-09 12:25:24 -08004915 class ReparentForDrawing {
4916 public:
4917 const sp<Layer>& oldParent;
4918 const sp<Layer>& newParent;
4919
4920 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4921 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004922 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004923 }
Robert Carr15eae092018-03-23 13:43:53 -07004924 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004925 };
4926
4927 void render(std::function<void()> drawLayers) override {
Chia-I Wu75dcd902018-08-28 11:01:44 -07004928 const Rect sourceCrop = getSourceCrop();
4929 // no need to check rotation because there is none
4930 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
4931 sourceCrop.height() != getReqHeight();
4932
Robert Carr578038f2018-03-09 12:25:24 -08004933 if (!mChildrenOnly) {
4934 mTransform = mLayer->getTransform().inverse();
4935 drawLayers();
4936 } else {
4937 Rect bounds = getBounds();
4938 screenshotParentLayer =
4939 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4940 bounds.getWidth(), bounds.getHeight(), 0);
4941
4942 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4943 drawLayers();
4944 }
4945 }
chaviwa76b2712017-09-20 12:02:26 -07004946
chaviwa76b2712017-09-20 12:02:26 -07004947 private:
chaviw7206d492017-11-10 16:16:12 -08004948 const sp<Layer> mLayer;
4949 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004950
4951 // In the "childrenOnly" case we reparent the children to a screenshot
4952 // layer which has no properties set and which does not draw.
4953 sp<ContainerLayer> screenshotParentLayer;
4954 Transform mTransform;
Chia-I Wu75dcd902018-08-28 11:01:44 -07004955 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08004956
4957 SurfaceFlinger* mFlinger;
4958 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004959 };
4960
4961 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4962 auto parent = layerHandle->owner.promote();
4963
chaviw7206d492017-11-10 16:16:12 -08004964 if (parent == nullptr || parent->isPendingRemoval()) {
4965 ALOGE("captureLayers called with a removed parent");
4966 return NAME_NOT_FOUND;
4967 }
4968
Robert Carr578038f2018-03-09 12:25:24 -08004969 const int uid = IPCThreadState::self()->getCallingUid();
4970 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4971 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4972 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4973 return PERMISSION_DENIED;
4974 }
4975
chaviw7206d492017-11-10 16:16:12 -08004976 Rect crop(sourceCrop);
4977 if (sourceCrop.width() <= 0) {
4978 crop.left = 0;
4979 crop.right = parent->getCurrentState().active.w;
4980 }
4981
4982 if (sourceCrop.height() <= 0) {
4983 crop.top = 0;
4984 crop.bottom = parent->getCurrentState().active.h;
4985 }
4986
4987 int32_t reqWidth = crop.width() * frameScale;
4988 int32_t reqHeight = crop.height() * frameScale;
4989
Chia-I Wu946e37e2018-08-23 12:55:44 -07004990 // really small crop or frameScale
4991 if (reqWidth <= 0) {
4992 reqWidth = 1;
4993 }
4994 if (reqHeight <= 0) {
4995 reqHeight = 1;
4996 }
4997
Robert Carr578038f2018-03-09 12:25:24 -08004998 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004999
Robert Carr578038f2018-03-09 12:25:24 -08005000 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005001 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5002 if (!layer->isVisible()) {
5003 return;
Robert Carr578038f2018-03-09 12:25:24 -08005004 } else if (childrenOnly && layer == parent.get()) {
5005 return;
chaviwa76b2712017-09-20 12:02:26 -07005006 }
5007 visitor(layer);
5008 });
5009 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005010 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005011}
5012
5013status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5014 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005015 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005016 bool useIdentityTransform) {
5017 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005018
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005019 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5020 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5021 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5022 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005023
5024 // This mutex protects syncFd and captureResult for communication of the return values from the
5025 // main thread back to this Binder thread
5026 std::mutex captureMutex;
5027 std::condition_variable captureCondition;
5028 std::unique_lock<std::mutex> captureLock(captureMutex);
5029 int syncFd = -1;
5030 std::optional<status_t> captureResult;
5031
Robert Carr03480e22018-01-04 16:02:06 -08005032 const int uid = IPCThreadState::self()->getCallingUid();
5033 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5034
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005035 sp<LambdaMessage> message = new LambdaMessage([&]() {
5036 // If there is a refresh pending, bug out early and tell the binder thread to try again
5037 // after the refresh.
5038 if (mRefreshPending) {
5039 ATRACE_NAME("Skipping screenshot for now");
5040 std::unique_lock<std::mutex> captureLock(captureMutex);
5041 captureResult = std::make_optional<status_t>(EAGAIN);
5042 captureCondition.notify_one();
5043 return;
5044 }
5045
5046 status_t result = NO_ERROR;
5047 int fd = -1;
5048 {
5049 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08005050 renderArea.render([&]() {
5051 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5052 useIdentityTransform, forSystem, &fd);
5053 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005054 }
5055
5056 {
5057 std::unique_lock<std::mutex> captureLock(captureMutex);
5058 syncFd = fd;
5059 captureResult = std::make_optional<status_t>(result);
5060 captureCondition.notify_one();
5061 }
5062 });
5063
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005064 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005065 if (result == NO_ERROR) {
5066 captureCondition.wait(captureLock, [&]() { return captureResult; });
5067 while (*captureResult == EAGAIN) {
5068 captureResult.reset();
5069 result = postMessageAsync(message);
5070 if (result != NO_ERROR) {
5071 return result;
5072 }
5073 captureCondition.wait(captureLock, [&]() { return captureResult; });
5074 }
5075 result = *captureResult;
5076 }
5077
5078 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005079 sync_wait(syncFd, -1);
5080 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005081 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005082
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005083 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005084}
5085
chaviwa76b2712017-09-20 12:02:26 -07005086void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5087 TraverseLayersFunction traverseLayers, bool yswap,
5088 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005089 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005090
Lloyd Pique144e1162017-12-20 16:44:52 -08005091 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005092
5093 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005094 const auto raHeight = renderArea.getHeight();
5095
5096 const auto reqWidth = renderArea.getReqWidth();
5097 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wubecab0f2018-08-27 14:54:37 -07005098 const auto sourceCrop = renderArea.getSourceCrop();
5099 const auto rotation = renderArea.getRotationFlags();
chaviwa76b2712017-09-20 12:02:26 -07005100
Chia-I Wu36574d92018-05-16 10:54:36 -07005101 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5102 engine.setOutputDataSpace(Dataspace::SRGB);
5103 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005104
Mathias Agopian180f10d2013-04-10 22:55:41 -07005105 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005106 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005107
5108 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005109 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005110 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005111 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005112
chaviw50da5042018-04-09 13:49:37 -07005113 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005114 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005115 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005116
chaviwa76b2712017-09-20 12:02:26 -07005117 traverseLayers([&](Layer* layer) {
chaviwa76b2712017-09-20 12:02:26 -07005118 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005119 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005120}
5121
chaviwa76b2712017-09-20 12:02:26 -07005122status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5123 TraverseLayersFunction traverseLayers,
5124 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005125 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005126 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005127 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005128 ATRACE_CALL();
5129
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005130 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005131
5132 traverseLayers([&](Layer* layer) {
5133 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5134 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005135
Robert Carr03480e22018-01-04 16:02:06 -08005136 // We allow the system server to take screenshots of secure layers for
5137 // use in situations like the Screen-rotation animation and place
5138 // the impetus on WindowManager to not persist them.
5139 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005140 ALOGW("FB is protected: PERMISSION_DENIED");
5141 return PERMISSION_DENIED;
5142 }
5143
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005144 // this binds the given EGLImage as a framebuffer for the
5145 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005146 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005147 if (bufferBond.getStatus() != NO_ERROR) {
5148 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005149 return INVALID_OPERATION;
5150 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005151
Dan Stozaabcda352017-06-01 14:37:39 -07005152 // this will in fact render into our dequeued buffer
5153 // via an FBO, which means we didn't have to create
5154 // an EGLSurface and therefore we're not
5155 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005156 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005157
Dan Stozaabcda352017-06-01 14:37:39 -07005158 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005159 getRenderEngine().finish();
5160 *outSyncFd = -1;
5161
chaviwa76b2712017-09-20 12:02:26 -07005162 const auto reqWidth = renderArea.getReqWidth();
5163 const auto reqHeight = renderArea.getReqHeight();
5164
Dan Stozaabcda352017-06-01 14:37:39 -07005165 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5166 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005167 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005168 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005169 } else {
5170 base::unique_fd syncFd = getRenderEngine().flush();
5171 if (syncFd < 0) {
5172 getRenderEngine().finish();
5173 }
5174 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005175 }
5176
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005177 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005178}
5179
Mathias Agopiand5556842013-09-19 17:08:37 -07005180void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005181 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005182 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005183 for (size_t y = 0; y < h; y++) {
5184 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5185 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005186 if (p[x] != 0xFF000000) return;
5187 }
5188 }
chaviwa76b2712017-09-20 12:02:26 -07005189 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005190
Robert Carr2047fae2016-11-28 14:09:09 -08005191 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005192 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005193 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005194 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5195 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5196 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5197 static_cast<float>(state.color.a));
5198 i++;
5199 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005200 }
5201}
5202
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005203// ---------------------------------------------------------------------------
5204
Dan Stoza412903f2017-04-27 13:42:17 -07005205void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5206 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005207}
5208
Dan Stoza412903f2017-04-27 13:42:17 -07005209void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5210 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005211}
5212
chaviwa76b2712017-09-20 12:02:26 -07005213void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5214 int32_t maxLayerZ,
5215 const LayerVector::Visitor& visitor) {
5216 // We loop through the first level of layers without traversing,
5217 // as we need to interpret min/max layer Z in the top level Z space.
5218 for (const auto& layer : mDrawingState.layersSortedByZ) {
5219 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5220 continue;
5221 }
5222 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005223 // relative layers are traversed in Layer::traverseInZOrder
5224 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005225 continue;
5226 }
5227 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005228 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5229 return;
5230 }
chaviwa76b2712017-09-20 12:02:26 -07005231 if (!layer->isVisible()) {
5232 return;
5233 }
5234 visitor(layer);
5235 });
5236 }
5237}
5238
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005239}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005240
5241
5242#if defined(__gl_h_)
5243#error "don't include gl/gl.h in this file"
5244#endif
5245
5246#if defined(__gl2_h_)
5247#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005248#endif