blob: 7022c36717abaeb4862bad40bd8eac9bd31cb2fe [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Chia-I Wud49d6692018-06-27 07:17:41 +080040#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060041#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070043#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080048#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070050#include <renderengine/RenderEngine.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070051#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Robert Carr578038f2018-03-09 12:25:24 -080065#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070066#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070067#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020070#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080072#include "DdmConnection.h"
Robert Carr578038f2018-03-09 12:25:24 -080073#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Steven Thomasb02664d2017-07-26 18:48:28 -070079#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070080#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070084#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070085#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070086#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070087#include "Scheduler/EventControlThread.h"
88#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070089#include "Scheduler/InjectVSyncSource.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070090#include "Scheduler/Scheduler.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070091
Mathias Agopianff2ed702013-09-01 21:36:12 -070092#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070093
David Sodman7e4ae112018-02-09 15:02:28 -080094#include "android-base/stringprintf.h"
95
Jiyong Park4b20c2e2017-01-14 19:45:11 +090096#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080097#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -070098#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080099#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900100#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900101
chaviw1d044282017-09-27 12:19:28 -0700102#include <layerproto/LayerProtoParser.h>
103
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800104#define DISPLAY_COUNT 1
105
Mathias Agopianfee2b462013-07-03 12:34:01 -0700106/*
107 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
108 * black pixels.
109 */
110#define DEBUG_SCREENSHOTS false
111
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800112namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700113
Jaesoo Lee43518572017-01-23 19:03:16 +0900114using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900115using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700116using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700117using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700118using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700119using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900120
Steven Thomasb02664d2017-07-26 18:48:28 -0700121namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700122
123#pragma clang diagnostic push
124#pragma clang diagnostic error "-Wswitch-enum"
125
126bool isWideColorMode(const ColorMode colorMode) {
127 switch (colorMode) {
128 case ColorMode::DISPLAY_P3:
129 case ColorMode::ADOBE_RGB:
130 case ColorMode::DCI_P3:
131 case ColorMode::BT2020:
132 case ColorMode::BT2100_PQ:
133 case ColorMode::BT2100_HLG:
134 return true;
135 case ColorMode::NATIVE:
136 case ColorMode::STANDARD_BT601_625:
137 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
138 case ColorMode::STANDARD_BT601_525:
139 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
140 case ColorMode::STANDARD_BT709:
141 case ColorMode::SRGB:
142 return false;
143 }
144 return false;
145}
146
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700147ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
148 switch (rotation) {
149 case ISurfaceComposer::eRotateNone:
150 return ui::Transform::ROT_0;
151 case ISurfaceComposer::eRotate90:
152 return ui::Transform::ROT_90;
153 case ISurfaceComposer::eRotate180:
154 return ui::Transform::ROT_180;
155 case ISurfaceComposer::eRotate270:
156 return ui::Transform::ROT_270;
157 }
158 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
159 return ui::Transform::ROT_0;
160}
161
Peiyong Linfca547f2018-07-09 13:03:33 -0700162#pragma clang diagnostic pop
163
Steven Thomasb02664d2017-07-26 18:48:28 -0700164class ConditionalLock {
165public:
166 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
167 if (lock) {
168 mMutex.lock();
169 }
170 }
171 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
172private:
173 Mutex& mMutex;
174 bool mLocked;
175};
Peiyong Linfca547f2018-07-09 13:03:33 -0700176
Steven Thomasb02664d2017-07-26 18:48:28 -0700177} // namespace anonymous
178
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800179// ---------------------------------------------------------------------------
180
Mathias Agopian99b49842011-06-27 16:05:52 -0700181const String16 sHardwareTest("android.permission.HARDWARE_TEST");
182const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
183const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
184const String16 sDump("android.permission.DUMP");
185
186// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800187int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
188int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700189int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700190bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800191uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800192bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800193bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800194int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800195// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600196bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700197int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700198bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700199bool SurfaceFlinger::useContextPriority;
Peiyong Lin0256f722018-08-31 15:45:10 -0700200Dataspace SurfaceFlinger::compositionDataSpace = Dataspace::V0_SRGB;
201ui::PixelFormat SurfaceFlinger::compositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700202
Kalle Raitaa099a242017-01-11 11:17:29 -0800203std::string getHwcServiceName() {
204 char value[PROPERTY_VALUE_MAX] = {};
205 property_get("debug.sf.hwc_service_name", value, "default");
206 ALOGI("Using HWComposer service: '%s'", value);
207 return std::string(value);
208}
209
210bool useTrebleTestingOverride() {
211 char value[PROPERTY_VALUE_MAX] = {};
212 property_get("debug.sf.treble_testing_override", value, "false");
213 ALOGI("Treble testing override: '%s'", value);
214 return std::string(value) == "true";
215}
216
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800217std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
218 switch(displayColorSetting) {
219 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700220 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800221 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700222 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800223 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700224 return std::string("Enhanced");
225 default:
226 return std::string("Unknown ") +
227 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800228 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800229}
230
Lloyd Pique99d3da52018-01-22 17:48:03 -0800231NativeWindowSurface::~NativeWindowSurface() = default;
232
233namespace impl {
234
235class NativeWindowSurface final : public android::NativeWindowSurface {
236public:
237 static std::unique_ptr<android::NativeWindowSurface> create(
238 const sp<IGraphicBufferProducer>& producer) {
239 return std::make_unique<NativeWindowSurface>(producer);
240 }
241
242 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
243 : surface(new Surface(producer, false)) {}
244
245 ~NativeWindowSurface() override = default;
246
247private:
248 sp<ANativeWindow> getNativeWindow() const override { return surface; }
249
250 void preallocateBuffers() override { surface->allocateBuffers(); }
251
252 sp<Surface> surface;
253};
254
255} // namespace impl
256
David Sodmanbc815282017-11-05 18:57:52 -0800257SurfaceFlingerBE::SurfaceFlingerBE()
258 : mHwcServiceName(getHwcServiceName()),
259 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800260 mFrameBuckets(),
261 mTotalTime(0),
262 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800263 mComposerSequenceId(0) {
264}
265
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800266SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800267 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800268 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700269 mTransactionPending(false),
270 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700271 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700272 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700273 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800274 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700275 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800277 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800278 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800279 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800280 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700281 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700282 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700283 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700284 mDebugInTransaction(0),
285 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700286 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700287 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700288 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800289 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800290 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800291 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700292 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800293 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800294 mCreateBufferQueue(&BufferQueue::createBufferQueue),
295 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800296
297SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800298 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800299
300 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
301 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
302
303 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
304 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
305
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800306 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
307 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800308
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700309 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
310 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
311
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700312 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
313 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
314
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800315 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
316 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
317
Steven Thomas050b2c82017-03-06 11:45:16 -0800318 // Vr flinger is only enabled on Daydream ready devices.
319 useVrFlinger = getBool< ISurfaceFlingerConfigs,
320 &ISurfaceFlingerConfigs::useVrFlinger>(false);
321
Fabien Sanglard1971b632017-03-10 14:50:03 -0800322 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
323 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
324
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600325 hasWideColorDisplay =
326 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700327 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700328 getBool<V1_2::ISurfaceFlingerConfigs,
329 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
330
331 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
332 if (surfaceFlingerConfigsServiceV1_2) {
333 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
334 [&](Dataspace tmpDataSpace, ui::PixelFormat tmpPixelFormat) {
335 compositionDataSpace = tmpDataSpace;
336 compositionPixelFormat = tmpPixelFormat;
337 });
338 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600339
Peiyong Linb3839ad2018-09-05 15:37:19 -0700340 useContextPriority = getBool<ISurfaceFlingerConfigs,
341 &ISurfaceFlingerConfigs::useContextPriority>(true);
342
Iris Chang7501ed62018-04-30 14:45:42 +0800343 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700344 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
345 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800346 V1_1::DisplayOrientation::ORIENTATION_0);
347
348 switch (primaryDisplayOrientation) {
349 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700350 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800351 break;
352 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700353 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800354 break;
355 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700356 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800357 break;
358 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700359 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800360 break;
361 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700362 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800363
Lloyd Pique41be5d22018-06-21 13:11:48 -0700364 // Note: We create a local temporary with the real DispSync implementation
365 // type temporarily so we can initialize it with the configured values,
366 // before storing it for more generic use using the interface type.
367 auto primaryDispSync = std::make_unique<impl::DispSync>("PrimaryDispSync");
368 primaryDispSync->init(SurfaceFlinger::hasSyncFramework,
369 SurfaceFlinger::dispSyncPresentTimeOffset);
370 mPrimaryDispSync = std::move(primaryDispSync);
Saurabh Shahf4174532017-07-13 10:45:07 -0700371
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800372 // debugging stuff...
373 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700374
Mathias Agopianb4b17302013-03-20 18:36:41 -0700375 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700376 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700377
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800378 property_get("debug.sf.showupdates", value, "0");
379 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700380
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700381 property_get("debug.sf.ddms", value, "0");
382 mDebugDDMS = atoi(value);
383 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700384 if (!startDdmConnection()) {
385 // start failed, and DDMS debugging not enabled
386 mDebugDDMS = 0;
387 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700388 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700389 ALOGI_IF(mDebugRegion, "showupdates enabled");
390 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700391
392 property_get("debug.sf.disable_backpressure", value, "0");
393 mPropagateBackpressure = !atoi(value);
394 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700395
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800396 property_get("debug.sf.enable_hwc_vds", value, "0");
397 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800398 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800399
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800400 property_get("ro.sf.disable_triple_buffer", value, "1");
401 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800402 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700403
Yiwei Zhang243b3782018-05-15 17:40:04 -0700404 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700405 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
406 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
407
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200408 property_get("debug.sf.early_phase_offset_ns", value, "-1");
409 const int earlySfOffsetNs = atoi(value);
410
411 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
412 const int earlyGlSfOffsetNs = atoi(value);
413
414 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
415 const int earlyAppOffsetNs = atoi(value);
416
417 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
418 const int earlyGlAppOffsetNs = atoi(value);
419
Ana Krulec98b5b242018-08-10 15:03:23 -0700420 property_get("debug.sf.use_scheduler", value, "0");
421 mUseScheduler = atoi(value);
422
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200423 const VSyncModulator::Offsets earlyOffsets =
424 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
425 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
426 const VSyncModulator::Offsets earlyGlOffsets =
427 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
428 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
429 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
430 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700431
Romain Guy11d63f42017-07-20 12:47:14 -0700432 // We should be reading 'persist.sys.sf.color_saturation' here
433 // but since /data may be encrypted, we need to wait until after vold
434 // comes online to attempt to read the property. The property is
435 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800436
437 if (useTrebleTestingOverride()) {
438 // Without the override SurfaceFlinger cannot connect to HIDL
439 // services that are not listed in the manifests. Considered
440 // deriving the setting from the set service name, but it
441 // would be brittle if the name that's not 'default' is used
442 // for production purposes later on.
443 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
444 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800445}
446
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800447void SurfaceFlinger::onFirstRef()
448{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800449 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800450}
451
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800452SurfaceFlinger::~SurfaceFlinger()
453{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800454}
455
Dan Stozac7014012014-02-14 15:03:43 -0800456void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800457{
458 // the window manager died on us. prepare its eulogy.
459
Andy McFadden13a082e2012-08-24 10:16:42 -0700460 // restore initial conditions (default device unblank, etc)
461 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800462
463 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700464 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800465}
466
Robert Carr1db73f62016-12-21 12:58:51 -0800467static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700468 status_t err = client->initCheck();
469 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800470 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800471 }
Robert Carr1db73f62016-12-21 12:58:51 -0800472 return nullptr;
473}
474
475sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
476 return initClient(new Client(this));
477}
478
479sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
480 const sp<IGraphicBufferProducer>& gbp) {
481 if (authenticateSurfaceTexture(gbp) == false) {
482 return nullptr;
483 }
484 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
485 if (layer == nullptr) {
486 return nullptr;
487 }
488
489 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800490}
491
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700492sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
493 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700494{
495 class DisplayToken : public BBinder {
496 sp<SurfaceFlinger> flinger;
497 virtual ~DisplayToken() {
498 // no more references, this display must be terminated
499 Mutex::Autolock _l(flinger->mStateLock);
500 flinger->mCurrentState.displays.removeItem(this);
501 flinger->setTransactionFlags(eDisplayTransactionNeeded);
502 }
503 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700504 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700505 : flinger(flinger) {
506 }
507 };
508
509 sp<BBinder> token = new DisplayToken(this);
510
511 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700512 DisplayDeviceState info;
513 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700514 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700515 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700516 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800517 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700518 return token;
519}
520
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700521void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700522 Mutex::Autolock _l(mStateLock);
523
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700524 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700525 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700526 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700527 return;
528 }
529
530 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700531 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700532 ALOGE("destroyDisplay called for non-virtual display");
533 return;
534 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700535 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700536 mCurrentState.displays.removeItemsAt(idx);
537 setTransactionFlags(eDisplayTransactionNeeded);
538}
539
Mathias Agopiane57f2922012-08-09 16:29:12 -0700540sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700541 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700542 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800543 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700544 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700545 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700546}
547
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800548void SurfaceFlinger::bootFinished()
549{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700550 if (mStartPropertySetThread->join() != NO_ERROR) {
551 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800552 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800553 const nsecs_t now = systemTime();
554 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000555 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700556
557 // wait patiently for the window manager death
558 const String16 name("window");
559 sp<IBinder> window(defaultServiceManager()->getService(name));
560 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700561 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700562 }
563
Steven Thomas050b2c82017-03-06 11:45:16 -0800564 if (mVrFlinger) {
565 mVrFlinger->OnBootFinished();
566 }
567
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700568 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700569 // formerly we would just kill the process, but we now ask it to exit so it
570 // can choose where to stop the animation.
571 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700572
573 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
574 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
575 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700576
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800577 postMessageAsync(new LambdaMessage([this] {
578 readPersistentProperties();
579 mBootStage = BootStage::FINISHED;
580 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800581}
582
Dan Stoza436ccf32018-06-21 12:10:12 -0700583uint32_t SurfaceFlinger::getNewTexture() {
584 {
585 std::lock_guard lock(mTexturePoolMutex);
586 if (!mTexturePool.empty()) {
587 uint32_t name = mTexturePool.back();
588 mTexturePool.pop_back();
589 ATRACE_INT("TexturePoolSize", mTexturePool.size());
590 return name;
591 }
592
593 // The pool was too small, so increase it for the future
594 ++mTexturePoolSize;
595 }
596
597 // The pool was empty, so we need to get a new texture name directly using a
598 // blocking call to the main thread
599 uint32_t name = 0;
600 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
601 return name;
602}
603
Mathias Agopian3f844832013-08-07 21:24:32 -0700604void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700605 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700606}
607
Wei Wangf9b05ee2017-07-19 20:59:39 -0700608// Do not call property_set on main thread which will be blocked by init
609// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700610void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700611 ALOGI( "SurfaceFlinger's main thread ready to run. "
612 "Initializing graphics H/W...");
613
Thierry Strudel2924d012017-08-14 15:19:37 -0700614 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900615
Steven Thomasb02664d2017-07-26 18:48:28 -0700616 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800617
Steven Thomasb02664d2017-07-26 18:48:28 -0700618 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700619 if (mUseScheduler) {
620 mScheduler = std::make_unique<Scheduler>();
621 mAppConnectionHandle =
622 mScheduler->createConnection("appConnection", mPrimaryDispSync.get(),
623 SurfaceFlinger::vsyncPhaseOffsetNs,
624 [this] { resyncWithRateLimit(); },
625 impl::EventThread::InterceptVSyncsCallback());
626 mSfConnectionHandle =
627 mScheduler->createConnection("sfConnection", mPrimaryDispSync.get(),
628 SurfaceFlinger::sfVsyncPhaseOffsetNs,
629 [this] { resyncWithRateLimit(); },
630 [this](nsecs_t timestamp) {
631 mInterceptor->saveVSyncEvent(timestamp);
632 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800633
Ana Krulec98b5b242018-08-10 15:03:23 -0700634 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700635 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
636 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700637 } else {
638 mEventThreadSource =
639 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
640 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
641 mEventThread =
642 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
643 [this] { resyncWithRateLimit(); },
644 impl::EventThread::InterceptVSyncsCallback(),
645 "appEventThread");
646 mSfEventThreadSource =
647 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
648 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
649
650 mSFEventThread =
651 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
652 [this] { resyncWithRateLimit(); },
653 [this](nsecs_t timestamp) {
654 mInterceptor->saveVSyncEvent(timestamp);
655 },
656 "sfEventThread");
657 mEventQueue->setEventThread(mSFEventThread.get());
658 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
659 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800660
Steven Thomasb02664d2017-07-26 18:48:28 -0700661 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700662 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700663 renderEngineFeature |= (useColorManagement ?
664 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700665 renderEngineFeature |= (useContextPriority ?
666 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700667
668 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
669 getBE().mRenderEngine =
Peiyong Linf11f39b2018-09-05 14:37:41 -0700670 renderengine::RenderEngine::create(static_cast<int32_t>(compositionPixelFormat),
671 renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800672 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700673
674 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
675 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800676 getBE().mHwc.reset(
677 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700678 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800679 // Process any initial hotplug and resulting display changes.
680 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700681 const auto display = getDefaultDisplayDeviceLocked();
682 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
683 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
684 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800685
Lloyd Piquefcd86612017-12-14 17:15:36 -0800686 // make the default display GLContext current so that we can create textures
687 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700688 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800689
Steven Thomas050b2c82017-03-06 11:45:16 -0800690 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700691 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700692 // This callback is called from the vr flinger dispatch thread. We
693 // need to call signalTransaction(), which requires holding
694 // mStateLock when we're not on the main thread. Acquiring
695 // mStateLock from the vr flinger dispatch thread might trigger a
696 // deadlock in surface flinger (see b/66916578), so post a message
697 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700698 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700699 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
700 mVrFlingerRequestsDisplay = requestDisplay;
701 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700702 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800703 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700704 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
705 getHwComposer()
706 .getHwcDisplayId(display->getId())
707 .value_or(0),
708 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800709 if (!mVrFlinger) {
710 ALOGE("Failed to start vrflinger");
711 }
712 }
713
Lloyd Pique379adc12018-01-22 17:31:47 -0800714 mEventControlThread = std::make_unique<impl::EventControlThread>(
715 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700716
Mathias Agopian92a979a2012-08-02 18:32:23 -0700717 // initialize our drawing state
718 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700719
Andy McFadden13a082e2012-08-24 10:16:42 -0700720 // set initial conditions (e.g. unblank default device)
721 initializeDisplays();
722
David Sodmanbc815282017-11-05 18:57:52 -0800723 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700724
Wei Wangf9b05ee2017-07-19 20:59:39 -0700725 // Inform native graphics APIs whether the present timestamp is supported:
726 if (getHwComposer().hasCapability(
727 HWC2::Capability::PresentFenceIsNotReliable)) {
728 mStartPropertySetThread = new StartPropertySetThread(false);
729 } else {
730 mStartPropertySetThread = new StartPropertySetThread(true);
731 }
732
733 if (mStartPropertySetThread->Start() != NO_ERROR) {
734 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800735 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800736
Chia-I Wud49d6692018-06-27 07:17:41 +0800737 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
738 // is used to saturate legacy sRGB content. However, to make sure the same color under
739 // Display P3 will be saturated to the same color, we intentionally break the API spec
740 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
741 // such saturation matrix on Display P3 is understood fully, the API should always return
742 // identify matrix.
743 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
744 Dataspace::SRGB_LINEAR);
745
746 // we will apply this on Display P3.
747 if (mEnhancedSaturationMatrix != mat4()) {
748 ColorSpace srgb(ColorSpace::sRGB());
749 ColorSpace displayP3(ColorSpace::DisplayP3());
750 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
751 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
752 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
753 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800754
Dan Stoza9e56aa02015-11-02 13:00:03 -0800755 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700756}
757
Romain Guy11d63f42017-07-20 12:47:14 -0700758void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700759 Mutex::Autolock _l(mStateLock);
760
Romain Guy11d63f42017-07-20 12:47:14 -0700761 char value[PROPERTY_VALUE_MAX];
762
763 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800764 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700765 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800766 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100767
768 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700769 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700770}
771
Mathias Agopiana67e4182012-06-19 17:26:12 -0700772void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800773 // Start boot animation service by setting a property mailbox
774 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700775 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800776 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700777 if (mStartPropertySetThread->join() != NO_ERROR) {
778 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800779 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700780}
781
Mathias Agopian875d8e12013-06-07 15:35:48 -0700782size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800783 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700784}
785
Mathias Agopian875d8e12013-06-07 15:35:48 -0700786size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800787 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700788}
789
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800790// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800791
Jamie Gennis582270d2011-08-17 18:19:00 -0700792bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800793 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800794 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800795 return authenticateSurfaceTextureLocked(bufferProducer);
796}
797
798bool SurfaceFlinger::authenticateSurfaceTextureLocked(
799 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800800 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800801 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800802}
803
Brian Anderson6b376712017-04-04 10:51:39 -0700804status_t SurfaceFlinger::getSupportedFrameTimestamps(
805 std::vector<FrameEvent>* outSupported) const {
806 *outSupported = {
807 FrameEvent::REQUESTED_PRESENT,
808 FrameEvent::ACQUIRE,
809 FrameEvent::LATCH,
810 FrameEvent::FIRST_REFRESH_START,
811 FrameEvent::LAST_REFRESH_START,
812 FrameEvent::GPU_COMPOSITION_DONE,
813 FrameEvent::DEQUEUE_READY,
814 FrameEvent::RELEASE,
815 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700816 ConditionalLock _l(mStateLock,
817 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700818 if (!getHwComposer().hasCapability(
819 HWC2::Capability::PresentFenceIsNotReliable)) {
820 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
821 }
822 return NO_ERROR;
823}
824
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700825status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
826 Vector<DisplayInfo>* configs) {
827 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700828 return BAD_VALUE;
829 }
830
Jesse Hall692c7232012-11-08 15:41:56 -0800831 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700832 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
833 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700834 type = i;
835 break;
836 }
837 }
838
839 if (type < 0) {
840 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700841 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700842
Mathias Agopian8b736f12012-08-13 17:54:26 -0700843 // TODO: Not sure if display density should handled by SF any longer
844 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700845 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700846 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700847 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800848 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700849 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700850 }
851 return density;
852 }
853 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700854 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700855 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700856 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700857 return getDensityFromProperty("ro.sf.lcd_density"); }
858 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700859
Dan Stoza7f7da322014-05-02 15:26:25 -0700860 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700861
Steven Thomas6d8110b2017-08-31 18:24:21 -0700862 ConditionalLock _l(mStateLock,
863 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800864 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700865 DisplayInfo info = DisplayInfo();
866
Dan Stoza9e56aa02015-11-02 13:00:03 -0800867 float xdpi = hwConfig->getDpiX();
868 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700869
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700870 info.w = hwConfig->getWidth();
871 info.h = hwConfig->getHeight();
872 // Default display viewport to display width and height
873 info.viewportW = info.w;
874 info.viewportH = info.h;
875
Dan Stoza7f7da322014-05-02 15:26:25 -0700876 if (type == DisplayDevice::DISPLAY_PRIMARY) {
877 // The density of the device is provided by a build property
878 float density = Density::getBuildDensity() / 160.0f;
879 if (density == 0) {
880 // the build doesn't provide a density -- this is wrong!
881 // use xdpi instead
882 ALOGE("ro.sf.lcd_density must be defined as a build property");
883 density = xdpi / 160.0f;
884 }
885 if (Density::getEmuDensity()) {
886 // if "qemu.sf.lcd_density" is specified, it overrides everything
887 xdpi = ydpi = density = Density::getEmuDensity();
888 density /= 160.0f;
889 }
890 info.density = density;
891
892 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700893 const auto display = getDefaultDisplayDeviceLocked();
894 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700895
896 // This is for screenrecord
897 const Rect viewport = display->getViewport();
898 if (viewport.isValid()) {
899 info.viewportW = uint32_t(viewport.getWidth());
900 info.viewportH = uint32_t(viewport.getHeight());
901 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700902 } else {
903 // TODO: where should this value come from?
904 static const int TV_DENSITY = 213;
905 info.density = TV_DENSITY / 160.0f;
906 info.orientation = 0;
907 }
908
Dan Stoza7f7da322014-05-02 15:26:25 -0700909 info.xdpi = xdpi;
910 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800911 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900912 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800913
Andy McFadden91b2ca82014-06-13 14:04:23 -0700914 // This is how far in advance a buffer must be queued for
915 // presentation at a given time. If you want a buffer to appear
916 // on the screen at time N, you must submit the buffer before
917 // (N - presentationDeadline).
918 //
919 // Normally it's one full refresh period (to give SF a chance to
920 // latch the buffer), but this can be reduced by configuring a
921 // DispSync offset. Any additional delays introduced by the hardware
922 // composer or panel must be accounted for here.
923 //
924 // We add an additional 1ms to allow for processing time and
925 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800926 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800927 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700928
929 // All non-virtual displays are currently considered secure.
930 info.secure = true;
931
Iris Chang7501ed62018-04-30 14:45:42 +0800932 if (type == DisplayDevice::DISPLAY_PRIMARY &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700933 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800934 std::swap(info.w, info.h);
935 }
936
Michael Wright28f24d02016-07-12 13:30:53 -0700937 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700938 }
939
Dan Stoza7f7da322014-05-02 15:26:25 -0700940 return NO_ERROR;
941}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700942
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700943status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
944 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700945 return BAD_VALUE;
946 }
947
948 // FIXME for now we always return stats for the primary display
949 memset(stats, 0, sizeof(*stats));
Lloyd Pique41be5d22018-06-21 13:11:48 -0700950 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
951 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700952 return NO_ERROR;
953}
954
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700955int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
956 const auto display = getDisplayDevice(displayToken);
957 if (!display) {
958 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800959 return BAD_VALUE;
960 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700961
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700962 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700963}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700964
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700965void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
966 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700967 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700968 return;
969 }
970
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700971 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700972 ALOGW("Trying to set config for virtual display");
973 return;
974 }
975
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700976 display->setActiveConfig(mode);
977 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700978}
979
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700980status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700981 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700982 Vector<DisplayInfo> configs;
983 getDisplayConfigs(displayToken, &configs);
984 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
985 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
986 configs.size());
987 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700988 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700989 const auto display = getDisplayDevice(displayToken);
990 if (!display) {
991 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
992 displayToken.get());
993 } else if (display->isVirtual()) {
994 ALOGW("Attempt to set active config %d for virtual display", mode);
995 } else {
996 setActiveConfigInternal(display, mode);
997 }
998 }));
999
Mathias Agopian888c8222012-08-04 21:10:38 -07001000 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001001}
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001002status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1003 Vector<ColorMode>* outColorModes) {
1004 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001005 return BAD_VALUE;
1006 }
1007
Michael Wright28f24d02016-07-12 13:30:53 -07001008 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001009 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
1010 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -07001011 type = i;
1012 break;
1013 }
1014 }
1015
1016 if (type < 0) {
1017 return type;
1018 }
1019
Peiyong Lina52f0292018-03-14 17:26:31 -07001020 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001021 {
1022 ConditionalLock _l(mStateLock,
1023 std::this_thread::get_id() != mMainThreadId);
1024 modes = getHwComposer().getColorModes(type);
1025 }
Michael Wright28f24d02016-07-12 13:30:53 -07001026 outColorModes->clear();
1027 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1028
1029 return NO_ERROR;
1030}
1031
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001032ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1033 if (const auto display = getDisplayDevice(displayToken)) {
1034 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001035 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001036 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001037}
1038
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001039void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1040 Dataspace dataSpace, RenderIntent renderIntent) {
1041 ColorMode currentMode = display->getActiveColorMode();
1042 Dataspace currentDataSpace = display->getCompositionDataSpace();
1043 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001044
Peiyong Lin38e9a562018-04-10 16:24:20 -07001045 if (mode == currentMode && dataSpace == currentDataSpace &&
1046 renderIntent == currentRenderIntent) {
1047 return;
1048 }
1049
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001050 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001051 ALOGW("Trying to set config for virtual display");
1052 return;
1053 }
1054
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001055 display->setActiveColorMode(mode);
1056 display->setCompositionDataSpace(dataSpace);
1057 display->setActiveRenderIntent(renderIntent);
1058 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001059
1060 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001061 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1062 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001063}
1064
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001065status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001066 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001067 Vector<ColorMode> modes;
1068 getDisplayColorModes(displayToken, &modes);
1069 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1070 if (mode < ColorMode::NATIVE || !exists) {
1071 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1072 decodeColorMode(mode).c_str(), mode, displayToken.get());
1073 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001074 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001075 const auto display = getDisplayDevice(displayToken);
1076 if (!display) {
1077 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1078 decodeColorMode(mode).c_str(), mode, displayToken.get());
1079 } else if (display->isVirtual()) {
1080 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1081 decodeColorMode(mode).c_str(), mode);
1082 } else {
1083 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1084 RenderIntent::COLORIMETRIC);
1085 }
1086 }));
1087
Michael Wright28f24d02016-07-12 13:30:53 -07001088 return NO_ERROR;
1089}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001090
Svetoslavd85084b2014-03-20 10:28:31 -07001091status_t SurfaceFlinger::clearAnimationFrameStats() {
1092 Mutex::Autolock _l(mStateLock);
1093 mAnimFrameTracker.clearStats();
1094 return NO_ERROR;
1095}
1096
1097status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1098 Mutex::Autolock _l(mStateLock);
1099 mAnimFrameTracker.getStats(outStats);
1100 return NO_ERROR;
1101}
1102
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001103status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1104 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001105 Mutex::Autolock _l(mStateLock);
1106
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001107 const auto display = getDisplayDeviceLocked(displayToken);
1108 if (!display) {
1109 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001110 return BAD_VALUE;
1111 }
1112
Peiyong Linfb069302018-04-25 14:34:31 -07001113 // At this point the DisplayDeivce should already be set up,
1114 // meaning the luminance information is already queried from
1115 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001116 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001117 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1118 capabilities.getDesiredMaxLuminance(),
1119 capabilities.getDesiredMaxAverageLuminance(),
1120 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001121
1122 return NO_ERROR;
1123}
1124
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001125status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001126 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001127 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001128
Chia-I Wu90f669f2017-10-05 14:24:41 -07001129 if (mInjectVSyncs == enable) {
1130 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001131 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001132
Ana Krulec98b5b242018-08-10 15:03:23 -07001133 // TODO(akrulec): Part of the Injector should be refactored, so that it
1134 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001135 if (enable) {
1136 ALOGV("VSync Injections enabled");
1137 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001138 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001139 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001140 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001141 impl::EventThread::InterceptVSyncsCallback(),
1142 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001143 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001144 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001145 } else {
1146 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001147 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001148 }
1149
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001150 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001151 }));
1152
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001153 return NO_ERROR;
1154}
1155
1156status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001157 Mutex::Autolock _l(mStateLock);
1158
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001159 if (!mInjectVSyncs) {
1160 ALOGE("VSync Injections not enabled");
1161 return BAD_VALUE;
1162 }
1163 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1164 ALOGV("Injecting VSync inside SurfaceFlinger");
1165 mVSyncInjector->onInjectSyncEvent(when);
1166 }
1167 return NO_ERROR;
1168}
1169
Lloyd Pique755e3192018-01-31 16:46:15 -08001170status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1171 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001172 // Try to acquire a lock for 1s, fail gracefully
1173 const status_t err = mStateLock.timedLock(s2ns(1));
1174 const bool locked = (err == NO_ERROR);
1175 if (!locked) {
1176 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1177 return TIMED_OUT;
1178 }
1179
1180 outLayers->clear();
1181 mCurrentState.traverseInZOrder([&](Layer* layer) {
1182 outLayers->push_back(layer->getLayerDebugInfo());
1183 });
1184
1185 mStateLock.unlock();
1186 return NO_ERROR;
1187}
1188
Peiyong Lin0256f722018-08-31 15:45:10 -07001189status_t SurfaceFlinger::getCompositionPreference(Dataspace* outDataSpace,
1190 ui::PixelFormat* outPixelFormat) const {
1191 *outDataSpace = compositionDataSpace;
1192 *outPixelFormat = compositionPixelFormat;
1193 return NO_ERROR;
1194}
1195
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001196// ----------------------------------------------------------------------------
1197
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001198sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1199 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001200 if (mUseScheduler) {
1201 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1202 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1203 } else {
1204 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1205 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001206 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001207 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1208 return mSFEventThread->createEventConnection();
1209 } else {
1210 return mEventThread->createEventConnection();
1211 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001212 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001213}
1214
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001215// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001216
1217void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001218 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001219}
1220
1221void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001222 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001223}
1224
1225void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001226 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001227}
1228
1229void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001230 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001231 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001232}
1233
1234status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001235 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001236 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001237}
1238
1239status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001240 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001241 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001242 if (res == NO_ERROR) {
1243 msg->wait();
1244 }
1245 return res;
1246}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001247
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001248void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001249 do {
1250 waitForEvent();
1251 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001252}
1253
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001254void SurfaceFlinger::enableHardwareVsync() {
1255 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001256 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001257 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001258 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001259 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001260 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001261}
1262
Jesse Hall948fe0c2013-10-14 12:56:09 -07001263void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001264 Mutex::Autolock _l(mHWVsyncLock);
1265
Jesse Hall948fe0c2013-10-14 12:56:09 -07001266 if (makeAvailable) {
1267 mHWVsyncAvailable = true;
1268 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001269 // Hardware vsync is not currently available, so abort the resync
1270 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001271 return;
1272 }
1273
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001274 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1275 if (!getHwComposer().isConnected(displayId)) {
1276 return;
1277 }
1278
1279 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001280 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001281
Lloyd Pique41be5d22018-06-21 13:11:48 -07001282 mPrimaryDispSync->reset();
1283 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001284
1285 if (!mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001286 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001287 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001288 mPrimaryHWVsyncEnabled = true;
1289 }
1290}
1291
Jesse Hall948fe0c2013-10-14 12:56:09 -07001292void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001293 Mutex::Autolock _l(mHWVsyncLock);
1294 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001295 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001296 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001297 mPrimaryHWVsyncEnabled = false;
1298 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001299 if (makeUnavailable) {
1300 mHWVsyncAvailable = false;
1301 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001302}
1303
Tim Murray4a4e4a22016-04-19 16:29:23 +00001304void SurfaceFlinger::resyncWithRateLimit() {
1305 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001306
1307 // No explicit locking is needed here since EventThread holds a lock while calling this method
1308 static nsecs_t sLastResyncAttempted = 0;
1309 const nsecs_t now = systemTime();
1310 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001311 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001312 }
Dan Stoza57164302017-05-08 14:03:54 -07001313 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001314}
1315
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001316void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1317 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001318 ATRACE_NAME("SF onVsync");
1319
Steven Thomas3cfac282017-02-06 12:29:30 -08001320 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001321 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001322 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001323 return;
1324 }
1325
1326 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001327 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001328 return;
1329 }
1330
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001331 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1332 // For now, we don't do anything with external display vsyncs.
1333 return;
1334 }
1335
Jamie Gennisd1700752013-10-14 12:22:52 -07001336 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001337
Jamie Gennisd1700752013-10-14 12:22:52 -07001338 { // Scope for the lock
1339 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001340 if (mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001341 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001342 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001343 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001344
1345 if (needsHwVsync) {
1346 enableHardwareVsync();
1347 } else {
1348 disableHardwareVsync(false);
1349 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001350}
1351
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001352void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001353 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1354 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001355}
1356
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001357void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001358 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001359 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001360 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001361
Lloyd Piqueba04e622017-12-14 17:11:26 -08001362 // Ignore events that do not have the right sequenceId.
1363 if (sequenceId != getBE().mComposerSequenceId) {
1364 return;
1365 }
1366
Steven Thomasb02664d2017-07-26 18:48:28 -07001367 // Only lock if we're not on the main thread. This function is normally
1368 // called on a hwbinder thread, but for the primary display it's called on
1369 // the main thread with the state lock already held, so don't attempt to
1370 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001371 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001372
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001373 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001374
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001375 if (std::this_thread::get_id() == mMainThreadId) {
1376 // Process all pending hot plug events immediately if we are on the main thread.
1377 processDisplayHotplugEventsLocked();
1378 }
1379
Lloyd Piqueba04e622017-12-14 17:11:26 -08001380 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001381}
1382
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001383void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001384 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001385 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001386 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001387 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001388 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001389}
1390
Dan Stoza9e56aa02015-11-02 13:00:03 -08001391void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001392 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001393 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001394 getHwComposer().setVsyncEnabled(disp,
1395 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001396}
1397
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001398// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001399void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001400 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001401 // Clear the drawing state so that the logic inside of
1402 // handleTransactionLocked will fire. It will determine the delta between
1403 // mCurrentState and mDrawingState and re-apply all changes when we make the
1404 // transition.
1405 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001406 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001407 mDisplays.clear();
1408}
1409
Steven Thomas050b2c82017-03-06 11:45:16 -08001410void SurfaceFlinger::updateVrFlinger() {
1411 if (!mVrFlinger)
1412 return;
1413 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001414 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001415 return;
1416 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001417
David Sodman105b7dc2017-11-04 20:28:14 -07001418 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001419 ALOGE("Vr flinger is only supported for remote hardware composer"
1420 " service connections. Ignoring request to transition to vr"
1421 " flinger.");
1422 mVrFlingerRequestsDisplay = false;
1423 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001424 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001425
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001426 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001427
Steven Thomas0123ac62018-07-12 11:32:34 -07001428 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001429 LOG_ALWAYS_FATAL_IF(!display);
1430 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001431 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1432 // called below. Clear the reference now so we don't accidentally use it
1433 // later.
1434 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001435
Steven Thomasb02664d2017-07-26 18:48:28 -07001436 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001437 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001438 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001439
Steven Thomasb02664d2017-07-26 18:48:28 -07001440 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001441 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001442 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1443 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001444 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001445
David Sodman105b7dc2017-11-04 20:28:14 -07001446 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1447 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001448
1449 if (vrFlingerRequestsDisplay) {
1450 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001451 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001452
1453 mVisibleRegionsDirty = true;
1454 invalidateHwcGeometry();
1455
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001456 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001457 display = getDefaultDisplayDeviceLocked();
1458 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001459 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001460
Steven Thomasb02664d2017-07-26 18:48:28 -07001461 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001462 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001463 const nsecs_t period = activeConfig->getVsyncPeriod();
1464 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001465
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001466 // The present fences returned from vr_hwc are not an accurate
1467 // representation of vsync times.
Lloyd Pique41be5d22018-06-21 13:11:48 -07001468 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1469 !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001470
Steven Thomasb02664d2017-07-26 18:48:28 -07001471 // Use phase of 0 since phase is not known.
1472 // Use latency of 0, which will snap to the ideal latency.
1473 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001474
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001475 resyncToHardwareVsync(false);
1476
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001477 android_atomic_or(1, &mRepaintEverything);
1478 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001479}
1480
Mathias Agopian4fec8732012-06-29 14:12:52 -07001481void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001482 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001483 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001484 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001485 bool frameMissed = !mHadClientComposition &&
1486 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001487 (mPreviousPresentFence->getSignalTime() ==
1488 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001489 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001490 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001491 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001492 mTimeStats.incrementMissedFrames();
1493 if (mPropagateBackpressure) {
1494 signalLayerUpdate();
1495 break;
1496 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001497 }
Dan Stoza50182882016-07-08 12:02:20 -07001498
Steven Thomas050b2c82017-03-06 11:45:16 -08001499 // Now that we're going to make it to the handleMessageTransaction()
1500 // call below it's safe to call updateVrFlinger(), which will
1501 // potentially trigger a display handoff.
1502 updateVrFlinger();
1503
Dan Stoza6b9454d2014-11-07 16:00:59 -08001504 bool refreshNeeded = handleMessageTransaction();
1505 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001506 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001507 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001508 // Signal a refresh if a transaction modified the window state,
1509 // a new buffer was latched, or if HWC has requested a full
1510 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001511 signalRefresh();
1512 }
1513 break;
1514 }
1515 case MessageQueue::REFRESH: {
1516 handleMessageRefresh();
1517 break;
1518 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001519 }
1520}
1521
Dan Stoza6b9454d2014-11-07 16:00:59 -08001522bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001523 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001524 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001525 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001526 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001527 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001528 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001529}
1530
Mathias Agopian4fec8732012-06-29 14:12:52 -07001531void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001532 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001533
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001534 mRefreshPending = false;
1535
David Sodmanfa9b2af2017-12-24 13:28:59 -08001536 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
David Sodman2b406362017-12-15 13:33:47 -08001537 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001538 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001539 calculateWorkingSet();
David Sodman10a41ff2018-08-05 12:14:17 -07001540
David Sodmanfa9b2af2017-12-24 13:28:59 -08001541 for (const auto& [token, display] : mDisplays) {
David Sodman10a41ff2018-08-05 12:14:17 -07001542 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001543 beginFrame(display);
David Sodman10a41ff2018-08-05 12:14:17 -07001544 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
1545 setUpHWComposer(compositionInfo);
1546 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001547 prepareFrame(display);
1548 doDebugFlashRegions(display, repaintEverything);
1549 doComposition(display, repaintEverything);
1550 }
1551
Adrian Roos1e1a1282017-11-01 19:05:31 +01001552 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001553 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001554
1555 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001556 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001557
Dan Stozabfbffeb2016-07-21 14:49:33 -07001558 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001559 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001560 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001561 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001562 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001563
Jorim Jaggi90535212018-05-23 23:44:06 +02001564 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001565
David Sodman7e4ae112018-02-09 15:02:28 -08001566 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001567 for (const auto& [token, display] : mDisplays) {
1568 const auto displayId = display->getId();
David Sodman7e4ae112018-02-09 15:02:28 -08001569 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[displayId]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001570 compositionInfo.hwc.hwcLayer = nullptr;
1571 }
David Sodmanba340492018-08-05 21:51:33 -07001572 }
David Sodman7e4ae112018-02-09 15:02:28 -08001573
1574 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001575}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001576
David Sodmanfa9b2af2017-12-24 13:28:59 -08001577
1578bool SurfaceFlinger::handleMessageInvalidate() {
1579 ATRACE_CALL();
1580 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001581}
1582
David Sodman79bba0e2018-08-05 18:07:49 -07001583void SurfaceFlinger::calculateWorkingSet() {
1584 ATRACE_CALL();
1585 ALOGV(__FUNCTION__);
1586
David Sodman79bba0e2018-08-05 18:07:49 -07001587 // build the h/w work list
1588 if (CC_UNLIKELY(mGeometryInvalid)) {
1589 mGeometryInvalid = false;
1590 for (const auto& [token, display] : mDisplays) {
1591 const auto displayId = display->getId();
1592 if (displayId >= 0) {
1593 const Vector<sp<Layer>>& currentLayers(
1594 display->getVisibleLayersSortedByZ());
1595 for (size_t i = 0; i < currentLayers.size(); i++) {
1596 const auto& layer = currentLayers[i];
1597
1598 if (!layer->hasHwcLayer(displayId)) {
1599 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1600 layer->forceClientComposition(displayId);
1601 continue;
1602 }
1603 }
1604
1605 layer->setGeometry(display, i);
1606 if (mDebugDisableHWC || mDebugRegion) {
1607 layer->forceClientComposition(displayId);
1608 }
1609 }
1610 }
1611 }
1612 }
1613
1614 // Set the per-frame data
1615 for (const auto& [token, display] : mDisplays) {
1616 const auto displayId = display->getId();
1617 if (displayId < 0) {
1618 continue;
1619 }
1620
1621 if (mDrawingState.colorMatrixChanged) {
1622 display->setColorTransform(mDrawingState.colorMatrix);
1623 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1624 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1625 "display %d: %d", displayId, result);
1626 }
1627 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1628 if (layer->isHdrY410()) {
1629 layer->forceClientComposition(displayId);
1630 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1631 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1632 !display->hasHDR10Support()) {
1633 layer->forceClientComposition(displayId);
1634 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1635 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1636 !display->hasHLGSupport()) {
1637 layer->forceClientComposition(displayId);
1638 }
1639
1640 if (layer->getForceClientComposition(displayId)) {
1641 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1642 layer->setCompositionType(displayId, HWC2::Composition::Client);
1643 continue;
1644 }
1645
1646 layer->setPerFrameData(display);
1647 }
1648
Peiyong Lin13effd12018-07-24 17:01:47 -07001649 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001650 ColorMode colorMode;
1651 Dataspace dataSpace;
1652 RenderIntent renderIntent;
1653 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1654 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1655 }
1656 }
1657
1658 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001659
1660 for (const auto& [token, display] : mDisplays) {
David Sodman15fb96e2018-01-07 10:23:24 -08001661 const auto displayId = display->getId();
1662 getBE().mCompositionInfo[displayId].clear();
David Sodmanba340492018-08-05 21:51:33 -07001663 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1664 auto displayId = display->getId();
1665 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1666 if (!layer->setHwcLayer(displayId)) {
1667 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1668 }
David Sodman15fb96e2018-01-07 10:23:24 -08001669 layer->getBE().compositionInfo.hwc.displayId = displayId;
1670 getBE().mCompositionInfo[displayId].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001671 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1672 }
1673 }
David Sodman79bba0e2018-08-05 18:07:49 -07001674}
1675
David Sodmanfa9b2af2017-12-24 13:28:59 -08001676void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001677{
David Sodmanfb95bcc2017-12-22 15:45:30 -08001678 const auto displayId = display->getId();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001679 // is debugging enabled
1680 if (CC_LIKELY(!mDebugRegion))
1681 return;
1682
David Sodmanfa9b2af2017-12-24 13:28:59 -08001683 if (display->isPoweredOn()) {
1684 // transform the dirty region into this screen's coordinate space
1685 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1686 if (!dirtyRegion.isEmpty()) {
1687 // redraw the whole screen
1688 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001689
David Sodmanfa9b2af2017-12-24 13:28:59 -08001690 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001691 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001692 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001693
David Sodmanfa9b2af2017-12-24 13:28:59 -08001694 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001695 }
1696 }
1697
David Sodmanfa9b2af2017-12-24 13:28:59 -08001698 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001699
1700 if (mDebugRegion > 1) {
1701 usleep(mDebugRegion * 1000);
1702 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001703
David Sodmanfa9b2af2017-12-24 13:28:59 -08001704 if (display->isPoweredOn()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08001705 status_t result = display->prepareFrame(
1706 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001707 ALOGE_IF(result != NO_ERROR,
1708 "prepareFrame for display %d failed:"
1709 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001710 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001711 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001712}
1713
Adrian Roos1e1a1282017-11-01 19:05:31 +01001714void SurfaceFlinger::doTracing(const char* where) {
1715 ATRACE_CALL();
1716 ATRACE_NAME(where);
1717 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001718 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001719 }
1720}
1721
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001722void SurfaceFlinger::logLayerStats() {
1723 ATRACE_CALL();
1724 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001725 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001726 if (display->isPrimary()) {
1727 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001728 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001729 }
1730 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001731
1732 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001733 }
1734}
1735
David Sodman2b406362017-12-15 13:33:47 -08001736void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001737{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001738 ATRACE_CALL();
1739 ALOGV("preComposition");
1740
David Sodman2b406362017-12-15 13:33:47 -08001741 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1742
Mathias Agopiancd60f992012-08-16 16:28:27 -07001743 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001744 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001745 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001746 needExtraInvalidate = true;
1747 }
Robert Carr2047fae2016-11-28 14:09:09 -08001748 });
1749
Mathias Agopiancd60f992012-08-16 16:28:27 -07001750 if (needExtraInvalidate) {
1751 signalLayerUpdate();
1752 }
1753}
1754
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001755void SurfaceFlinger::updateCompositorTiming(
1756 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1757 std::shared_ptr<FenceTime>& presentFenceTime) {
1758 // Update queue of past composite+present times and determine the
1759 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001760 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001761 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001762 while (!getBE().mCompositePresentTimes.empty()) {
1763 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001764 // Cached values should have been updated before calling this method,
1765 // which helps avoid duplicate syscalls.
1766 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1767 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1768 break;
1769 }
1770 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001771 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001772 }
1773
1774 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001775 while (getBE().mCompositePresentTimes.size() > 16) {
1776 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001777 }
1778
Brian Andersond0010582017-03-07 13:20:31 -08001779 setCompositorTimingSnapped(
1780 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1781}
1782
1783void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1784 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001785 // Integer division and modulo round toward 0 not -inf, so we need to
1786 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001787 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001788 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1789 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1790
Brian Andersond0010582017-03-07 13:20:31 -08001791 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1792 if (idealLatency <= 0) {
1793 idealLatency = vsyncInterval;
1794 }
1795
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001796 // Snap the latency to a value that removes scheduling jitter from the
1797 // composition and present times, which often have >1ms of jitter.
1798 // Reducing jitter is important if an app attempts to extrapolate
1799 // something (such as user input) to an accurate diasplay time.
1800 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1801 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001802 nsecs_t bias = vsyncInterval / 2;
1803 int64_t extraVsyncs =
1804 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1805 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1806 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001807
David Sodman99974d22017-11-28 12:04:33 -08001808 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1809 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1810 getBE().mCompositorTiming.interval = vsyncInterval;
1811 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001812}
1813
David Sodman2b406362017-12-15 13:33:47 -08001814void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001815{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001816 ATRACE_CALL();
1817 ALOGV("postComposition");
1818
Brian Anderson3546a3f2016-07-14 11:51:14 -07001819 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001820 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001821 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001822 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001823 }
1824
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001825 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001826 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001827
David Sodman73beded2017-11-15 11:56:06 -08001828 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001829 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001830 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001831 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001832 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001833 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001834 } else {
1835 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1836 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001837
David Sodman73beded2017-11-15 11:56:06 -08001838 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001839 mPreviousPresentFence =
1840 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1841 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001842 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001843
Lloyd Pique41be5d22018-06-21 13:11:48 -07001844 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1845 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001846
David Sodman2b406362017-12-15 13:33:47 -08001847 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001848 // when we started doing work for this frame, but that should be okay
1849 // since updateCompositorTiming has snapping logic.
1850 updateCompositorTiming(
David Sodman2b406362017-12-15 13:33:47 -08001851 vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001852 CompositorTiming compositorTiming;
1853 {
David Sodman99974d22017-11-28 12:04:33 -08001854 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1855 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001856 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001857
Robert Carr2047fae2016-11-28 14:09:09 -08001858 mDrawingState.traverseInZOrder([&](Layer* layer) {
1859 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001860 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001861 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001862 recordBufferingStats(layer->getName().string(),
1863 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001864 }
Robert Carr2047fae2016-11-28 14:09:09 -08001865 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001866
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001867 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001868 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001869 enableHardwareVsync();
1870 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001871 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001872 }
1873 }
1874
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001875 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001876 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001877 enableHardwareVsync();
1878 }
1879 }
1880
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001881 if (mAnimCompositionPending) {
1882 mAnimCompositionPending = false;
1883
Brian Anderson4e606e32017-03-16 15:34:57 -07001884 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001885 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001886 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001887 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001888 // The HWC doesn't support present fences, so use the refresh
1889 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001890 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001891 mAnimFrameTracker.setActualPresentTime(presentTime);
1892 }
1893 mAnimFrameTracker.advanceFrame();
1894 }
Dan Stozab90cf072015-03-05 11:05:59 -08001895
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001896 mTimeStats.incrementTotalFrames();
1897 if (mHadClientComposition) {
1898 mTimeStats.incrementClientCompositionFrames();
1899 }
1900
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001901 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001902 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001903 return;
1904 }
1905
1906 nsecs_t currentTime = systemTime();
1907 if (mHasPoweredOff) {
1908 mHasPoweredOff = false;
1909 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001910 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001911 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001912 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1913 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001914 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001915 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001916 }
David Sodman4a36e932017-11-07 14:29:47 -08001917 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001918 }
David Sodman4a36e932017-11-07 14:29:47 -08001919 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001920
1921 {
1922 std::lock_guard lock(mTexturePoolMutex);
1923 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1924 if (refillCount > 0) {
1925 const size_t offset = mTexturePool.size();
1926 mTexturePool.resize(mTexturePoolSize);
1927 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1928 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1929 }
1930 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001931}
1932
1933void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001934 ATRACE_CALL();
1935 ALOGV("rebuildLayerStacks");
1936
Mathias Agopiancd60f992012-08-16 16:28:27 -07001937 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001938 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001939 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001940 mVisibleRegionsDirty = false;
1941 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001942
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001943 for (const auto& pair : mDisplays) {
1944 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001945 Region opaqueRegion;
1946 Region dirtyRegion;
1947 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001948 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001949 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001950 const Rect bounds = display->getBounds();
1951 if (display->isPoweredOn()) {
1952 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001953
Jeff Sharkey76488112017-02-27 14:15:18 -07001954 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001955 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001956 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001957 Region drawRegion(tr.transform(
1958 layer->visibleNonTransparentRegion));
1959 drawRegion.andSelf(bounds);
1960 if (!drawRegion.isEmpty()) {
1961 layersSortedByZ.add(layer);
1962 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001963 // Clear out the HWC layer if this layer was
1964 // previously visible, but no longer is
1965 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001966 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001967 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001968 // WM changes display->layerStack upon sleep/awake.
1969 // Here we make sure we delete the HWC layers even if
1970 // WM changed their layer stack.
1971 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001972 }
1973
1974 // If a layer is not going to get a release fence because
1975 // it is invisible, but it is also going to release its
1976 // old buffer, add it to the list of layers needing
1977 // fences.
1978 if (hwcLayerDestroyed) {
1979 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1980 mLayersWithQueuedFrames.cend(), layer);
1981 if (found != mLayersWithQueuedFrames.cend()) {
1982 layersNeedingFences.add(layer);
1983 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001984 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001985 });
1986 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001987 display->setVisibleLayersSortedByZ(layersSortedByZ);
1988 display->setLayersNeedingFences(layersNeedingFences);
1989 display->undefinedRegion.set(bounds);
1990 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1991 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001992 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001993 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001994}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001995
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001996// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001997// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001998// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001999// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002000// The returned HDR data space is one of
2001// - Dataspace::UNKNOWN
2002// - Dataspace::BT2020_HLG
2003// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002004Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2005 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07002006 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002007 *outHdrDataSpace = Dataspace::UNKNOWN;
2008
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002009 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002010 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002011 case Dataspace::V0_SCRGB:
2012 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002013 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002014 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002015 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002016 case Dataspace::BT2020_PQ:
2017 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002018 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002019 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002020 case Dataspace::BT2020_HLG:
2021 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002022 // When there's mixed PQ content and HLG content, we set the HDR
2023 // data space to be BT2020_PQ and convert HLG to PQ.
2024 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2025 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002026 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002027 break;
2028 default:
2029 break;
2030 }
Romain Guy54f154a2017-10-24 21:40:32 +01002031 }
2032
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002033 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002034}
2035
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002036// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002037void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2038 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002039 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2040 *outMode = ColorMode::NATIVE;
2041 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002042 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002043 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002044 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002045
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002046 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002047 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002048
Peiyong Lindfde5112018-06-05 10:58:41 -07002049 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002050 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002051 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002052 if (isHdr) {
2053 bestDataSpace = hdrDataSpace;
2054 }
2055
Chia-I Wu0d711262018-05-21 15:19:35 -07002056 RenderIntent intent;
2057 switch (mDisplayColorSetting) {
2058 case DisplayColorSetting::MANAGED:
2059 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002060 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002061 break;
2062 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002063 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002064 break;
2065 default: // vendor display color setting
2066 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2067 break;
2068 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002069
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002070 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002071}
2072
David Sodman10a41ff2018-08-05 12:14:17 -07002073void SurfaceFlinger::configureSidebandComposition(const CompositionInfo& compositionInfo) const
2074{
2075 HWC2::Error error;
2076 LOG_ALWAYS_FATAL_IF(compositionInfo.hwc.sidebandStream == nullptr,
2077 "CompositionType is sideband, but sideband stream is nullptr");
2078 error = (compositionInfo.hwc.hwcLayer)
2079 ->setSidebandStream(compositionInfo.hwc.sidebandStream->handle());
2080 if (error != HWC2::Error::None) {
2081 ALOGE("[SF] Failed to set sideband stream %p: %s (%d)",
2082 compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
2083 static_cast<int32_t>(error));
2084 }
2085}
2086
2087void SurfaceFlinger::configureHwcCommonData(const CompositionInfo& compositionInfo) const
2088{
2089 HWC2::Error error;
2090
2091 if (!compositionInfo.hwc.skipGeometry) {
2092 error = (compositionInfo.hwc.hwcLayer)->setBlendMode(compositionInfo.hwc.blendMode);
2093 ALOGE_IF(error != HWC2::Error::None,
2094 "[SF] Failed to set blend mode %s:"
2095 " %s (%d)",
2096 to_string(compositionInfo.hwc.blendMode).c_str(), to_string(error).c_str(),
2097 static_cast<int32_t>(error));
2098
2099 error = (compositionInfo.hwc.hwcLayer)->setDisplayFrame(compositionInfo.hwc.displayFrame);
2100 ALOGE_IF(error != HWC2::Error::None,
2101 "[SF] Failed to set the display frame [%d, %d, %d, %d] %s (%d)",
2102 compositionInfo.hwc.displayFrame.left,
2103 compositionInfo.hwc.displayFrame.right,
2104 compositionInfo.hwc.displayFrame.top,
2105 compositionInfo.hwc.displayFrame.bottom,
2106 to_string(error).c_str(), static_cast<int32_t>(error));
2107
2108 error = (compositionInfo.hwc.hwcLayer)->setSourceCrop(compositionInfo.hwc.sourceCrop);
2109 ALOGE_IF(error != HWC2::Error::None,
2110 "[SF] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: %s (%d)",
2111 compositionInfo.hwc.sourceCrop.left,
2112 compositionInfo.hwc.sourceCrop.right,
2113 compositionInfo.hwc.sourceCrop.top,
2114 compositionInfo.hwc.sourceCrop.bottom,
2115 to_string(error).c_str(), static_cast<int32_t>(error));
2116
2117 error = (compositionInfo.hwc.hwcLayer)->setPlaneAlpha(compositionInfo.hwc.alpha);
2118 ALOGE_IF(error != HWC2::Error::None,
2119 "[SF] Failed to set plane alpha %.3f: "
2120 "%s (%d)",
2121 compositionInfo.hwc.alpha,
2122 to_string(error).c_str(), static_cast<int32_t>(error));
2123
2124
2125 error = (compositionInfo.hwc.hwcLayer)->setZOrder(compositionInfo.hwc.z);
2126 ALOGE_IF(error != HWC2::Error::None,
2127 "[SF] Failed to set Z %u: %s (%d)",
2128 compositionInfo.hwc.z,
2129 to_string(error).c_str(), static_cast<int32_t>(error));
2130
2131 error = (compositionInfo.hwc.hwcLayer)
2132 ->setInfo(compositionInfo.hwc.type, compositionInfo.hwc.appId);
2133 ALOGE_IF(error != HWC2::Error::None,
2134 "[SF] Failed to set info (%d)",
2135 static_cast<int32_t>(error));
2136
2137 error = (compositionInfo.hwc.hwcLayer)->setTransform(compositionInfo.hwc.transform);
2138 ALOGE_IF(error != HWC2::Error::None,
2139 "[SF] Failed to set transform %s: "
2140 "%s (%d)",
2141 to_string(compositionInfo.hwc.transform).c_str(), to_string(error).c_str(),
2142 static_cast<int32_t>(error));
2143 }
2144
2145 error = (compositionInfo.hwc.hwcLayer)->setCompositionType(compositionInfo.compositionType);
2146 ALOGE_IF(error != HWC2::Error::None,
2147 "[SF] Failed to set composition type: %s (%d)",
2148 to_string(error).c_str(), static_cast<int32_t>(error));
2149
2150 error = (compositionInfo.hwc.hwcLayer)->setDataspace(compositionInfo.hwc.dataspace);
2151 ALOGE_IF(error != HWC2::Error::None,
2152 "[SF] Failed to set dataspace: %s (%d)",
2153 to_string(error).c_str(), static_cast<int32_t>(error));
2154
2155 error = (compositionInfo.hwc.hwcLayer)->setPerFrameMetadata(
2156 compositionInfo.hwc.supportedPerFrameMetadata, compositionInfo.hwc.hdrMetadata);
2157 ALOGE_IF(error != HWC2::Error::None && error != HWC2::Error::Unsupported,
2158 "[SF] Failed to set hdrMetadata: %s (%d)",
2159 to_string(error).c_str(), static_cast<int32_t>(error));
2160
2161 if (compositionInfo.compositionType == HWC2::Composition::SolidColor) {
2162 error = (compositionInfo.hwc.hwcLayer)->setColor(compositionInfo.hwc.color);
2163 ALOGE_IF(error != HWC2::Error::None,
2164 "[SF] Failed to set color: %s (%d)",
2165 to_string(error).c_str(), static_cast<int32_t>(error));
2166 }
2167
2168 error = (compositionInfo.hwc.hwcLayer)->setVisibleRegion(compositionInfo.hwc.visibleRegion);
2169 ALOGE_IF(error != HWC2::Error::None,
2170 "[SF] Failed to set visible region: %s (%d)",
2171 to_string(error).c_str(), static_cast<int32_t>(error));
2172
2173 error = (compositionInfo.hwc.hwcLayer)->setSurfaceDamage(compositionInfo.hwc.surfaceDamage);
2174 ALOGE_IF(error != HWC2::Error::None,
2175 "[SF] Failed to set surface damage: %s (%d)",
2176 to_string(error).c_str(), static_cast<int32_t>(error));
2177}
2178
2179void SurfaceFlinger::configureDeviceComposition(const CompositionInfo& compositionInfo) const
2180{
2181 HWC2::Error error;
2182
2183 if (compositionInfo.hwc.fence) {
2184 error = (compositionInfo.hwc.hwcLayer)->setBuffer(compositionInfo.mBufferSlot,
2185 compositionInfo.mBuffer, compositionInfo.hwc.fence);
2186 ALOGE_IF(error != HWC2::Error::None,
2187 "[SF] Failed to set buffer: %s (%d)",
2188 to_string(error).c_str(), static_cast<int32_t>(error));
2189 }
2190}
2191
David Sodmanfa9b2af2017-12-24 13:28:59 -08002192void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002193{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002194 bool dirty = !display->getDirtyRegion(false).isEmpty();
2195 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2196 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002197
David Sodmanfa9b2af2017-12-24 13:28:59 -08002198 // If nothing has changed (!dirty), don't recompose.
2199 // If something changed, but we don't currently have any visible layers,
2200 // and didn't when we last did a composition, then skip it this time.
2201 // The second rule does two things:
2202 // - When all layers are removed from a display, we'll emit one black
2203 // frame, then nothing more until we get new layers.
2204 // - When a display is created with a private layer stack, we won't
2205 // emit any black frames until a layer is added to the layer stack.
2206 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002207
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002208 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2209 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002210 mustRecompose ? "doing" : "skipping",
2211 dirty ? "+" : "-",
2212 empty ? "+" : "-",
2213 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002214
David Sodmanfa9b2af2017-12-24 13:28:59 -08002215 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002216
David Sodmanfa9b2af2017-12-24 13:28:59 -08002217 if (mustRecompose) {
2218 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002219 }
2220}
2221
David Sodmanfa9b2af2017-12-24 13:28:59 -08002222void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002223{
David Sodmanfb95bcc2017-12-22 15:45:30 -08002224 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002225 if (!display->isPoweredOn()) {
2226 return;
David Sodman2b406362017-12-15 13:33:47 -08002227 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002228
David Sodmanfb95bcc2017-12-22 15:45:30 -08002229 status_t result = display->prepareFrame(
2230 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08002231 ALOGE_IF(result != NO_ERROR,
2232 "prepareFrame for display %d failed:"
2233 " %d (%s)",
2234 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002235}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002236
David Sodman10a41ff2018-08-05 12:14:17 -07002237void SurfaceFlinger::setUpHWComposer(const CompositionInfo& compositionInfo) {
2238 ATRACE_CALL();
2239 ALOGV("setUpHWComposer");
2240
2241 switch (compositionInfo.compositionType)
2242 {
2243 case HWC2::Composition::Invalid:
David Sodmana6d42332018-08-29 14:07:04 -07002244 break;
2245
David Sodman10a41ff2018-08-05 12:14:17 -07002246 case HWC2::Composition::Client:
David Sodmana6d42332018-08-29 14:07:04 -07002247 if (compositionInfo.hwc.hwcLayer) {
2248 auto error = (compositionInfo.hwc.hwcLayer)->
2249 setCompositionType(compositionInfo.compositionType);
2250 ALOGE_IF(error != HWC2::Error::None,
2251 "[SF] Failed to set composition type: %s (%d)",
2252 to_string(error).c_str(), static_cast<int32_t>(error));
2253 }
David Sodman10a41ff2018-08-05 12:14:17 -07002254 break;
2255
2256 case HWC2::Composition::Sideband:
2257 configureHwcCommonData(compositionInfo);
2258 configureSidebandComposition(compositionInfo);
2259 break;
2260
2261 case HWC2::Composition::SolidColor:
2262 configureHwcCommonData(compositionInfo);
2263 break;
2264
2265 case HWC2::Composition::Device:
2266 case HWC2::Composition::Cursor:
2267 configureHwcCommonData(compositionInfo);
2268 configureDeviceComposition(compositionInfo);
2269 break;
2270 }
2271}
2272
David Sodmanfa9b2af2017-12-24 13:28:59 -08002273void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002274 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002275 ALOGV("doComposition");
2276
David Sodmanfa9b2af2017-12-24 13:28:59 -08002277 if (display->isPoweredOn()) {
2278 // transform the dirty region into this screen's coordinate space
2279 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002280
David Sodmanfa9b2af2017-12-24 13:28:59 -08002281 // repaint the framebuffer (if needed)
2282 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002283
David Sodmanfa9b2af2017-12-24 13:28:59 -08002284 display->dirtyRegion.clear();
2285 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002286 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002287 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002288}
2289
David Sodmanfa9b2af2017-12-24 13:28:59 -08002290void SurfaceFlinger::postFrame()
2291{
2292 // |mStateLock| not needed as we are on the main thread
2293 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2294 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2295 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2296 logFrameStats();
2297 }
2298 }
2299}
2300
2301void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002302{
Mathias Agopian841cde52012-03-01 15:44:37 -08002303 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002304 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002305
David Sodmanfa9b2af2017-12-24 13:28:59 -08002306 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002307
David Sodmanfa9b2af2017-12-24 13:28:59 -08002308 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002309 const auto displayId = display->getId();
2310 if (displayId >= 0) {
2311 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002312 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002313 display->onSwapBuffersCompleted();
2314 display->makeCurrent();
David Sodman10a41ff2018-08-05 12:14:17 -07002315 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002316 sp<Fence> releaseFence = Fence::NO_FENCE;
Chia-I Wu7b549592017-11-15 09:14:57 -08002317 // The layer buffer from the previous frame (if any) is released
2318 // by HWC only when the release fence from this frame (if any) is
2319 // signaled. Always get the release fence from HWC first.
David Sodman10a41ff2018-08-05 12:14:17 -07002320 auto hwcLayer = compositionInfo.hwc.hwcLayer;
2321 if ((displayId >= 0) && hwcLayer) {
2322 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer.get());
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002323 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002324
2325 // If the layer was client composited in the previous frame, we
2326 // need to merge with the previous client target acquire fence.
2327 // Since we do not track that, always merge with the current
2328 // client target acquire fence when it is available, even though
2329 // this is suboptimal.
David Sodman10a41ff2018-08-05 12:14:17 -07002330 if (compositionInfo.compositionType == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002331 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002332 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002333 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002334
David Sodman10a41ff2018-08-05 12:14:17 -07002335 if (compositionInfo.layer) {
2336 compositionInfo.layer->onLayerDisplayed(releaseFence);
2337 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002338 }
Chia-I Wu83806892017-11-16 10:50:20 -08002339
2340 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002341 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002342 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002343 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002344 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002345 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002346 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002347 }
2348 }
2349
Dominik Laskowski7e045462018-05-30 13:02:02 -07002350 if (displayId >= 0) {
2351 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002352 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002353 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002354}
2355
Mathias Agopian87baae12012-07-31 12:38:26 -07002356void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002357{
Mathias Agopian841cde52012-03-01 15:44:37 -08002358 ATRACE_CALL();
2359
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002360 // here we keep a copy of the drawing state (that is the state that's
2361 // going to be overwritten by handleTransactionLocked()) outside of
2362 // mStateLock so that the side-effects of the State assignment
2363 // don't happen with mStateLock held (which can cause deadlocks).
2364 State drawingState(mDrawingState);
2365
Mathias Agopianca4d3602011-05-19 15:38:14 -07002366 Mutex::Autolock _l(mStateLock);
2367 const nsecs_t now = systemTime();
2368 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002369
Mathias Agopianca4d3602011-05-19 15:38:14 -07002370 // Here we're guaranteed that some transaction flags are set
2371 // so we can call handleTransactionLocked() unconditionally.
2372 // We call getTransactionFlags(), which will also clear the flags,
2373 // with mStateLock held to guarantee that mCurrentState won't change
2374 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002375
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002376 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002377 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002378 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002379
Mathias Agopianca4d3602011-05-19 15:38:14 -07002380 mLastTransactionTime = systemTime() - now;
2381 mDebugInTransaction = 0;
2382 invalidateHwcGeometry();
2383 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002384}
2385
Dominik Laskowski7e045462018-05-30 13:02:02 -07002386DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002387 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002388 // Figure out whether the event is for the primary display or an
2389 // external display by matching the Hwc display id against one for a
2390 // connected display. If we did not find a match, we then check what
2391 // displays are not already connected to determine the type. If we don't
2392 // have a connected primary display, we assume the new display is meant to
2393 // be the primary display, and then if we don't have an external display,
2394 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002395 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2396 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002397 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002398 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002399 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002400 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002401 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002402 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002403 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002404 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002405 return DisplayDevice::DISPLAY_EXTERNAL;
2406 }
2407
2408 return DisplayDevice::DISPLAY_ID_INVALID;
2409}
2410
Lloyd Piqueba04e622017-12-14 17:11:26 -08002411void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2412 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002413 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002414 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002415 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002416 continue;
2417 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002418
2419 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2420 ALOGE("External displays are not supported by the vr hardware composer.");
2421 continue;
2422 }
2423
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002424 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002425 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002426 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002427 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002428 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002429
2430 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002431 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002432 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002433 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002434 DisplayDeviceState info;
2435 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002436 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2437 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002438 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002439 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002440 mInterceptor->saveDisplayCreation(info);
2441 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002442 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002443 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002444
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002445 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002446 if (idx >= 0) {
2447 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002448 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002449 mCurrentState.displays.removeItemsAt(idx);
2450 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002451 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002452 }
2453
2454 processDisplayChangesLocked();
2455 }
2456
2457 mPendingHotplugEvents.clear();
2458}
2459
Lloyd Pique99d3da52018-01-22 17:48:03 -08002460sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002461 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002462 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002463 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002464 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002465 HdrCapabilities hdrCapabilities;
2466 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002467
Peiyong Lin13effd12018-07-24 17:01:47 -07002468 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002469 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002470 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002471 if (isWideColorMode(colorMode)) {
2472 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002473 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002474
Dominik Laskowski7e045462018-05-30 13:02:02 -07002475 std::vector<RenderIntent> renderIntents =
2476 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002477 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002478 }
tangrobin6753a022018-08-10 10:58:54 +08002479 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002480
tangrobin6753a022018-08-10 10:58:54 +08002481 if (displayId >= 0) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002482 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2483 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2484 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002485
2486 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2487 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2488
2489 /*
2490 * Create our display's surface
2491 */
Peiyong Lin833074a2018-08-28 11:53:54 -07002492 std::unique_ptr<renderengine::Surface> renderSurface = getRenderEngine().createSurface();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002493 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002494 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002495 renderSurface->setNativeWindow(nativeWindow.get());
2496 const int displayWidth = renderSurface->queryWidth();
2497 const int displayHeight = renderSurface->queryHeight();
2498
2499 // Make sure that composition can never be stalled by a virtual display
2500 // consumer that isn't processing buffers fast enough. We have to do this
2501 // in two places:
2502 // * Here, in case the display is composed entirely by HWC.
2503 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2504 // window's swap interval in eglMakeCurrent, so they'll override the
2505 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002506 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002507 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2508 }
2509
Chia-I Wua02871c2018-08-27 14:38:23 -07002510 const int displayInstallOrientation = state.type == DisplayDevice::DISPLAY_PRIMARY ?
2511 primaryDisplayOrientation : DisplayState::eOrientationDefault;
2512
Lloyd Pique99d3da52018-01-22 17:48:03 -08002513 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002514 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002515
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002516 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002517 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2518 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
Chia-I Wua02871c2018-08-27 14:38:23 -07002519 displayHeight, displayInstallOrientation, hasWideColorGamut,
2520 hdrCapabilities, supportedPerFrameMetadata, hwcColorModes,
2521 initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002522
2523 if (maxFrameBufferAcquiredBuffers >= 3) {
2524 nativeWindowSurface->preallocateBuffers();
2525 }
2526
2527 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002528 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2529 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002530 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002531 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002532 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002533 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002534 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002535 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002536 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002537 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002538 display->setLayerStack(state.layerStack);
2539 display->setProjection(state.orientation, state.viewport, state.frame);
2540 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002541
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002542 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002543}
2544
Lloyd Pique347200f2017-12-14 17:00:15 -08002545void SurfaceFlinger::processDisplayChangesLocked() {
2546 // here we take advantage of Vector's copy-on-write semantics to
2547 // improve performance by skipping the transaction entirely when
2548 // know that the lists are identical
2549 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2550 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2551 if (!curr.isIdenticalTo(draw)) {
2552 mVisibleRegionsDirty = true;
2553 const size_t cc = curr.size();
2554 size_t dc = draw.size();
2555
2556 // find the displays that were removed
2557 // (ie: in drawing state but not in current state)
2558 // also handle displays that changed
2559 // (ie: displays that are in both lists)
2560 for (size_t i = 0; i < dc;) {
2561 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2562 if (j < 0) {
2563 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002564 // Call makeCurrent() on the primary display so we can
2565 // be sure that nothing associated with this display
2566 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002567 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2568 defaultDisplay->makeCurrent();
2569 }
2570 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2571 display->disconnect(getHwComposer());
2572 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002573 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002574 if (mUseScheduler) {
2575 mScheduler->hotplugReceived(mAppConnectionHandle,
2576 EventThread::DisplayType::Primary, false);
2577 } else {
2578 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2579 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002580 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002581 if (mUseScheduler) {
2582 mScheduler->hotplugReceived(mAppConnectionHandle,
2583 EventThread::DisplayType::External, false);
2584 } else {
2585 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2586 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002587 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002588 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002589 } else {
2590 // this display is in both lists. see if something changed.
2591 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002592 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002593 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2594 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2595 if (state_binder != draw_binder) {
2596 // changing the surface is like destroying and
2597 // recreating the DisplayDevice, so we just remove it
2598 // from the drawing state, so that it get re-added
2599 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002600 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2601 display->disconnect(getHwComposer());
2602 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002603 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002604 mDrawingState.displays.removeItemsAt(i);
2605 dc--;
2606 // at this point we must loop to the next item
2607 continue;
2608 }
2609
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002610 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002611 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002612 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002613 }
2614 if ((state.orientation != draw[i].orientation) ||
2615 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002616 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002617 }
2618 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002619 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002620 }
2621 }
2622 }
2623 ++i;
2624 }
2625
2626 // find displays that were added
2627 // (ie: in current state but not in drawing state)
2628 for (size_t i = 0; i < cc; i++) {
2629 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2630 const DisplayDeviceState& state(curr[i]);
2631
2632 sp<DisplaySurface> dispSurface;
2633 sp<IGraphicBufferProducer> producer;
2634 sp<IGraphicBufferProducer> bqProducer;
2635 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002636 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002637
Dominik Laskowski7e045462018-05-30 13:02:02 -07002638 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002639 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002640 // Virtual displays without a surface are dormant:
2641 // they have external state (layer stack, projection,
2642 // etc.) but no internal state (i.e. a DisplayDevice).
2643 if (state.surface != nullptr) {
2644 // Allow VR composer to use virtual displays.
2645 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2646 int width = 0;
2647 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2648 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2649 int height = 0;
2650 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2651 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2652 int intFormat = 0;
2653 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2654 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002655 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002656
Dominik Laskowski7e045462018-05-30 13:02:02 -07002657 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2658 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002659 }
2660
2661 // TODO: Plumb requested format back up to consumer
2662
2663 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002664 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002665 bqProducer, bqConsumer,
2666 state.displayName);
2667
2668 dispSurface = vds;
2669 producer = vds;
2670 }
2671 } else {
2672 ALOGE_IF(state.surface != nullptr,
2673 "adding a supported display, but rendering "
2674 "surface is provided (%p), ignoring it",
2675 state.surface.get());
2676
Dominik Laskowski7e045462018-05-30 13:02:02 -07002677 displayId = state.type;
2678 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002679 producer = bqProducer;
2680 }
2681
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002682 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002683 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002684 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002685 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002686 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002687 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002688 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002689 if (mUseScheduler) {
2690 mScheduler->hotplugReceived(mAppConnectionHandle,
2691 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002692 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002693 } else {
2694 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2695 true);
2696 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002697 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002698 if (mUseScheduler) {
2699 mScheduler->hotplugReceived(mAppConnectionHandle,
2700 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002701 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002702 } else {
2703 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2704 true);
2705 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002706 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002707 }
2708 }
2709 }
2710 }
2711 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002712
2713 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002714}
2715
Mathias Agopian87baae12012-07-31 12:38:26 -07002716void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002717{
Dan Stoza7dde5992015-05-22 09:51:44 -07002718 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002719 mCurrentState.traverseInZOrder([](Layer* layer) {
2720 layer->notifyAvailableFrames();
2721 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002722
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002723 /*
2724 * Traversal of the children
2725 * (perform the transaction for each of them if needed)
2726 */
2727
Mathias Agopian3559b072012-08-15 13:46:03 -07002728 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002729 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002730 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002731 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002732
2733 const uint32_t flags = layer->doTransaction(0);
2734 if (flags & Layer::eVisibleRegion)
2735 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002736 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002737 }
2738
2739 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002740 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002741 */
2742
Mathias Agopiane57f2922012-08-09 16:29:12 -07002743 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002744 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002745 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002746 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002747
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002748 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002749 // The transform hint might have changed for some layers
2750 // (either because a display has changed, or because a layer
2751 // as changed).
2752 //
2753 // Walk through all the layers in currentLayers,
2754 // and update their transform hint.
2755 //
2756 // If a layer is visible only on a single display, then that
2757 // display is used to calculate the hint, otherwise we use the
2758 // default display.
2759 //
2760 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2761 // the hint is set before we acquire a buffer from the surface texture.
2762 //
2763 // NOTE: layer transactions have taken place already, so we use their
2764 // drawing state. However, SurfaceFlinger's own transaction has not
2765 // happened yet, so we must use the current state layer list
2766 // (soon to become the drawing state list).
2767 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002768 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002769 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002770 bool first = true;
2771 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002772 // NOTE: we rely on the fact that layers are sorted by
2773 // layerStack first (so we don't have to traverse the list
2774 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002775 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002776 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002777 currentlayerStack = layerStack;
2778 // figure out if this layerstack is mirrored
2779 // (more than one display) if so, pick the default display,
2780 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002781 hintDisplay = nullptr;
2782 for (const auto& [token, display] : mDisplays) {
2783 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2784 if (hintDisplay) {
2785 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002786 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002787 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002788 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002789 }
2790 }
2791 }
2792 }
Chet Haase91d25932013-04-11 15:24:55 -07002793
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002794 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002795 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2796 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002797
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002798 // could be null when this layer is using a layerStack
2799 // that is not visible on any display. Also can occur at
2800 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002801 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002802 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002803
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002804 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002805 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002806 if (hintDisplay) {
2807 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002808 }
Robert Carr2047fae2016-11-28 14:09:09 -08002809
2810 first = false;
2811 });
Mathias Agopian84300952012-11-21 16:02:13 -08002812 }
2813
2814
Mathias Agopian3559b072012-08-15 13:46:03 -07002815 /*
2816 * Perform our own transaction if needed
2817 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002818
2819 if (mLayersAdded) {
2820 mLayersAdded = false;
2821 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002822 mVisibleRegionsDirty = true;
2823 }
2824
2825 // some layers might have been removed, so
2826 // we need to update the regions they're exposing.
2827 if (mLayersRemoved) {
2828 mLayersRemoved = false;
2829 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002830 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002831 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002832 // this layer is not visible anymore
2833 // TODO: we could traverse the tree from front to back and
2834 // compute the actual visible region
2835 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002836 Region visibleReg;
2837 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002838 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002839 }
Robert Carr2047fae2016-11-28 14:09:09 -08002840 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002841 }
2842
2843 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002844
2845 updateCursorAsync();
2846}
2847
2848void SurfaceFlinger::updateCursorAsync()
2849{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002850 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002851 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002852 continue;
2853 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002854
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002855 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2856 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002857 }
2858 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002859}
2860
2861void SurfaceFlinger::commitTransaction()
2862{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002863 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002864 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002865 for (const auto& l : mLayersPendingRemoval) {
2866 recordBufferingStats(l->getName().string(),
2867 l->getOccupancyHistory(true));
2868 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002869 }
2870 mLayersPendingRemoval.clear();
2871 }
2872
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002873 // If this transaction is part of a window animation then the next frame
2874 // we composite should be considered an animation as well.
2875 mAnimCompositionPending = mAnimTransactionPending;
2876
Mathias Agopian4fec8732012-06-29 14:12:52 -07002877 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002878 // clear the "changed" flags in current state
2879 mCurrentState.colorMatrixChanged = false;
2880
Robert Carr1f0a16a2016-10-24 16:27:39 -07002881 mDrawingState.traverseInZOrder([](Layer* layer) {
2882 layer->commitChildList();
2883 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002884 mTransactionPending = false;
2885 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002886 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002887}
2888
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002889void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2890 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002891 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002892 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002893
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002894 Region aboveOpaqueLayers;
2895 Region aboveCoveredLayers;
2896 Region dirty;
2897
Mathias Agopian87baae12012-07-31 12:38:26 -07002898 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002899
Robert Carr2047fae2016-11-28 14:09:09 -08002900 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002901 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002902 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002903
Jesse Hall01e29052013-02-19 16:13:35 -08002904 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002905 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002906 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002907 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002908
Mathias Agopianab028732010-03-16 16:41:46 -07002909 /*
2910 * opaqueRegion: area of a surface that is fully opaque.
2911 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002912 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002913
2914 /*
2915 * visibleRegion: area of a surface that is visible on screen
2916 * and not fully transparent. This is essentially the layer's
2917 * footprint minus the opaque regions above it.
2918 * Areas covered by a translucent surface are considered visible.
2919 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002920 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002921
2922 /*
2923 * coveredRegion: area of a surface that is covered by all
2924 * visible regions above it (which includes the translucent areas).
2925 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002926 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002927
Jesse Halla8026d22012-09-25 13:25:04 -07002928 /*
2929 * transparentRegion: area of a surface that is hinted to be completely
2930 * transparent. This is only used to tell when the layer has no visible
2931 * non-transparent regions and can be removed from the layer list. It
2932 * does not affect the visibleRegion of this layer or any layers
2933 * beneath it. The hint may not be correct if apps don't respect the
2934 * SurfaceView restrictions (which, sadly, some don't).
2935 */
2936 Region transparentRegion;
2937
Mathias Agopianab028732010-03-16 16:41:46 -07002938
2939 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002940 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002941 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002942 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002943 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002944 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002945 if (!visibleRegion.isEmpty()) {
2946 // Remove the transparent area from the visible region
2947 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002948 if (tr.preserveRects()) {
2949 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002950 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002951 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002952 // transformation too complex, can't do the
2953 // transparent region optimization.
2954 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002955 }
Mathias Agopianab028732010-03-16 16:41:46 -07002956 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002957
Mathias Agopianab028732010-03-16 16:41:46 -07002958 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002959 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002960 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002961 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002962 // the opaque region is the layer's footprint
2963 opaqueRegion = visibleRegion;
2964 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002965 }
2966 }
2967
Robert Carre5f4f692018-01-12 13:12:28 -08002968 if (visibleRegion.isEmpty()) {
2969 layer->clearVisibilityRegions();
2970 return;
2971 }
2972
Mathias Agopianab028732010-03-16 16:41:46 -07002973 // Clip the covered region to the visible region
2974 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2975
2976 // Update aboveCoveredLayers for next (lower) layer
2977 aboveCoveredLayers.orSelf(visibleRegion);
2978
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002979 // subtract the opaque region covered by the layers above us
2980 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002981
2982 // compute this layer's dirty region
2983 if (layer->contentDirty) {
2984 // we need to invalidate the whole region
2985 dirty = visibleRegion;
2986 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002987 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002988 layer->contentDirty = false;
2989 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002990 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002991 * the exposed region consists of two components:
2992 * 1) what's VISIBLE now and was COVERED before
2993 * 2) what's EXPOSED now less what was EXPOSED before
2994 *
2995 * note that (1) is conservative, we start with the whole
2996 * visible region but only keep what used to be covered by
2997 * something -- which mean it may have been exposed.
2998 *
2999 * (2) handles areas that were not covered by anything but got
3000 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003001 */
Mathias Agopianab028732010-03-16 16:41:46 -07003002 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003003 const Region oldVisibleRegion = layer->visibleRegion;
3004 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003005 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3006 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003007 }
3008 dirty.subtractSelf(aboveOpaqueLayers);
3009
3010 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003011 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003012
Mathias Agopianab028732010-03-16 16:41:46 -07003013 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003014 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003015
Jesse Halla8026d22012-09-25 13:25:04 -07003016 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003017 layer->setVisibleRegion(visibleRegion);
3018 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003019 layer->setVisibleNonTransparentRegion(
3020 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003021 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003022
Mathias Agopian87baae12012-07-31 12:38:26 -07003023 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003024}
3025
Chia-I Wuab0c3192017-08-01 11:29:00 -07003026void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003027 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003028 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
3029 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003030 }
3031 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003032}
3033
Dan Stoza6b9454d2014-11-07 16:00:59 -08003034bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003035{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003036 ALOGV("handlePageFlip");
3037
Brian Andersond6927fb2016-07-23 23:37:30 -07003038 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003039
Mathias Agopian4fec8732012-06-29 14:12:52 -07003040 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003041 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003042 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003043
3044 // Store the set of layers that need updates. This set must not change as
3045 // buffers are being latched, as this could result in a deadlock.
3046 // Example: Two producers share the same command stream and:
3047 // 1.) Layer 0 is latched
3048 // 2.) Layer 0 gets a new frame
3049 // 2.) Layer 1 gets a new frame
3050 // 3.) Layer 1 is latched.
3051 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3052 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003053 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003054 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003055 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07003056 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003057 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003058 } else {
3059 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003060 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003061 } else {
3062 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003063 }
Robert Carr2047fae2016-11-28 14:09:09 -08003064 });
3065
Dan Stoza9e56aa02015-11-02 13:00:03 -08003066 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07003067 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07003068 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003069 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07003070 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06003071 newDataLatched = true;
3072 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003073 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003074
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003075 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003076
3077 // If we will need to wake up at some time in the future to deal with a
3078 // queued frame that shouldn't be displayed during this vsync period, wake
3079 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003080 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003081 signalLayerUpdate();
3082 }
3083
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003084 // enter boot animation on first buffer latch
3085 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3086 ALOGI("Enter boot animation");
3087 mBootStage = BootStage::BOOTANIMATION;
3088 }
3089
Dan Stoza6b9454d2014-11-07 16:00:59 -08003090 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003091 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003092}
3093
Mathias Agopianad456f92011-01-13 17:53:01 -08003094void SurfaceFlinger::invalidateHwcGeometry()
3095{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003096 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003097}
3098
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003099void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
3100 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003101 // We only need to actually compose the display if:
3102 // 1) It is being handled by hardware composer, which may need this to
3103 // keep its virtual display state machine in sync, or
3104 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07003105 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08003106 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003107 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003108 return;
3109 }
3110
Dan Stoza9e56aa02015-11-02 13:00:03 -08003111 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003112 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003113
3114 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003115 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003116}
3117
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003118bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003119 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003120
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003121 const Region bounds(display->bounds());
3122 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003123 const auto displayId = display->getId();
3124 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003125 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003126
Chia-I Wu8e50e692018-05-04 10:12:37 -07003127 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003128 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003129
Dan Stoza9e56aa02015-11-02 13:00:03 -08003130 if (hasClientComposition) {
3131 ALOGV("hasClientComposition");
3132
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003133 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003134 if (display->hasWideColorGamut()) {
3135 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003136 }
3137 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003138 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003139 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003140
Dominik Laskowski7e045462018-05-30 13:02:02 -07003141 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003142 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3143 HWC2::Capability::SkipClientColorTransform);
3144
Chia-I Wud49d6692018-06-27 07:17:41 +08003145 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003146 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3147 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003148 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003149 }
3150
Chia-I Wud49d6692018-06-27 07:17:41 +08003151 // The current enhanced saturation matrix is designed to enhance Display P3,
3152 // thus we only apply this matrix when the render intent is not colorimetric
3153 // and the output color space is Display P3.
3154 needsEnhancedColorMatrix =
3155 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3156 outputDataspace == Dataspace::DISPLAY_P3);
3157 if (needsEnhancedColorMatrix) {
3158 colorMatrix *= mEnhancedSaturationMatrix;
3159 }
3160
3161 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003162
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003163 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003164 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003165 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003166 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003167
3168 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003169 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3170 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3171 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003172 }
3173 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003174 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003175
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003176 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003177 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003178 // when using overlays, we assume a fully transparent framebuffer
3179 // NOTE: we could reduce how much we need to clear, for instance
3180 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003181 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003182 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003183 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003184 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003185 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003186 // we're left with the letterbox region
3187 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003188 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003189
3190 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003191 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003192
Mathias Agopianb9494d52012-04-18 02:28:45 -07003193 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003194 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003195 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003196 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003197 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003198 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003199
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003200 const Rect& bounds = display->getBounds();
3201 const Rect& scissor = display->getScissor();
3202 if (scissor != bounds) {
3203 // scissor doesn't match the screen's dimensions, so we
3204 // need to clear everything outside of it and enable
3205 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003206
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003207 // enable scissor for this frame
3208 const uint32_t height = display->getHeight();
3209 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
3210 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003211 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003212 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003213
Mathias Agopian85d751c2012-08-29 16:59:24 -07003214 /*
3215 * and then, render the layers targeted at the framebuffer
3216 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003217
Dan Stoza9e56aa02015-11-02 13:00:03 -08003218 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003219 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003220 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003221 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003222 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003223 displayTransform.transform(layer->visibleRegion)));
3224 ALOGV("Layer: %s", layer->getName().string());
3225 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003226 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003227 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003228 case HWC2::Composition::Cursor:
3229 case HWC2::Composition::Device:
3230 case HWC2::Composition::Sideband:
3231 case HWC2::Composition::SolidColor: {
David Sodmanc1498e62018-09-12 14:36:26 -07003232 const Layer::State& state(layer->getDrawingState());
3233 if (layer->getClearClientTarget(displayId) && !firstLayer &&
3234 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3235 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003236 // never clear the very first layer since we're
3237 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003238 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003239 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003240 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003241 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003242 case HWC2::Composition::Client: {
David Sodmanc1498e62018-09-12 14:36:26 -07003243 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003244 break;
3245 }
3246 default:
3247 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003248 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003249 } else {
3250 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003251 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003252 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003253 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003254
Chia-I Wud49d6692018-06-27 07:17:41 +08003255 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003256 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003257 }
3258
Mathias Agopianf45c5102012-10-24 16:29:17 -07003259 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003260 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003261 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003262}
3263
Chia-I Wu28e3a252018-09-07 12:05:02 -07003264void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003265 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003266 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003267}
3268
Dan Stoza7d89d062015-04-30 13:29:25 -07003269status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003270 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003271 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003272 const sp<Layer>& lbc,
3273 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003274{
Dan Stoza7d89d062015-04-30 13:29:25 -07003275 // add this layer to the current state list
3276 {
3277 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003278 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003279 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3280 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003281 return NO_MEMORY;
3282 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003283 if (parent == nullptr) {
3284 mCurrentState.layersSortedByZ.add(lbc);
3285 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003286 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003287 ALOGE("addClientLayer called with a removed parent");
3288 return NAME_NOT_FOUND;
3289 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003290 parent->addChild(lbc);
3291 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003292
Yiwei Zhang243b3782018-05-15 17:40:04 -07003293 if (gbc != nullptr) {
3294 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3295 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3296 mMaxGraphicBufferProducerListSize,
3297 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3298 mGraphicBufferProducerList.size(),
3299 mMaxGraphicBufferProducerListSize, mNumLayers);
3300 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003301 mLayersAdded = true;
3302 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003303 }
3304
Mathias Agopian96f08192010-06-02 23:28:45 -07003305 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003306 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003307
Dan Stoza7d89d062015-04-30 13:29:25 -07003308 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003309}
3310
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003311status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003312 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003313 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3314}
Robert Carr7f9b8992017-03-10 11:08:39 -08003315
chaviwca27f252018-02-06 16:46:39 -08003316status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3317 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003318 if (layer->isPendingRemoval()) {
3319 return NO_ERROR;
3320 }
3321
Robert Carr1f0a16a2016-10-24 16:27:39 -07003322 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003323 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003324 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003325 if (topLevelOnly) {
3326 return NO_ERROR;
3327 }
3328
Chia-I Wu98f1c102017-05-30 14:54:08 -07003329 sp<Layer> ancestor = p;
3330 while (ancestor->getParent() != nullptr) {
3331 ancestor = ancestor->getParent();
3332 }
3333 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3334 ALOGE("removeLayer called with a layer whose parent has been removed");
3335 return NAME_NOT_FOUND;
3336 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003337
3338 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003339 } else {
3340 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003341 }
3342
Robert Carr136e2f62017-02-08 17:54:29 -08003343 // As a matter of normal operation, the LayerCleaner will produce a second
3344 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3345 // so we will succeed in promoting it, but it's already been removed
3346 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3347 // otherwise something has gone wrong and we are leaking the layer.
3348 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003349 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3350 layer->getName().string(),
3351 (p != nullptr) ? p->getName().string() : "no-parent");
3352 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003353 } else if (index < 0) {
3354 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003355 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003356
Chia-I Wuc6657022017-08-15 11:18:17 -07003357 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003358 mLayersPendingRemoval.add(layer);
3359 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003360 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003361 setTransactionFlags(eTransactionNeeded);
3362 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003363}
3364
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003365uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003366 return android_atomic_release_load(&mTransactionFlags);
3367}
3368
Mathias Agopian3f844832013-08-07 21:24:32 -07003369uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003370 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3371}
3372
Mathias Agopian3f844832013-08-07 21:24:32 -07003373uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003374 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3375}
3376
3377uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3378 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003379 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003380 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003381 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003382 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003383 }
3384 return old;
3385}
3386
chaviwca27f252018-02-06 16:46:39 -08003387bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3388 for (const ComposerState& state : states) {
3389 // Here we need to check that the interface we're given is indeed
3390 // one of our own. A malicious client could give us a nullptr
3391 // IInterface, or one of its own or even one of our own but a
3392 // different type. All these situations would cause us to crash.
3393 if (state.client == nullptr) {
3394 return true;
3395 }
3396
3397 sp<IBinder> binder = IInterface::asBinder(state.client);
3398 if (binder == nullptr) {
3399 return true;
3400 }
3401
3402 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3403 return true;
3404 }
3405 }
3406 return false;
3407}
3408
Mathias Agopian8b33f032012-07-24 20:43:54 -07003409void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003410 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003411 const Vector<DisplayState>& displays,
3412 uint32_t flags)
3413{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003414 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003415 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003416 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003417
chaviwca27f252018-02-06 16:46:39 -08003418 if (containsAnyInvalidClientState(states)) {
3419 return;
3420 }
3421
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003422 if (flags & eAnimation) {
3423 // For window updates that are part of an animation we must wait for
3424 // previous animation "frames" to be handled.
3425 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003426 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003427 if (CC_UNLIKELY(err != NO_ERROR)) {
3428 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003429 // caller after a few seconds.
3430 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3431 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003432 mAnimTransactionPending = false;
3433 break;
3434 }
3435 }
3436 }
3437
chaviwca27f252018-02-06 16:46:39 -08003438 for (const DisplayState& display : displays) {
3439 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003440 }
3441
chaviwca27f252018-02-06 16:46:39 -08003442 for (const ComposerState& state : states) {
3443 transactionFlags |= setClientStateLocked(state);
3444 }
3445
3446 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3447 // as destroyed should only occur after setting all other states. This is to allow for a
3448 // child re-parent to happen before marking its original parent as destroyed (which would
3449 // then mark the child as destroyed).
3450 for (const ComposerState& state : states) {
3451 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003452 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003453
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003454 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3455 // anyway. This can be used as a flush mechanism for previous async transactions.
3456 // Empty animation transaction can be used to simulate back-pressure, so also force a
3457 // transaction for empty animation transactions.
3458 if (transactionFlags == 0 &&
3459 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003460 transactionFlags = eTransactionNeeded;
3461 }
3462
Mathias Agopian386aa982011-11-07 21:58:03 -08003463 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003464 if (mInterceptor->isEnabled()) {
3465 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003466 }
Irvel468051e2016-06-13 16:44:44 -07003467
Mathias Agopian386aa982011-11-07 21:58:03 -08003468 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003469 const auto start = (flags & eEarlyWakeup)
3470 ? VSyncModulator::TransactionStart::EARLY
3471 : VSyncModulator::TransactionStart::NORMAL;
3472 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003473
3474 // if this is a synchronous transaction, wait for it to take effect
3475 // before returning.
3476 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003477 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003478 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003479 if (flags & eAnimation) {
3480 mAnimTransactionPending = true;
3481 }
3482 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003483 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3484 if (CC_UNLIKELY(err != NO_ERROR)) {
3485 // just in case something goes wrong in SF, return to the
3486 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003487 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3488 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003489 break;
3490 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003491 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003492 }
3493}
3494
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003495uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3496 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3497 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003498
Mathias Agopiane57f2922012-08-09 16:29:12 -07003499 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003500 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3501
3502 const uint32_t what = s.what;
3503 if (what & DisplayState::eSurfaceChanged) {
3504 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3505 state.surface = s.surface;
3506 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003507 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003508 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003509 if (what & DisplayState::eLayerStackChanged) {
3510 if (state.layerStack != s.layerStack) {
3511 state.layerStack = s.layerStack;
3512 flags |= eDisplayTransactionNeeded;
3513 }
3514 }
3515 if (what & DisplayState::eDisplayProjectionChanged) {
3516 if (state.orientation != s.orientation) {
3517 state.orientation = s.orientation;
3518 flags |= eDisplayTransactionNeeded;
3519 }
3520 if (state.frame != s.frame) {
3521 state.frame = s.frame;
3522 flags |= eDisplayTransactionNeeded;
3523 }
3524 if (state.viewport != s.viewport) {
3525 state.viewport = s.viewport;
3526 flags |= eDisplayTransactionNeeded;
3527 }
3528 }
3529 if (what & DisplayState::eDisplaySizeChanged) {
3530 if (state.width != s.width) {
3531 state.width = s.width;
3532 flags |= eDisplayTransactionNeeded;
3533 }
3534 if (state.height != s.height) {
3535 state.height = s.height;
3536 flags |= eDisplayTransactionNeeded;
3537 }
3538 }
3539
Mathias Agopiane57f2922012-08-09 16:29:12 -07003540 return flags;
3541}
3542
Robert Carrd4ae7f32018-06-07 16:10:57 -07003543bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3544 IPCThreadState* ipc = IPCThreadState::self();
3545 const int pid = ipc->getCallingPid();
3546 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003547 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003548 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003549 return false;
3550 }
3551 return true;
3552}
3553
chaviwca27f252018-02-06 16:46:39 -08003554uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3555 const layer_state_t& s = composerState.state;
3556 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3557
Mathias Agopian13127d82013-03-05 17:47:11 -08003558 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003559 if (layer == nullptr) {
3560 return 0;
3561 }
3562
3563 if (layer->isPendingRemoval()) {
3564 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3565 return 0;
3566 }
3567
3568 uint32_t flags = 0;
3569
3570 const uint32_t what = s.what;
3571 bool geometryAppliesWithResize =
3572 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003573
3574 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3575 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003576 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003577 layer->pushPendingState();
3578 }
3579
chaviw8b3871a2017-11-01 17:41:01 -07003580 if (what & layer_state_t::ePositionChanged) {
3581 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3582 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003583 }
chaviw8b3871a2017-11-01 17:41:01 -07003584 }
3585 if (what & layer_state_t::eLayerChanged) {
3586 // NOTE: index needs to be calculated before we update the state
3587 const auto& p = layer->getParent();
3588 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003589 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003590 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003591 mCurrentState.layersSortedByZ.removeAt(idx);
3592 mCurrentState.layersSortedByZ.add(layer);
3593 // we need traversal (state changed)
3594 // AND transaction (list changed)
3595 flags |= eTransactionNeeded|eTraversalNeeded;
3596 }
chaviw8b3871a2017-11-01 17:41:01 -07003597 } else {
3598 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003599 flags |= eTransactionNeeded|eTraversalNeeded;
3600 }
3601 }
chaviw8b3871a2017-11-01 17:41:01 -07003602 }
3603 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003604 // NOTE: index needs to be calculated before we update the state
3605 const auto& p = layer->getParent();
3606 if (p == nullptr) {
3607 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3608 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3609 mCurrentState.layersSortedByZ.removeAt(idx);
3610 mCurrentState.layersSortedByZ.add(layer);
3611 // we need traversal (state changed)
3612 // AND transaction (list changed)
3613 flags |= eTransactionNeeded|eTraversalNeeded;
3614 }
3615 } else {
3616 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3617 flags |= eTransactionNeeded|eTraversalNeeded;
3618 }
chaviw8b3871a2017-11-01 17:41:01 -07003619 }
3620 }
3621 if (what & layer_state_t::eSizeChanged) {
3622 if (layer->setSize(s.w, s.h)) {
3623 flags |= eTraversalNeeded;
3624 }
3625 }
3626 if (what & layer_state_t::eAlphaChanged) {
3627 if (layer->setAlpha(s.alpha))
3628 flags |= eTraversalNeeded;
3629 }
3630 if (what & layer_state_t::eColorChanged) {
3631 if (layer->setColor(s.color))
3632 flags |= eTraversalNeeded;
3633 }
3634 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003635 // TODO: b/109894387
3636 //
3637 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3638 // rotation. To see the problem observe that if we have a square parent, and a child
3639 // of the same size, then we rotate the child 45 degrees around it's center, the child
3640 // must now be cropped to a non rectangular 8 sided region.
3641 //
3642 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3643 // private API, and the WindowManager only uses rotation in one case, which is on a top
3644 // level layer in which cropping is not an issue.
3645 //
3646 // However given that abuse of rotation matrices could lead to surfaces extending outside
3647 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3648 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3649 // transformations.
3650 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003651 flags |= eTraversalNeeded;
3652 }
3653 if (what & layer_state_t::eTransparentRegionChanged) {
3654 if (layer->setTransparentRegionHint(s.transparentRegion))
3655 flags |= eTraversalNeeded;
3656 }
3657 if (what & layer_state_t::eFlagsChanged) {
3658 if (layer->setFlags(s.flags, s.mask))
3659 flags |= eTraversalNeeded;
3660 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003661 if (what & layer_state_t::eCropChanged_legacy) {
3662 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003663 flags |= eTraversalNeeded;
3664 }
chaviw8b3871a2017-11-01 17:41:01 -07003665 if (what & layer_state_t::eLayerStackChanged) {
3666 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3667 // We only allow setting layer stacks for top level layers,
3668 // everything else inherits layer stack from its parent.
3669 if (layer->hasParent()) {
3670 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3671 layer->getName().string());
3672 } else if (idx < 0) {
3673 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3674 "that also does not appear in the top level layer list. Something"
3675 " has gone wrong.", layer->getName().string());
3676 } else if (layer->setLayerStack(s.layerStack)) {
3677 mCurrentState.layersSortedByZ.removeAt(idx);
3678 mCurrentState.layersSortedByZ.add(layer);
3679 // we need traversal (state changed)
3680 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003681 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003682 }
3683 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003684 if (what & layer_state_t::eDeferTransaction_legacy) {
3685 if (s.barrierHandle_legacy != nullptr) {
3686 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3687 } else if (s.barrierGbp_legacy != nullptr) {
3688 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003689 if (authenticateSurfaceTextureLocked(gbp)) {
3690 const auto& otherLayer =
3691 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003692 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003693 } else {
3694 ALOGE("Attempt to defer transaction to to an"
3695 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003696 }
3697 }
chaviw8b3871a2017-11-01 17:41:01 -07003698 // We don't trigger a traversal here because if no other state is
3699 // changed, we don't want this to cause any more work
3700 }
3701 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003702 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003703 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003704 if (!hadParent) {
3705 mCurrentState.layersSortedByZ.remove(layer);
3706 }
chaviw8b3871a2017-11-01 17:41:01 -07003707 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003708 }
chaviw8b3871a2017-11-01 17:41:01 -07003709 }
3710 if (what & layer_state_t::eReparentChildren) {
3711 if (layer->reparentChildren(s.reparentHandle)) {
3712 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003713 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003714 }
chaviw8b3871a2017-11-01 17:41:01 -07003715 if (what & layer_state_t::eDetachChildren) {
3716 layer->detachChildren();
3717 }
3718 if (what & layer_state_t::eOverrideScalingModeChanged) {
3719 layer->setOverrideScalingMode(s.overrideScalingMode);
3720 // We don't trigger a traversal here because if no other state is
3721 // changed, we don't want this to cause any more work
3722 }
Marissa Wall61c58622018-07-18 10:12:20 -07003723 if (what & layer_state_t::eTransformChanged) {
3724 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3725 }
3726 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3727 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3728 flags |= eTraversalNeeded;
3729 }
3730 if (what & layer_state_t::eCropChanged) {
3731 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3732 }
3733 if (what & layer_state_t::eBufferChanged) {
3734 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3735 }
3736 if (what & layer_state_t::eAcquireFenceChanged) {
3737 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3738 }
3739 if (what & layer_state_t::eDataspaceChanged) {
3740 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3741 }
3742 if (what & layer_state_t::eHdrMetadataChanged) {
3743 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3744 }
3745 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3746 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3747 }
3748 if (what & layer_state_t::eApiChanged) {
3749 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3750 }
3751 if (what & layer_state_t::eSidebandStreamChanged) {
3752 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3753 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003754 return flags;
3755}
3756
chaviwca27f252018-02-06 16:46:39 -08003757void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3758 const layer_state_t& state = composerState.state;
3759 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3760
3761 sp<Layer> layer(client->getLayerUser(state.surface));
3762 if (layer == nullptr) {
3763 return;
3764 }
3765
3766 if (layer->isPendingRemoval()) {
3767 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3768 return;
3769 }
3770
3771 if (state.what & layer_state_t::eDestroySurface) {
3772 removeLayerLocked(mStateLock, layer);
3773 }
3774}
3775
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003776status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003777 const String8& name,
3778 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003779 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003780 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003781 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003782{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003783 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003784 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003785 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003786 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003787 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003788
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003789 status_t result = NO_ERROR;
3790
3791 sp<Layer> layer;
3792
Cody Northropbc755282017-03-31 12:00:08 -06003793 String8 uniqueName = getUniqueLayerName(name);
3794
Mathias Agopian3165cc22012-08-08 19:42:09 -07003795 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003796 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003797 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3798 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003799
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003800 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003801 case ISurfaceComposerClient::eFXSurfaceBufferState:
3802 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3803 break;
chaviw13fdc492017-06-27 12:40:18 -07003804 case ISurfaceComposerClient::eFXSurfaceColor:
3805 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003806 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003807 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003808 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003809 case ISurfaceComposerClient::eFXSurfaceContainer:
3810 result = createContainerLayer(client,
3811 uniqueName, w, h, flags,
3812 handle, &layer);
3813 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003814 default:
3815 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003816 break;
3817 }
3818
Dan Stoza7d89d062015-04-30 13:29:25 -07003819 if (result != NO_ERROR) {
3820 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003821 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003822
Chia-I Wuab0c3192017-08-01 11:29:00 -07003823 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3824 // TODO b/64227542
3825 if (windowType == 441731) {
3826 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3827 layer->setPrimaryDisplayOnly();
3828 }
3829
Albert Chaulk479c60c2017-01-27 14:21:34 -05003830 layer->setInfo(windowType, ownerUid);
3831
Robert Carr1f0a16a2016-10-24 16:27:39 -07003832 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003833 if (result != NO_ERROR) {
3834 return result;
3835 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003836 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003837
3838 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003839 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003840}
3841
Cody Northropbc755282017-03-31 12:00:08 -06003842String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3843{
3844 bool matchFound = true;
3845 uint32_t dupeCounter = 0;
3846
3847 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3848 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3849
Dan Stoza436ccf32018-06-21 12:10:12 -07003850 // Grab the state lock since we're accessing mCurrentState
3851 Mutex::Autolock lock(mStateLock);
3852
Cody Northropbc755282017-03-31 12:00:08 -06003853 // Loop over layers until we're sure there is no matching name
3854 while (matchFound) {
3855 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003856 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003857 if (layer->getName() == uniqueName) {
3858 matchFound = true;
3859 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3860 }
3861 });
3862 }
3863
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003864 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3865 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003866
3867 return uniqueName;
3868}
3869
Marissa Wallfd668622018-05-10 10:21:13 -07003870status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3871 uint32_t w, uint32_t h, uint32_t flags,
3872 PixelFormat& format, sp<IBinder>* handle,
3873 sp<IGraphicBufferProducer>* gbp,
3874 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003875 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003876 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003877 case PIXEL_FORMAT_TRANSPARENT:
3878 case PIXEL_FORMAT_TRANSLUCENT:
3879 format = PIXEL_FORMAT_RGBA_8888;
3880 break;
3881 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003882 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003883 break;
3884 }
3885
Marissa Wallfd668622018-05-10 10:21:13 -07003886 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3887 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003888 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003889 *handle = layer->getHandle();
3890 *gbp = layer->getProducer();
3891 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003892 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003893
Marissa Wallfd668622018-05-10 10:21:13 -07003894 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003895 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003896}
3897
Marissa Wall61c58622018-07-18 10:12:20 -07003898status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3899 uint32_t w, uint32_t h, uint32_t flags,
3900 sp<IBinder>* handle, sp<Layer>* outLayer) {
3901 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3902 *handle = layer->getHandle();
3903 *outLayer = layer;
3904
3905 return NO_ERROR;
3906}
3907
chaviw13fdc492017-06-27 12:40:18 -07003908status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003909 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003910 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003911{
chaviw13fdc492017-06-27 12:40:18 -07003912 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003913 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003914 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003915}
3916
Robert Carr6b3f6c52018-08-13 13:05:17 -07003917status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3918 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3919 sp<IBinder>* handle, sp<Layer>* outLayer)
3920{
3921 *outLayer = new ContainerLayer(this, client, name, w, h, flags);
3922 *handle = (*outLayer)->getHandle();
3923 return NO_ERROR;
3924}
3925
3926
Mathias Agopianac9fa422013-02-11 16:40:36 -08003927status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003928{
Robert Carr9524cb32017-02-13 11:32:32 -08003929 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003930 status_t err = NO_ERROR;
3931 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003932 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003933 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003934 err = removeLayer(l);
3935 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3936 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003937 }
3938 return err;
3939}
3940
Mathias Agopian13127d82013-03-05 17:47:11 -08003941status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003942{
Mathias Agopian67106042013-03-14 19:18:13 -07003943 // called by ~LayerCleaner() when all references to the IBinder (handle)
3944 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003945 sp<Layer> l = layer.promote();
3946 if (l == nullptr) {
3947 // The layer has already been removed, carry on
3948 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003949 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003950 // If we have a parent, then we can continue to live as long as it does.
3951 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003952}
3953
Mathias Agopianb60314a2012-04-10 22:09:54 -07003954// ---------------------------------------------------------------------------
3955
Andy McFadden13a082e2012-08-24 10:16:42 -07003956void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003957 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3958 if (!displayToken) return;
3959
Jesse Hall01e29052013-02-19 16:13:35 -08003960 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003961 Vector<ComposerState> state;
3962 Vector<DisplayState> displays;
3963 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003964 d.what = DisplayState::eDisplayProjectionChanged |
3965 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003966 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003967 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003968 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003969 d.frame.makeInvalid();
3970 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003971 d.width = 0;
3972 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003973 displays.add(d);
3974 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003975
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003976 const auto display = getDisplayDevice(displayToken);
3977 if (!display) return;
3978
3979 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3980
3981 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003982 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003983 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003984
Brian Andersond0010582017-03-07 13:20:31 -08003985 // Use phase of 0 since phase is not known.
3986 // Use latency of 0, which will snap to the ideal latency.
3987 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003988}
3989
3990void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003991 // Async since we may be called from the main thread.
3992 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003993}
3994
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003995void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3996 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003997 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003998 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003999
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004000 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004001 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004002 return;
4003 }
4004
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004005 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004006 ALOGW("Trying to set power mode for virtual display");
4007 return;
4008 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004009
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004010 display->setPowerMode(mode);
4011
Lloyd Pique4dccc412018-01-22 17:21:36 -08004012 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07004013 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004014 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07004015 if (idx < 0) {
4016 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
4017 return;
4018 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07004019 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07004020 }
4021
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004022 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004023 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004024 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004025 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004026 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004027 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004028 if (mUseScheduler) {
4029 mScheduler->onScreenAcquired(mAppConnectionHandle);
4030 } else {
4031 mEventThread->onScreenAcquired();
4032 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07004033 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004034 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004035
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004036 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004037 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004038 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004039
4040 struct sched_param param = {0};
4041 param.sched_priority = 1;
4042 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4043 ALOGW("Couldn't set SCHED_FIFO on display on");
4044 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004045 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004046 // Turn off the display
4047 struct sched_param param = {0};
4048 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4049 ALOGW("Couldn't set SCHED_OTHER on display off");
4050 }
4051
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004052 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07004053 disableHardwareVsync(true); // also cancels any in-progress resync
4054
Mathias Agopiancde87a32012-09-13 14:09:01 -07004055 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004056 if (mUseScheduler) {
4057 mScheduler->onScreenReleased(mAppConnectionHandle);
4058 } else {
4059 mEventThread->onScreenReleased();
4060 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004061 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004062
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004063 getHwComposer().setPowerMode(type, mode);
4064 mVisibleRegionsDirty = true;
4065 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004066 } else if (mode == HWC_POWER_MODE_DOZE ||
4067 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004068 // Update display while dozing
4069 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004070 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004071 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004072 if (mUseScheduler) {
4073 mScheduler->onScreenAcquired(mAppConnectionHandle);
4074 } else {
4075 mEventThread->onScreenAcquired();
4076 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004077 resyncToHardwareVsync(true);
4078 }
4079 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4080 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004081 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004082 disableHardwareVsync(true); // also cancels any in-progress resync
4083 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004084 if (mUseScheduler) {
4085 mScheduler->onScreenReleased(mAppConnectionHandle);
4086 } else {
4087 mEventThread->onScreenReleased();
4088 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004089 }
4090 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004091 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004092 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004093 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004094 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004095
4096 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004097}
4098
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004099void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004100 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004101 const auto display = getDisplayDevice(displayToken);
4102 if (!display) {
4103 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4104 displayToken.get());
4105 } else if (display->isVirtual()) {
4106 ALOGW("Attempt to set power mode %d for virtual display", mode);
4107 } else {
4108 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004109 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004110 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004111}
4112
4113// ---------------------------------------------------------------------------
4114
Lloyd Pique755e3192018-01-31 16:46:15 -08004115status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4116 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004117 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004118
Mathias Agopianbd115332013-04-18 16:41:04 -07004119 IPCThreadState* ipc = IPCThreadState::self();
4120 const int pid = ipc->getCallingPid();
4121 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004122
Mathias Agopianbd115332013-04-18 16:41:04 -07004123 if ((uid != AID_SHELL) &&
4124 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004125 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07004126 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004127 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004128 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004129 // (this would indicate SF is stuck, but we want to be able to
4130 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004131 status_t err = mStateLock.timedLock(s2ns(1));
4132 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004133 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004134 result.appendFormat(
4135 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4136 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004137 }
4138
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004139 bool dumpAll = true;
4140 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004141 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004142
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004143 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004144 if ((index < numArgs) &&
4145 (args[index] == String16("--list"))) {
4146 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004147 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004148 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004149 }
4150
4151 if ((index < numArgs) &&
4152 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004153 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004154 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004155 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004156 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004157
4158 if ((index < numArgs) &&
4159 (args[index] == String16("--latency-clear"))) {
4160 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004161 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004162 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004163 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004164
4165 if ((index < numArgs) &&
4166 (args[index] == String16("--dispsync"))) {
4167 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004168 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004169 dumpAll = false;
4170 }
Dan Stozab90cf072015-03-05 11:05:59 -08004171
4172 if ((index < numArgs) &&
4173 (args[index] == String16("--static-screen"))) {
4174 index++;
4175 dumpStaticScreenStats(result);
4176 dumpAll = false;
4177 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004178
4179 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004180 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004181 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004182 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004183 dumpAll = false;
4184 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004185
4186 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4187 index++;
4188 dumpWideColorInfo(result);
4189 dumpAll = false;
4190 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004191
4192 if ((index < numArgs) &&
4193 (args[index] == String16("--enable-layer-stats"))) {
4194 index++;
4195 mLayerStats.enable();
4196 dumpAll = false;
4197 }
4198
4199 if ((index < numArgs) &&
4200 (args[index] == String16("--disable-layer-stats"))) {
4201 index++;
4202 mLayerStats.disable();
4203 dumpAll = false;
4204 }
4205
4206 if ((index < numArgs) &&
4207 (args[index] == String16("--clear-layer-stats"))) {
4208 index++;
4209 mLayerStats.clear();
4210 dumpAll = false;
4211 }
4212
4213 if ((index < numArgs) &&
4214 (args[index] == String16("--dump-layer-stats"))) {
4215 index++;
4216 mLayerStats.dump(result);
4217 dumpAll = false;
4218 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004219
4220 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004221 (args[index] == String16("--frame-composition"))) {
4222 index++;
4223 dumpFrameCompositionInfo(result);
4224 dumpAll = false;
4225 }
4226
4227 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004228 (args[index] == String16("--display-identification"))) {
4229 index++;
4230 dumpDisplayIdentificationData(result);
4231 dumpAll = false;
4232 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004233
4234 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4235 index++;
4236 mTimeStats.parseArgs(asProto, args, index, result);
4237 dumpAll = false;
4238 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004239 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004240
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004241 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004242 if (asProto) {
4243 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4244 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4245 } else {
4246 dumpAllLocked(args, index, result);
4247 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004248 }
4249
Mathias Agopian9795c422009-08-26 16:36:26 -07004250 if (locked) {
4251 mStateLock.unlock();
4252 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004253 }
4254 write(fd, result.string(), result.size());
4255 return NO_ERROR;
4256}
4257
Dan Stozac7014012014-02-14 15:03:43 -08004258void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4259 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004260{
Robert Carr2047fae2016-11-28 14:09:09 -08004261 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004262 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004263 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004264}
4265
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004266void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004267 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004268{
4269 String8 name;
4270 if (index < args.size()) {
4271 name = String8(args[index]);
4272 index++;
4273 }
4274
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004275 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4276 getHwComposer().isConnected(displayId)) {
4277 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4278 const nsecs_t period = activeConfig->getVsyncPeriod();
4279 result.appendFormat("%" PRId64 "\n", period);
4280 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004281
4282 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004283 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004284 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004285 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004286 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004287 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004288 }
Robert Carr2047fae2016-11-28 14:09:09 -08004289 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004290 }
4291}
4292
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004293void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004294 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004295{
4296 String8 name;
4297 if (index < args.size()) {
4298 name = String8(args[index]);
4299 index++;
4300 }
4301
Robert Carr2047fae2016-11-28 14:09:09 -08004302 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004303 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004304 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004305 }
Robert Carr2047fae2016-11-28 14:09:09 -08004306 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004307
Svetoslavd85084b2014-03-20 10:28:31 -07004308 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004309}
4310
Jamie Gennis6547ff42013-07-16 20:12:42 -07004311// This should only be called from the main thread. Otherwise it would need
4312// the lock and should use mCurrentState rather than mDrawingState.
4313void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004314 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004315 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004316 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004317
4318 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4319}
4320
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004321void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004322{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004323 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004324
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004325 if (isLayerTripleBufferingDisabled())
4326 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004327
4328 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004329 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004330 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004331 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004332 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4333 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004334 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004335}
4336
Dan Stozab90cf072015-03-05 11:05:59 -08004337void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4338{
4339 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004340 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4341 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004342 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004343 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004344 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4345 b + 1, bucketTimeSec, percent);
4346 }
David Sodman4a36e932017-11-07 14:29:47 -08004347 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004348 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004349 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004350 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004351 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004352}
4353
Dan Stozae77c7662016-05-13 11:37:28 -07004354void SurfaceFlinger::recordBufferingStats(const char* layerName,
4355 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004356 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4357 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004358 for (const auto& segment : history) {
4359 if (!segment.usedThirdBuffer) {
4360 stats.twoBufferTime += segment.totalTime;
4361 }
4362 if (segment.occupancyAverage < 1.0f) {
4363 stats.doubleBufferedTime += segment.totalTime;
4364 } else if (segment.occupancyAverage < 2.0f) {
4365 stats.tripleBufferedTime += segment.totalTime;
4366 }
4367 ++stats.numSegments;
4368 stats.totalTime += segment.totalTime;
4369 }
4370}
4371
Brian Andersond6927fb2016-07-23 23:37:30 -07004372void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4373 result.appendFormat("Layer frame timestamps:\n");
4374
4375 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4376 const size_t count = currentLayers.size();
4377 for (size_t i=0 ; i<count ; i++) {
4378 currentLayers[i]->dumpFrameEvents(result);
4379 }
4380}
4381
Dan Stozae77c7662016-05-13 11:37:28 -07004382void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4383 result.append("Buffering stats:\n");
4384 result.append(" [Layer name] <Active time> <Two buffer> "
4385 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004386 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004387 typedef std::tuple<std::string, float, float, float> BufferTuple;
4388 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004389 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004390 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004391 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004392 if (stats.numSegments == 0) {
4393 continue;
4394 }
4395 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4396 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4397 stats.totalTime;
4398 float doubleBufferRatio = static_cast<float>(
4399 stats.doubleBufferedTime) / stats.totalTime;
4400 float tripleBufferRatio = static_cast<float>(
4401 stats.tripleBufferedTime) / stats.totalTime;
4402 sorted.insert({activeTime, {name, twoBufferRatio,
4403 doubleBufferRatio, tripleBufferRatio}});
4404 }
4405 for (const auto& sortedPair : sorted) {
4406 float activeTime = sortedPair.first;
4407 const BufferTuple& values = sortedPair.second;
4408 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4409 std::get<0>(values).c_str(), activeTime,
4410 std::get<1>(values), std::get<2>(values),
4411 std::get<3>(values));
4412 }
4413 result.append("\n");
4414}
4415
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004416void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004417 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004418 const int32_t displayId = display->getId();
4419 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4420 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004421 continue;
4422 }
4423
Dominik Laskowski7e045462018-05-30 13:02:02 -07004424 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004425 uint8_t port;
4426 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004427 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004428 result.append("no identification data\n");
4429 continue;
4430 }
4431
4432 if (!isEdid(data)) {
4433 result.append("unknown identification data: ");
4434 for (uint8_t byte : data) {
4435 result.appendFormat("%x ", byte);
4436 }
4437 result.append("\n");
4438 continue;
4439 }
4440
4441 const auto edid = parseEdid(data);
4442 if (!edid) {
4443 result.append("invalid EDID: ");
4444 for (uint8_t byte : data) {
4445 result.appendFormat("%x ", byte);
4446 }
4447 result.append("\n");
4448 continue;
4449 }
4450
4451 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4452 result.append(edid->displayName.data(), edid->displayName.length());
4453 result.append("\"\n");
4454 }
4455 result.append("\n");
4456}
4457
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004458void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004459 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4460 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004461 result.appendFormat("DisplayColorSetting: %s\n",
4462 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004463
4464 // TODO: print out if wide-color mode is active or not
4465
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004466 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004467 const int32_t displayId = display->getId();
4468 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004469 continue;
4470 }
4471
Dominik Laskowski7e045462018-05-30 13:02:02 -07004472 result.appendFormat("Display %d color modes:\n", displayId);
4473 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004474 for (auto&& mode : modes) {
4475 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4476 }
4477
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004478 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004479 result.appendFormat(" Current color mode: %s (%d)\n",
4480 decodeColorMode(currentMode).c_str(), currentMode);
4481 }
4482 result.append("\n");
4483}
4484
David Sodman7e4ae112018-02-09 15:02:28 -08004485void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4486 std::string stringResult;
4487
4488 for (const auto& [token, display] : mDisplays) {
4489 const auto displayId = display->getId();
4490 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
4491 continue;
4492 }
4493
4494 const auto& compositionInfoIt = getBE().mEndOfFrameCompositionInfo.find(displayId);
4495 if (compositionInfoIt == getBE().mEndOfFrameCompositionInfo.end()) {
4496 break;
4497 }
4498 const auto& compositionInfoList = compositionInfoIt->second;
4499 stringResult += base::StringPrintf("Display: %d\n", displayId);
4500 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4501 for (const auto& compositionInfo : compositionInfoList) {
4502 compositionInfo.dump(stringResult, nullptr);
4503 stringResult += base::StringPrintf("\n");
4504 }
4505 }
4506
4507 result.append(stringResult.c_str());
4508}
4509
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004510LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004511 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004512 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4513 const State& state = useDrawing ? mDrawingState : mCurrentState;
4514 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004515 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004516 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004517 });
4518
4519 return layersProto;
4520}
4521
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004522LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004523 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004524
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004525 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004526 resolution->set_w(display.getWidth());
4527 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004528
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004529 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4530 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4531 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004532
Dominik Laskowski7e045462018-05-30 13:02:02 -07004533 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004534 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004535 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004536 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004537 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004538 }
4539 });
4540
4541 return layersProto;
4542}
4543
Mathias Agopian74d211a2013-04-22 16:55:35 +02004544void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4545 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004546{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004547 bool colorize = false;
4548 if (index < args.size()
4549 && (args[index] == String16("--color"))) {
4550 colorize = true;
4551 index++;
4552 }
4553
4554 Colorizer colorizer(colorize);
4555
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004556 // figure out if we're stuck somewhere
4557 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004558 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004559 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4560
4561 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004562 * Dump library configuration.
4563 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004564
4565 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004566 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004567 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004568 appendSfConfigString(result);
4569 appendUiConfigString(result);
4570 appendGuiConfigString(result);
4571 result.append("\n");
4572
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004573 result.append("\nDisplay identification data:\n");
4574 dumpDisplayIdentificationData(result);
4575
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004576 result.append("\nWide-Color information:\n");
4577 dumpWideColorInfo(result);
4578
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004579 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004580 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004581 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004582 result.append(SyncFeatures::getInstance().toString());
4583 result.append("\n");
4584
Andy McFadden41d67d72014-04-25 16:58:34 -07004585 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004586 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004587 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004588
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004589 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4590 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004591 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4592 getHwComposer().isConnected(displayId)) {
4593 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004594 result.appendFormat("Display %d: "
4595 "app phase %" PRId64 " ns, "
4596 "sf phase %" PRId64 " ns, "
4597 "early app phase %" PRId64 " ns, "
4598 "early sf phase %" PRId64 " ns, "
4599 "early app gl phase %" PRId64 " ns, "
4600 "early sf gl phase %" PRId64 " ns, "
4601 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4602 displayId,
4603 vsyncPhaseOffsetNs,
4604 sfVsyncPhaseOffsetNs,
4605 appEarlyOffset,
4606 sfEarlyOffset,
4607 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004608 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004609 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004610 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004611 result.append("\n");
4612
Dan Stozab90cf072015-03-05 11:05:59 -08004613 // Dump static screen stats
4614 result.append("\n");
4615 dumpStaticScreenStats(result);
4616 result.append("\n");
4617
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004618 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4619
Dan Stozae77c7662016-05-13 11:37:28 -07004620 dumpBufferingStats(result);
4621
Andy McFadden4803b742012-09-24 19:07:20 -07004622 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004623 * Dump the visible layer list
4624 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004625 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004626 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004627 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4628 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004629 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004630
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004631 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004632 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004633 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004634 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004635
David Sodman7e4ae112018-02-09 15:02:28 -08004636 result.append("\nFrame-Composition information:\n");
4637 dumpFrameCompositionInfo(result);
4638 result.append("\n");
4639
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004640 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004641 * Dump Display state
4642 */
4643
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004644 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004645 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004646 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004647 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004648 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004649 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004650 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004651
4652 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004653 * Dump SurfaceFlinger global state
4654 */
4655
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004656 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004657 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004658 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004659
Mathias Agopian888c8222012-08-04 21:10:38 -07004660 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004661 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004662
David Sodmanbc815282017-11-05 18:57:52 -08004663 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004664
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004665 if (display) {
4666 display->undefinedRegion.dump(result, "undefinedRegion");
4667 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4668 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004669 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004670 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004671 " gpu_to_cpu_unsupported : %d\n",
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004672 mTransactionFlags, !mGpuToCpuSupported);
4673
4674 if (display) {
4675 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4676 result.appendFormat(" refresh-rate : %f fps\n"
4677 " x-dpi : %f\n"
4678 " y-dpi : %f\n",
4679 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4680 activeConfig->getDpiY());
4681 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004682
Mathias Agopian74d211a2013-04-22 16:55:35 +02004683 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004684 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004685
Ana Krulec98b5b242018-08-10 15:03:23 -07004686 result.appendFormat(" use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004687 /*
4688 * VSYNC state
4689 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004690 if (mUseScheduler) {
4691 mScheduler->dump(mAppConnectionHandle, result);
4692 } else {
4693 mEventThread->dump(result);
4694 }
Dan Stozae22aec72016-08-01 13:20:59 -07004695 result.append("\n");
4696
4697 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004698 * Tracing state
4699 */
4700 mTracing.dump(result);
4701 result.append("\n");
4702
4703 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004704 * HWC layer minidump
4705 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004706 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004707 const int32_t displayId = display->getId();
4708 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004709 continue;
4710 }
4711
Dominik Laskowski7e045462018-05-30 13:02:02 -07004712 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004713 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004714 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004715 result.append("\n");
4716 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004717
4718 /*
4719 * Dump HWComposer state
4720 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004721 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004722 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004723 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004724 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004725 result.appendFormat(" h/w composer %s\n",
4726 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004727 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004728
4729 /*
4730 * Dump gralloc state
4731 */
4732 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4733 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004734
4735 /*
4736 * Dump VrFlinger state if in use.
4737 */
4738 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4739 result.append("VrFlinger state:\n");
4740 result.append(mVrFlinger->Dump().c_str());
4741 result.append("\n");
4742 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004743}
4744
Dominik Laskowski7e045462018-05-30 13:02:02 -07004745const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004746 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004747 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004748 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004749 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004750 }
4751 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004752
4753 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4754 static const Vector<sp<Layer>> empty;
4755 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004756}
4757
Keun young Park63f165f2012-08-31 10:53:36 -07004758bool SurfaceFlinger::startDdmConnection()
4759{
4760 void* libddmconnection_dso =
4761 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4762 if (!libddmconnection_dso) {
4763 return false;
4764 }
4765 void (*DdmConnection_start)(const char* name);
4766 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004767 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004768 if (!DdmConnection_start) {
4769 dlclose(libddmconnection_dso);
4770 return false;
4771 }
4772 (*DdmConnection_start)(getServiceName());
4773 return true;
4774}
4775
Chia-I Wu28f320b2018-05-03 11:02:56 -07004776void SurfaceFlinger::updateColorMatrixLocked() {
4777 mat4 colorMatrix;
4778 if (mGlobalSaturationFactor != 1.0f) {
4779 // Rec.709 luma coefficients
4780 float3 luminance{0.213f, 0.715f, 0.072f};
4781 luminance *= 1.0f - mGlobalSaturationFactor;
4782 mat4 saturationMatrix = mat4(
4783 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4784 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4785 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4786 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4787 );
4788 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4789 } else {
4790 colorMatrix = mClientColorMatrix * mDaltonizer();
4791 }
4792
4793 if (mCurrentState.colorMatrix != colorMatrix) {
4794 mCurrentState.colorMatrix = colorMatrix;
4795 mCurrentState.colorMatrixChanged = true;
4796 setTransactionFlags(eTransactionNeeded);
4797 }
4798}
4799
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004800status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004801#pragma clang diagnostic push
4802#pragma clang diagnostic error "-Wswitch-enum"
4803 switch (static_cast<ISurfaceComposerTag>(code)) {
4804 // These methods should at minimum make sure that the client requested
4805 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004806 case BOOT_FINISHED:
4807 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004808 case CREATE_CONNECTION:
4809 case CREATE_DISPLAY:
4810 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004811 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004812 case GET_ACTIVE_COLOR_MODE:
4813 case GET_ANIMATION_FRAME_STATS:
4814 case GET_HDR_CAPABILITIES:
4815 case SET_ACTIVE_CONFIG:
4816 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004817 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004818 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004819 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4820 IPCThreadState* ipc = IPCThreadState::self();
4821 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4822 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004823 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004824 }
Robert Carr1db73f62016-12-21 12:58:51 -08004825 return OK;
4826 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004827 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004828 IPCThreadState* ipc = IPCThreadState::self();
4829 const int pid = ipc->getCallingPid();
4830 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004831 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4832 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004833 return PERMISSION_DENIED;
4834 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004835 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004836 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004837 // Used by apps to hook Choreographer to SurfaceFlinger.
4838 case CREATE_DISPLAY_EVENT_CONNECTION:
4839 // The following calls are currently used by clients that do not
4840 // request necessary permissions. However, they do not expose any secret
4841 // information, so it is OK to pass them.
4842 case AUTHENTICATE_SURFACE:
4843 case GET_ACTIVE_CONFIG:
4844 case GET_BUILT_IN_DISPLAY:
4845 case GET_DISPLAY_COLOR_MODES:
4846 case GET_DISPLAY_CONFIGS:
4847 case GET_DISPLAY_STATS:
4848 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4849 // Calling setTransactionState is safe, because you need to have been
4850 // granted a reference to Client* and Handle* to do anything with it.
4851 case SET_TRANSACTION_STATE:
4852 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004853 case CREATE_SCOPED_CONNECTION:
4854 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004855 return OK;
4856 }
4857 case CAPTURE_LAYERS:
4858 case CAPTURE_SCREEN: {
4859 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004860 IPCThreadState* ipc = IPCThreadState::self();
4861 const int pid = ipc->getCallingPid();
4862 const int uid = ipc->getCallingUid();
4863 if ((uid != AID_GRAPHICS) &&
4864 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4865 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4866 return PERMISSION_DENIED;
4867 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004868 return OK;
4869 }
4870 // The following codes are deprecated and should never be allowed to access SF.
4871 case CONNECT_DISPLAY_UNUSED:
4872 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4873 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4874 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004875 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004876 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004877
4878 // These codes are used for the IBinder protocol to either interrogate the recipient
4879 // side of the transaction for its canonical interface descriptor or to dump its state.
4880 // We let them pass by default.
4881 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4882 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4883 code == IBinder::SYSPROPS_TRANSACTION) {
4884 return OK;
4885 }
4886 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4887 // in onTransact verifies that the user is root, and has access to use SF.
4888 if (code >= 1000 && code <= 1029) {
4889 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4890 return OK;
4891 }
4892 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4893 return PERMISSION_DENIED;
4894#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004895}
4896
Ana Krulec13be8ad2018-08-21 02:43:56 +00004897status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4898 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004899 status_t credentialCheck = CheckTransactCodeCredentials(code);
4900 if (credentialCheck != OK) {
4901 return credentialCheck;
4902 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004903
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004904 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4905 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004906 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004907 IPCThreadState* ipc = IPCThreadState::self();
4908 const int uid = ipc->getCallingUid();
4909 if (CC_UNLIKELY(uid != AID_SYSTEM
4910 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004911 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004912 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004913 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004914 return PERMISSION_DENIED;
4915 }
4916 int n;
4917 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004918 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004919 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004920 return NO_ERROR;
4921 case 1002: // SHOW_UPDATES
4922 n = data.readInt32();
4923 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004924 invalidateHwcGeometry();
4925 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004926 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004927 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004928 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004929 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004930 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004931 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004932 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004933 setTransactionFlags(
4934 eTransactionNeeded|
4935 eDisplayTransactionNeeded|
4936 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004937 return NO_ERROR;
4938 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004939 case 1006:{ // send empty update
4940 signalRefresh();
4941 return NO_ERROR;
4942 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004943 case 1008: // toggle use of hw composer
4944 n = data.readInt32();
4945 mDebugDisableHWC = n ? 1 : 0;
4946 invalidateHwcGeometry();
4947 repaintEverything();
4948 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004949 case 1009: // toggle use of transform hint
4950 n = data.readInt32();
4951 mDebugDisableTransformHint = n ? 1 : 0;
4952 invalidateHwcGeometry();
4953 repaintEverything();
4954 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004955 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004956 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004957 reply->writeInt32(0);
4958 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004959 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004960 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004961 return NO_ERROR;
4962 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004963 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004964 if (!display) {
4965 return NAME_NOT_FOUND;
4966 }
4967
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004968 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004969 return NO_ERROR;
4970 }
4971 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004972 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004973 // daltonize
4974 n = data.readInt32();
4975 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004976 case 1:
4977 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4978 break;
4979 case 2:
4980 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4981 break;
4982 case 3:
4983 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4984 break;
4985 default:
4986 mDaltonizer.setType(ColorBlindnessType::None);
4987 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004988 }
4989 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004990 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004991 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004992 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004993 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004994
4995 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004996 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004997 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004998 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004999 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005000 // apply a color matrix
5001 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005002 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005003 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005004 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005005 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005006 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005007 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005008 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005009 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005010 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005011 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005012
5013 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5014 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005015 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005016 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5017 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5018 }
5019
Chia-I Wu28f320b2018-05-03 11:02:56 -07005020 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005021 return NO_ERROR;
5022 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005023 // This is an experimental interface
5024 // Needs to be shifted to proper binder interface when we productize
5025 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005026 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07005027 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005028 return NO_ERROR;
5029 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005030 case 1017: {
5031 n = data.readInt32();
5032 mForceFullDamage = static_cast<bool>(n);
5033 return NO_ERROR;
5034 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005035 case 1018: { // Modify Choreographer's phase offset
5036 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005037 if (mUseScheduler) {
5038 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5039 } else {
5040 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5041 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005042 return NO_ERROR;
5043 }
5044 case 1019: { // Modify SurfaceFlinger's phase offset
5045 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005046 if (mUseScheduler) {
5047 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5048 } else {
5049 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5050 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005051 return NO_ERROR;
5052 }
Irvel468051e2016-06-13 16:44:44 -07005053 case 1020: { // Layer updates interceptor
5054 n = data.readInt32();
5055 if (n) {
5056 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005057 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005058 }
5059 else{
5060 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005061 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005062 }
5063 return NO_ERROR;
5064 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005065 case 1021: { // Disable HWC virtual displays
5066 n = data.readInt32();
5067 mUseHwcVirtualDisplays = !n;
5068 return NO_ERROR;
5069 }
Romain Guy0147a172017-06-01 13:53:56 -07005070 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005071 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005072 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005073
Chia-I Wu28f320b2018-05-03 11:02:56 -07005074 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005075 return NO_ERROR;
5076 }
Romain Guy54f154a2017-10-24 21:40:32 +01005077 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005078 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005079 invalidateHwcGeometry();
5080 repaintEverything();
5081 return NO_ERROR;
5082 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005083 // TODO(b/111505327): Find out whether the usage of 1024 can switch to 1030,
5084 // deprecate 1024 if they can.
5085 case 1024: { // Does device have wide color gamut display?
Romain Guy54f154a2017-10-24 21:40:32 +01005086 reply->writeBool(hasWideColorDisplay);
5087 return NO_ERROR;
5088 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005089 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005090 n = data.readInt32();
5091 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005092 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005093 mTracing.enable();
5094 doTracing("tracing.enable");
5095 reply->writeInt32(NO_ERROR);
5096 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005097 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005098 status_t err = mTracing.disable();
5099 reply->writeInt32(err);
5100 }
5101 return NO_ERROR;
5102 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005103 case 1026: { // Get layer tracing status
5104 reply->writeBool(mTracing.isEnabled());
5105 return NO_ERROR;
5106 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005107 // Is a DisplayColorSetting supported?
5108 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005109 const auto display = getDefaultDisplayDevice();
5110 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005111 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005112 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005113
5114 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5115 switch (setting) {
5116 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005117 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005118 break;
5119 case DisplayColorSetting::UNMANAGED:
5120 reply->writeBool(true);
5121 break;
5122 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005123 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005124 break;
5125 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005126 reply->writeBool(
5127 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005128 break;
5129 }
5130 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005131 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005132 // Is VrFlinger active?
5133 case 1028: {
5134 Mutex::Autolock _l(mStateLock);
5135 reply->writeBool(getBE().mHwc->isUsingVrComposer());
5136 return NO_ERROR;
5137 }
David Sodman6d46c1e2018-07-13 12:59:48 -07005138 case 1029: {
5139 // Code 1029 is an experimental feature that allows applications to
5140 // simulate a high frequency panel by setting a multiplier and divisor
5141 // on the VSYNC-sf clock. If either the multiplier or divisor are
David Sodman44b5de02018-08-21 16:28:53 -07005142 // 0, then the code simply return the current multiplier and divisor.
5143 HWC2::Device::FrequencyScaler frequencyScaler;
5144 frequencyScaler.multiplier = data.readInt32();
5145 frequencyScaler.divisor = data.readInt32();
David Sodman6d46c1e2018-07-13 12:59:48 -07005146
David Sodman44b5de02018-08-21 16:28:53 -07005147 if ((frequencyScaler.multiplier == 0) || (frequencyScaler.divisor == 0)) {
5148 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5149 reply->writeInt32(frequencyScaler.multiplier);
5150 reply->writeInt32(frequencyScaler.divisor);
5151 return NO_ERROR;
David Sodman6d46c1e2018-07-13 12:59:48 -07005152 }
5153
David Sodman44b5de02018-08-21 16:28:53 -07005154 if ((frequencyScaler.multiplier == 1) && (frequencyScaler.divisor == 1)) {
David Sodman6d46c1e2018-07-13 12:59:48 -07005155 enableHardwareVsync();
5156 } else {
5157 disableHardwareVsync(true);
5158 }
David Sodman44b5de02018-08-21 16:28:53 -07005159 mPrimaryDispSync->scalePeriod(frequencyScaler);
5160 getBE().mHwc->setDisplayFrequencyScaleParameters(frequencyScaler);
David Sodman6d46c1e2018-07-13 12:59:48 -07005161
David Sodman44b5de02018-08-21 16:28:53 -07005162 ATRACE_INT("PeriodMultiplier", frequencyScaler.multiplier);
5163 ATRACE_INT("PeriodDivisor", frequencyScaler.divisor);
5164
5165 const hwc2_display_t hwcDisplayId = getBE().mHwc->getActiveConfig(
5166 DisplayDevice::DISPLAY_PRIMARY)->getDisplayId();
5167
5168 onHotplugReceived(getBE().mComposerSequenceId,
5169 hwcDisplayId, HWC2::Connection::Disconnected);
5170 onHotplugReceived(getBE().mComposerSequenceId,
5171 hwcDisplayId, HWC2::Connection::Connected);
5172 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5173 reply->writeInt32(frequencyScaler.multiplier);
5174 reply->writeInt32(frequencyScaler.divisor);
5175
David Sodman6d46c1e2018-07-13 12:59:48 -07005176 return NO_ERROR;
5177 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005178 // Is device color managed?
5179 case 1030: {
5180 reply->writeBool(useColorManagement);
5181 return NO_ERROR;
5182 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005183 }
5184 }
5185 return err;
5186}
5187
Steven Thomas6d8110b2017-08-31 18:24:21 -07005188void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07005189 android_atomic_or(1, &mRepaintEverything);
5190 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005191}
5192
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005193// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5194class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005195public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005196 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5197 ~WindowDisconnector() {
5198 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005199 }
5200
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005201private:
5202 ANativeWindow* mWindow;
5203 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005204};
5205
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005206status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
5207 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
5208 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
5209 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005210 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005211 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005212
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005213 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005214
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005215 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5216
Chia-I Wu20261cb2018-08-23 12:55:44 -07005217 sp<DisplayDevice> display;
5218 {
5219 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005220
Chia-I Wu20261cb2018-08-23 12:55:44 -07005221 display = getDisplayDeviceLocked(displayToken);
5222 if (!display) return BAD_VALUE;
5223
Chia-I Wu8730ba82018-08-29 09:25:59 -07005224 // ignore sourceCrop (i.e., use the projected logical display
5225 // viewport) until the framework is fixed
5226 sourceCrop.clear();
Chia-I Wucb023152018-08-28 12:57:23 -07005227
5228 // set the requested width/height to the logical display viewport size
5229 // by default
5230 if (reqWidth == 0 || reqHeight == 0) {
5231 reqWidth = uint32_t(display->getViewport().width());
5232 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005233 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005234 }
5235
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005236 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005237
5238 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005239 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005240 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005241}
5242
5243status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08005244 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005245 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005246 ATRACE_CALL();
5247
5248 class LayerRenderArea : public RenderArea {
5249 public:
Robert Carr578038f2018-03-09 12:25:24 -08005250 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
5251 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
Chia-I Wu9d1abea2018-08-23 13:44:43 -07005252 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08005253 mLayer(layer),
5254 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005255 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005256 mFlinger(flinger),
5257 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005258 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005259 Rect getBounds() const override {
5260 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005261 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005262 }
Marissa Wall61c58622018-07-18 10:12:20 -07005263 int getHeight() const override {
5264 return mLayer->getActiveHeight(mLayer->getDrawingState());
5265 }
5266 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005267 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005268 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005269 Rect getSourceCrop() const override {
5270 if (mCrop.isEmpty()) {
5271 return getBounds();
5272 } else {
5273 return mCrop;
5274 }
5275 }
Robert Carr578038f2018-03-09 12:25:24 -08005276 class ReparentForDrawing {
5277 public:
5278 const sp<Layer>& oldParent;
5279 const sp<Layer>& newParent;
5280
5281 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5282 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005283 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005284 }
Robert Carr15eae092018-03-23 13:43:53 -07005285 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005286 };
5287
5288 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005289 const Rect sourceCrop = getSourceCrop();
5290 // no need to check rotation because there is none
5291 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5292 sourceCrop.height() != getReqHeight();
5293
Robert Carr578038f2018-03-09 12:25:24 -08005294 if (!mChildrenOnly) {
5295 mTransform = mLayer->getTransform().inverse();
5296 drawLayers();
5297 } else {
5298 Rect bounds = getBounds();
5299 screenshotParentLayer =
5300 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
5301 bounds.getWidth(), bounds.getHeight(), 0);
5302
5303 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5304 drawLayers();
5305 }
5306 }
chaviwa76b2712017-09-20 12:02:26 -07005307
chaviwa76b2712017-09-20 12:02:26 -07005308 private:
chaviw7206d492017-11-10 16:16:12 -08005309 const sp<Layer> mLayer;
5310 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005311
5312 // In the "childrenOnly" case we reparent the children to a screenshot
5313 // layer which has no properties set and which does not draw.
5314 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005315 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005316 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005317
5318 SurfaceFlinger* mFlinger;
5319 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005320 };
5321
5322 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5323 auto parent = layerHandle->owner.promote();
5324
chaviw7206d492017-11-10 16:16:12 -08005325 if (parent == nullptr || parent->isPendingRemoval()) {
5326 ALOGE("captureLayers called with a removed parent");
5327 return NAME_NOT_FOUND;
5328 }
5329
Robert Carr578038f2018-03-09 12:25:24 -08005330 const int uid = IPCThreadState::self()->getCallingUid();
5331 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5332 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5333 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5334 return PERMISSION_DENIED;
5335 }
5336
chaviw7206d492017-11-10 16:16:12 -08005337 Rect crop(sourceCrop);
5338 if (sourceCrop.width() <= 0) {
5339 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005340 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005341 }
5342
5343 if (sourceCrop.height() <= 0) {
5344 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005345 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005346 }
5347
5348 int32_t reqWidth = crop.width() * frameScale;
5349 int32_t reqHeight = crop.height() * frameScale;
5350
Chia-I Wu20261cb2018-08-23 12:55:44 -07005351 // really small crop or frameScale
5352 if (reqWidth <= 0) {
5353 reqWidth = 1;
5354 }
5355 if (reqHeight <= 0) {
5356 reqHeight = 1;
5357 }
5358
Robert Carr578038f2018-03-09 12:25:24 -08005359 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005360
Robert Carr578038f2018-03-09 12:25:24 -08005361 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005362 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5363 if (!layer->isVisible()) {
5364 return;
Robert Carr578038f2018-03-09 12:25:24 -08005365 } else if (childrenOnly && layer == parent.get()) {
5366 return;
chaviwa76b2712017-09-20 12:02:26 -07005367 }
5368 visitor(layer);
5369 });
5370 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005371 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005372}
5373
5374status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5375 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005376 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005377 bool useIdentityTransform) {
5378 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005379
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005380 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5381 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5382 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5383 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005384
5385 // This mutex protects syncFd and captureResult for communication of the return values from the
5386 // main thread back to this Binder thread
5387 std::mutex captureMutex;
5388 std::condition_variable captureCondition;
5389 std::unique_lock<std::mutex> captureLock(captureMutex);
5390 int syncFd = -1;
5391 std::optional<status_t> captureResult;
5392
Robert Carr03480e22018-01-04 16:02:06 -08005393 const int uid = IPCThreadState::self()->getCallingUid();
5394 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5395
Dominik Laskowski8c001672018-05-30 16:52:06 -07005396 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005397 // If there is a refresh pending, bug out early and tell the binder thread to try again
5398 // after the refresh.
5399 if (mRefreshPending) {
5400 ATRACE_NAME("Skipping screenshot for now");
5401 std::unique_lock<std::mutex> captureLock(captureMutex);
5402 captureResult = std::make_optional<status_t>(EAGAIN);
5403 captureCondition.notify_one();
5404 return;
5405 }
5406
5407 status_t result = NO_ERROR;
5408 int fd = -1;
5409 {
5410 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005411 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005412 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5413 useIdentityTransform, forSystem, &fd);
5414 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005415 }
5416
5417 {
5418 std::unique_lock<std::mutex> captureLock(captureMutex);
5419 syncFd = fd;
5420 captureResult = std::make_optional<status_t>(result);
5421 captureCondition.notify_one();
5422 }
5423 });
5424
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005425 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005426 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005427 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005428 while (*captureResult == EAGAIN) {
5429 captureResult.reset();
5430 result = postMessageAsync(message);
5431 if (result != NO_ERROR) {
5432 return result;
5433 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005434 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005435 }
5436 result = *captureResult;
5437 }
5438
5439 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005440 sync_wait(syncFd, -1);
5441 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005442 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005443
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005444 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005445}
5446
chaviwa76b2712017-09-20 12:02:26 -07005447void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005448 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005449 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005450 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005451
Lloyd Pique144e1162017-12-20 16:44:52 -08005452 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005453
chaviwa76b2712017-09-20 12:02:26 -07005454 const auto reqWidth = renderArea.getReqWidth();
5455 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005456 const auto sourceCrop = renderArea.getSourceCrop();
5457 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005458
Chia-I Wu36574d92018-05-16 10:54:36 -07005459 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5460 engine.setOutputDataSpace(Dataspace::SRGB);
5461 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005462
Mathias Agopian180f10d2013-04-10 22:55:41 -07005463 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005464 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005465
5466 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005467 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005468 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005469
chaviw50da5042018-04-09 13:49:37 -07005470 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005471 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005472 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005473
chaviwa76b2712017-09-20 12:02:26 -07005474 traverseLayers([&](Layer* layer) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08005475 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005476 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005477}
5478
chaviwa76b2712017-09-20 12:02:26 -07005479status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5480 TraverseLayersFunction traverseLayers,
5481 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005482 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005483 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005484 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005485 ATRACE_CALL();
5486
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005487 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005488
5489 traverseLayers([&](Layer* layer) {
5490 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5491 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005492
Robert Carr03480e22018-01-04 16:02:06 -08005493 // We allow the system server to take screenshots of secure layers for
5494 // use in situations like the Screen-rotation animation and place
5495 // the impetus on WindowManager to not persist them.
5496 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005497 ALOGW("FB is protected: PERMISSION_DENIED");
5498 return PERMISSION_DENIED;
5499 }
5500
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005501 // this binds the given EGLImage as a framebuffer for the
5502 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005503 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005504 if (bufferBond.getStatus() != NO_ERROR) {
5505 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005506 return INVALID_OPERATION;
5507 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005508
Dan Stozaabcda352017-06-01 14:37:39 -07005509 // this will in fact render into our dequeued buffer
5510 // via an FBO, which means we didn't have to create
5511 // an EGLSurface and therefore we're not
5512 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005513 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005514
Dan Stozaabcda352017-06-01 14:37:39 -07005515 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005516 getRenderEngine().finish();
5517 *outSyncFd = -1;
5518
chaviwa76b2712017-09-20 12:02:26 -07005519 const auto reqWidth = renderArea.getReqWidth();
5520 const auto reqHeight = renderArea.getReqHeight();
5521
Dan Stozaabcda352017-06-01 14:37:39 -07005522 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5523 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005524 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005525 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005526 } else {
5527 base::unique_fd syncFd = getRenderEngine().flush();
5528 if (syncFd < 0) {
5529 getRenderEngine().finish();
5530 }
5531 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005532 }
5533
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005534 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005535}
5536
Mathias Agopiand5556842013-09-19 17:08:37 -07005537void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005538 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005539 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005540 for (size_t y = 0; y < h; y++) {
5541 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5542 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005543 if (p[x] != 0xFF000000) return;
5544 }
5545 }
chaviwa76b2712017-09-20 12:02:26 -07005546 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005547
Robert Carr2047fae2016-11-28 14:09:09 -08005548 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005549 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005550 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005551 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5552 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5553 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5554 static_cast<float>(state.color.a));
5555 i++;
5556 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005557 }
5558}
5559
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005560// ---------------------------------------------------------------------------
5561
Dan Stoza412903f2017-04-27 13:42:17 -07005562void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5563 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005564}
5565
Dan Stoza412903f2017-04-27 13:42:17 -07005566void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5567 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005568}
5569
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005570void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5571 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005572 const LayerVector::Visitor& visitor) {
5573 // We loop through the first level of layers without traversing,
5574 // as we need to interpret min/max layer Z in the top level Z space.
5575 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005576 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005577 continue;
5578 }
5579 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005580 // relative layers are traversed in Layer::traverseInZOrder
5581 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005582 continue;
5583 }
5584 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005585 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005586 return;
5587 }
chaviwa76b2712017-09-20 12:02:26 -07005588 if (!layer->isVisible()) {
5589 return;
5590 }
5591 visitor(layer);
5592 });
5593 }
5594}
5595
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005596}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005597
Lloyd Pique074e8122018-07-26 12:57:23 -07005598
Mathias Agopian3f844832013-08-07 21:24:32 -07005599#if defined(__gl_h_)
5600#error "don't include gl/gl.h in this file"
5601#endif
5602
5603#if defined(__gl2_h_)
5604#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005605#endif