blob: e2605b29f1893ba2d758aaf9990deabc7f631a03 [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
106namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700107
Jaesoo Lee43518572017-01-23 19:03:16 +0900108using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900109using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700110using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700111using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700112using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700113using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900114
Steven Thomasb02664d2017-07-26 18:48:28 -0700115namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700116
117#pragma clang diagnostic push
118#pragma clang diagnostic error "-Wswitch-enum"
119
120bool isWideColorMode(const ColorMode colorMode) {
121 switch (colorMode) {
122 case ColorMode::DISPLAY_P3:
123 case ColorMode::ADOBE_RGB:
124 case ColorMode::DCI_P3:
125 case ColorMode::BT2020:
126 case ColorMode::BT2100_PQ:
127 case ColorMode::BT2100_HLG:
128 return true;
129 case ColorMode::NATIVE:
130 case ColorMode::STANDARD_BT601_625:
131 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
132 case ColorMode::STANDARD_BT601_525:
133 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
134 case ColorMode::STANDARD_BT709:
135 case ColorMode::SRGB:
136 return false;
137 }
138 return false;
139}
140
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700141ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
142 switch (rotation) {
143 case ISurfaceComposer::eRotateNone:
144 return ui::Transform::ROT_0;
145 case ISurfaceComposer::eRotate90:
146 return ui::Transform::ROT_90;
147 case ISurfaceComposer::eRotate180:
148 return ui::Transform::ROT_180;
149 case ISurfaceComposer::eRotate270:
150 return ui::Transform::ROT_270;
151 }
152 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
153 return ui::Transform::ROT_0;
154}
155
Peiyong Linfca547f2018-07-09 13:03:33 -0700156#pragma clang diagnostic pop
157
Steven Thomasb02664d2017-07-26 18:48:28 -0700158class ConditionalLock {
159public:
160 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
161 if (lock) {
162 mMutex.lock();
163 }
164 }
165 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
166private:
167 Mutex& mMutex;
168 bool mLocked;
169};
Peiyong Linfca547f2018-07-09 13:03:33 -0700170
Steven Thomasb02664d2017-07-26 18:48:28 -0700171} // namespace anonymous
172
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800173// ---------------------------------------------------------------------------
174
Mathias Agopian99b49842011-06-27 16:05:52 -0700175const String16 sHardwareTest("android.permission.HARDWARE_TEST");
176const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
177const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
178const String16 sDump("android.permission.DUMP");
179
180// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800181int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
182int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700183int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700184bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800185uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800186bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800187bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800188int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800189// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600190bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700191int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700192bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700193bool SurfaceFlinger::useContextPriority;
Peiyong Lin0256f722018-08-31 15:45:10 -0700194Dataspace SurfaceFlinger::compositionDataSpace = Dataspace::V0_SRGB;
195ui::PixelFormat SurfaceFlinger::compositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700196
Kalle Raitaa099a242017-01-11 11:17:29 -0800197std::string getHwcServiceName() {
198 char value[PROPERTY_VALUE_MAX] = {};
199 property_get("debug.sf.hwc_service_name", value, "default");
200 ALOGI("Using HWComposer service: '%s'", value);
201 return std::string(value);
202}
203
204bool useTrebleTestingOverride() {
205 char value[PROPERTY_VALUE_MAX] = {};
206 property_get("debug.sf.treble_testing_override", value, "false");
207 ALOGI("Treble testing override: '%s'", value);
208 return std::string(value) == "true";
209}
210
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800211std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
212 switch(displayColorSetting) {
213 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700214 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800215 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700216 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800217 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700218 return std::string("Enhanced");
219 default:
220 return std::string("Unknown ") +
221 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800222 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800223}
224
Lloyd Pique99d3da52018-01-22 17:48:03 -0800225NativeWindowSurface::~NativeWindowSurface() = default;
226
227namespace impl {
228
229class NativeWindowSurface final : public android::NativeWindowSurface {
230public:
231 static std::unique_ptr<android::NativeWindowSurface> create(
232 const sp<IGraphicBufferProducer>& producer) {
233 return std::make_unique<NativeWindowSurface>(producer);
234 }
235
236 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
237 : surface(new Surface(producer, false)) {}
238
239 ~NativeWindowSurface() override = default;
240
241private:
242 sp<ANativeWindow> getNativeWindow() const override { return surface; }
243
244 void preallocateBuffers() override { surface->allocateBuffers(); }
245
246 sp<Surface> surface;
247};
248
249} // namespace impl
250
David Sodmanbc815282017-11-05 18:57:52 -0800251SurfaceFlingerBE::SurfaceFlingerBE()
252 : mHwcServiceName(getHwcServiceName()),
253 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800254 mFrameBuckets(),
255 mTotalTime(0),
256 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800257 mComposerSequenceId(0) {
258}
259
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800260SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800261 : BnSurfaceComposer(),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700262 mTransactionPending(false),
263 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700264 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700265 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800266 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700267 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800268 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800269 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800270 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800271 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800272 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700273 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700274 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700275 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700276 mDebugInTransaction(0),
277 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700278 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700279 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700280 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800281 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800282 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800283 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700284 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800285 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800286 mCreateBufferQueue(&BufferQueue::createBufferQueue),
287 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800288
289SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800290 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800291
292 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
293 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
294
295 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
296 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
297
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800298 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
299 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800300
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700301 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
302 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
303
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700304 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
305 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
306
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800307 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
308 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
309
Steven Thomas050b2c82017-03-06 11:45:16 -0800310 // Vr flinger is only enabled on Daydream ready devices.
311 useVrFlinger = getBool< ISurfaceFlingerConfigs,
312 &ISurfaceFlingerConfigs::useVrFlinger>(false);
313
Fabien Sanglard1971b632017-03-10 14:50:03 -0800314 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
315 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
316
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600317 hasWideColorDisplay =
318 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700319 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700320 getBool<V1_2::ISurfaceFlingerConfigs,
321 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
322
323 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
324 if (surfaceFlingerConfigsServiceV1_2) {
325 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
326 [&](Dataspace tmpDataSpace, ui::PixelFormat tmpPixelFormat) {
327 compositionDataSpace = tmpDataSpace;
328 compositionPixelFormat = tmpPixelFormat;
329 });
330 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600331
Peiyong Linb3839ad2018-09-05 15:37:19 -0700332 useContextPriority = getBool<ISurfaceFlingerConfigs,
333 &ISurfaceFlingerConfigs::useContextPriority>(true);
334
Iris Chang7501ed62018-04-30 14:45:42 +0800335 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700336 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
337 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800338 V1_1::DisplayOrientation::ORIENTATION_0);
339
340 switch (primaryDisplayOrientation) {
341 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700342 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800343 break;
344 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700345 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800346 break;
347 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700348 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800349 break;
350 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700351 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800352 break;
353 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700354 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800355
Lloyd Pique41be5d22018-06-21 13:11:48 -0700356 // Note: We create a local temporary with the real DispSync implementation
357 // type temporarily so we can initialize it with the configured values,
358 // before storing it for more generic use using the interface type.
359 auto primaryDispSync = std::make_unique<impl::DispSync>("PrimaryDispSync");
360 primaryDispSync->init(SurfaceFlinger::hasSyncFramework,
361 SurfaceFlinger::dispSyncPresentTimeOffset);
362 mPrimaryDispSync = std::move(primaryDispSync);
Saurabh Shahf4174532017-07-13 10:45:07 -0700363
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800364 // debugging stuff...
365 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700366
Mathias Agopianb4b17302013-03-20 18:36:41 -0700367 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700368 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700369
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800370 property_get("debug.sf.showupdates", value, "0");
371 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700372
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700373 property_get("debug.sf.ddms", value, "0");
374 mDebugDDMS = atoi(value);
375 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700376 if (!startDdmConnection()) {
377 // start failed, and DDMS debugging not enabled
378 mDebugDDMS = 0;
379 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700380 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700381 ALOGI_IF(mDebugRegion, "showupdates enabled");
382 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700383
384 property_get("debug.sf.disable_backpressure", value, "0");
385 mPropagateBackpressure = !atoi(value);
386 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700387
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800388 property_get("debug.sf.enable_hwc_vds", value, "0");
389 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800390 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800391
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800392 property_get("ro.sf.disable_triple_buffer", value, "1");
393 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800394 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700395
Yiwei Zhang243b3782018-05-15 17:40:04 -0700396 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700397 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
398 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
399
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200400 property_get("debug.sf.early_phase_offset_ns", value, "-1");
401 const int earlySfOffsetNs = atoi(value);
402
403 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
404 const int earlyGlSfOffsetNs = atoi(value);
405
406 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
407 const int earlyAppOffsetNs = atoi(value);
408
409 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
410 const int earlyGlAppOffsetNs = atoi(value);
411
Ana Krulec98b5b242018-08-10 15:03:23 -0700412 property_get("debug.sf.use_scheduler", value, "0");
413 mUseScheduler = atoi(value);
414
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200415 const VSyncModulator::Offsets earlyOffsets =
416 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
417 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
418 const VSyncModulator::Offsets earlyGlOffsets =
419 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
420 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
421 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
422 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700423
Romain Guy11d63f42017-07-20 12:47:14 -0700424 // We should be reading 'persist.sys.sf.color_saturation' here
425 // but since /data may be encrypted, we need to wait until after vold
426 // comes online to attempt to read the property. The property is
427 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800428
429 if (useTrebleTestingOverride()) {
430 // Without the override SurfaceFlinger cannot connect to HIDL
431 // services that are not listed in the manifests. Considered
432 // deriving the setting from the set service name, but it
433 // would be brittle if the name that's not 'default' is used
434 // for production purposes later on.
435 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
436 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800437}
438
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800439void SurfaceFlinger::onFirstRef()
440{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800441 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800442}
443
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800444SurfaceFlinger::~SurfaceFlinger()
445{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800446}
447
Dan Stozac7014012014-02-14 15:03:43 -0800448void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800449{
450 // the window manager died on us. prepare its eulogy.
451
Andy McFadden13a082e2012-08-24 10:16:42 -0700452 // restore initial conditions (default device unblank, etc)
453 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800454
455 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700456 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800457}
458
Robert Carr1db73f62016-12-21 12:58:51 -0800459static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700460 status_t err = client->initCheck();
461 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800462 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800463 }
Robert Carr1db73f62016-12-21 12:58:51 -0800464 return nullptr;
465}
466
467sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
468 return initClient(new Client(this));
469}
470
471sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
472 const sp<IGraphicBufferProducer>& gbp) {
473 if (authenticateSurfaceTexture(gbp) == false) {
474 return nullptr;
475 }
476 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
477 if (layer == nullptr) {
478 return nullptr;
479 }
480
481 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800482}
483
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700484sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
485 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700486{
487 class DisplayToken : public BBinder {
488 sp<SurfaceFlinger> flinger;
489 virtual ~DisplayToken() {
490 // no more references, this display must be terminated
491 Mutex::Autolock _l(flinger->mStateLock);
492 flinger->mCurrentState.displays.removeItem(this);
493 flinger->setTransactionFlags(eDisplayTransactionNeeded);
494 }
495 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700496 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700497 : flinger(flinger) {
498 }
499 };
500
501 sp<BBinder> token = new DisplayToken(this);
502
503 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700504 DisplayDeviceState info;
505 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700506 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700507 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700508 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800509 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700510 return token;
511}
512
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700513void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700514 Mutex::Autolock _l(mStateLock);
515
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700516 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700517 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700518 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700519 return;
520 }
521
522 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700523 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700524 ALOGE("destroyDisplay called for non-virtual display");
525 return;
526 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700527 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700528 mCurrentState.displays.removeItemsAt(idx);
529 setTransactionFlags(eDisplayTransactionNeeded);
530}
531
Mathias Agopiane57f2922012-08-09 16:29:12 -0700532sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700533 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700534 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800535 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700536 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700537 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700538}
539
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800540void SurfaceFlinger::bootFinished()
541{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700542 if (mStartPropertySetThread->join() != NO_ERROR) {
543 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800544 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800545 const nsecs_t now = systemTime();
546 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000547 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700548
549 // wait patiently for the window manager death
550 const String16 name("window");
551 sp<IBinder> window(defaultServiceManager()->getService(name));
552 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700553 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700554 }
555
Steven Thomas050b2c82017-03-06 11:45:16 -0800556 if (mVrFlinger) {
557 mVrFlinger->OnBootFinished();
558 }
559
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700560 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700561 // formerly we would just kill the process, but we now ask it to exit so it
562 // can choose where to stop the animation.
563 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700564
565 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
566 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
567 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700568
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800569 postMessageAsync(new LambdaMessage([this] {
570 readPersistentProperties();
571 mBootStage = BootStage::FINISHED;
572 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800573}
574
Dan Stoza436ccf32018-06-21 12:10:12 -0700575uint32_t SurfaceFlinger::getNewTexture() {
576 {
577 std::lock_guard lock(mTexturePoolMutex);
578 if (!mTexturePool.empty()) {
579 uint32_t name = mTexturePool.back();
580 mTexturePool.pop_back();
581 ATRACE_INT("TexturePoolSize", mTexturePool.size());
582 return name;
583 }
584
585 // The pool was too small, so increase it for the future
586 ++mTexturePoolSize;
587 }
588
589 // The pool was empty, so we need to get a new texture name directly using a
590 // blocking call to the main thread
591 uint32_t name = 0;
592 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
593 return name;
594}
595
Mathias Agopian3f844832013-08-07 21:24:32 -0700596void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700597 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700598}
599
Wei Wangf9b05ee2017-07-19 20:59:39 -0700600// Do not call property_set on main thread which will be blocked by init
601// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700602void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700603 ALOGI( "SurfaceFlinger's main thread ready to run. "
604 "Initializing graphics H/W...");
605
Thierry Strudel2924d012017-08-14 15:19:37 -0700606 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900607
Steven Thomasb02664d2017-07-26 18:48:28 -0700608 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800609
Steven Thomasb02664d2017-07-26 18:48:28 -0700610 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700611 if (mUseScheduler) {
612 mScheduler = std::make_unique<Scheduler>();
613 mAppConnectionHandle =
614 mScheduler->createConnection("appConnection", mPrimaryDispSync.get(),
615 SurfaceFlinger::vsyncPhaseOffsetNs,
616 [this] { resyncWithRateLimit(); },
617 impl::EventThread::InterceptVSyncsCallback());
618 mSfConnectionHandle =
619 mScheduler->createConnection("sfConnection", mPrimaryDispSync.get(),
620 SurfaceFlinger::sfVsyncPhaseOffsetNs,
621 [this] { resyncWithRateLimit(); },
622 [this](nsecs_t timestamp) {
623 mInterceptor->saveVSyncEvent(timestamp);
624 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800625
Ana Krulec98b5b242018-08-10 15:03:23 -0700626 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700627 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
628 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700629 } else {
630 mEventThreadSource =
631 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
632 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
633 mEventThread =
634 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
635 [this] { resyncWithRateLimit(); },
636 impl::EventThread::InterceptVSyncsCallback(),
637 "appEventThread");
638 mSfEventThreadSource =
639 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
640 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
641
642 mSFEventThread =
643 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
644 [this] { resyncWithRateLimit(); },
645 [this](nsecs_t timestamp) {
646 mInterceptor->saveVSyncEvent(timestamp);
647 },
648 "sfEventThread");
649 mEventQueue->setEventThread(mSFEventThread.get());
650 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
651 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800652
Steven Thomasb02664d2017-07-26 18:48:28 -0700653 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700654 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700655 renderEngineFeature |= (useColorManagement ?
656 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700657 renderEngineFeature |= (useContextPriority ?
658 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700659
660 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
661 getBE().mRenderEngine =
Peiyong Linf11f39b2018-09-05 14:37:41 -0700662 renderengine::RenderEngine::create(static_cast<int32_t>(compositionPixelFormat),
663 renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800664 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700665
666 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
667 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800668 getBE().mHwc.reset(
669 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700670 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800671 // Process any initial hotplug and resulting display changes.
672 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700673 const auto display = getDefaultDisplayDeviceLocked();
674 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
675 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
676 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800677
Lloyd Piquefcd86612017-12-14 17:15:36 -0800678 // make the default display GLContext current so that we can create textures
679 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700680 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800681
Steven Thomas050b2c82017-03-06 11:45:16 -0800682 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700683 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700684 // This callback is called from the vr flinger dispatch thread. We
685 // need to call signalTransaction(), which requires holding
686 // mStateLock when we're not on the main thread. Acquiring
687 // mStateLock from the vr flinger dispatch thread might trigger a
688 // deadlock in surface flinger (see b/66916578), so post a message
689 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700690 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700691 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
692 mVrFlingerRequestsDisplay = requestDisplay;
693 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700694 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800695 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700696 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
697 getHwComposer()
698 .getHwcDisplayId(display->getId())
699 .value_or(0),
700 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800701 if (!mVrFlinger) {
702 ALOGE("Failed to start vrflinger");
703 }
704 }
705
Lloyd Pique379adc12018-01-22 17:31:47 -0800706 mEventControlThread = std::make_unique<impl::EventControlThread>(
707 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700708
Mathias Agopian92a979a2012-08-02 18:32:23 -0700709 // initialize our drawing state
710 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700711
Andy McFadden13a082e2012-08-24 10:16:42 -0700712 // set initial conditions (e.g. unblank default device)
713 initializeDisplays();
714
David Sodmanbc815282017-11-05 18:57:52 -0800715 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700716
Wei Wangf9b05ee2017-07-19 20:59:39 -0700717 // Inform native graphics APIs whether the present timestamp is supported:
718 if (getHwComposer().hasCapability(
719 HWC2::Capability::PresentFenceIsNotReliable)) {
720 mStartPropertySetThread = new StartPropertySetThread(false);
721 } else {
722 mStartPropertySetThread = new StartPropertySetThread(true);
723 }
724
725 if (mStartPropertySetThread->Start() != NO_ERROR) {
726 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800727 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800728
Chia-I Wud49d6692018-06-27 07:17:41 +0800729 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
730 // is used to saturate legacy sRGB content. However, to make sure the same color under
731 // Display P3 will be saturated to the same color, we intentionally break the API spec
732 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
733 // such saturation matrix on Display P3 is understood fully, the API should always return
734 // identify matrix.
735 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
736 Dataspace::SRGB_LINEAR);
737
738 // we will apply this on Display P3.
739 if (mEnhancedSaturationMatrix != mat4()) {
740 ColorSpace srgb(ColorSpace::sRGB());
741 ColorSpace displayP3(ColorSpace::DisplayP3());
742 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
743 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
744 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
745 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800746
Dan Stoza9e56aa02015-11-02 13:00:03 -0800747 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700748}
749
Romain Guy11d63f42017-07-20 12:47:14 -0700750void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700751 Mutex::Autolock _l(mStateLock);
752
Romain Guy11d63f42017-07-20 12:47:14 -0700753 char value[PROPERTY_VALUE_MAX];
754
755 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800756 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700757 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800758 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100759
760 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700761 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700762}
763
Mathias Agopiana67e4182012-06-19 17:26:12 -0700764void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800765 // Start boot animation service by setting a property mailbox
766 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700767 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800768 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700769 if (mStartPropertySetThread->join() != NO_ERROR) {
770 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800771 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700772}
773
Mathias Agopian875d8e12013-06-07 15:35:48 -0700774size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800775 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700776}
777
Mathias Agopian875d8e12013-06-07 15:35:48 -0700778size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800779 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700780}
781
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800782// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800783
Jamie Gennis582270d2011-08-17 18:19:00 -0700784bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800785 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800786 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800787 return authenticateSurfaceTextureLocked(bufferProducer);
788}
789
790bool SurfaceFlinger::authenticateSurfaceTextureLocked(
791 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800792 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800793 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800794}
795
Brian Anderson6b376712017-04-04 10:51:39 -0700796status_t SurfaceFlinger::getSupportedFrameTimestamps(
797 std::vector<FrameEvent>* outSupported) const {
798 *outSupported = {
799 FrameEvent::REQUESTED_PRESENT,
800 FrameEvent::ACQUIRE,
801 FrameEvent::LATCH,
802 FrameEvent::FIRST_REFRESH_START,
803 FrameEvent::LAST_REFRESH_START,
804 FrameEvent::GPU_COMPOSITION_DONE,
805 FrameEvent::DEQUEUE_READY,
806 FrameEvent::RELEASE,
807 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700808 ConditionalLock _l(mStateLock,
809 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700810 if (!getHwComposer().hasCapability(
811 HWC2::Capability::PresentFenceIsNotReliable)) {
812 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
813 }
814 return NO_ERROR;
815}
816
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700817status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
818 Vector<DisplayInfo>* configs) {
819 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700820 return BAD_VALUE;
821 }
822
Jesse Hall692c7232012-11-08 15:41:56 -0800823 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700824 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
825 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700826 type = i;
827 break;
828 }
829 }
830
831 if (type < 0) {
832 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700833 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700834
Mathias Agopian8b736f12012-08-13 17:54:26 -0700835 // TODO: Not sure if display density should handled by SF any longer
836 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700837 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700838 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700839 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800840 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700841 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700842 }
843 return density;
844 }
845 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700846 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700847 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700848 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700849 return getDensityFromProperty("ro.sf.lcd_density"); }
850 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700851
Dan Stoza7f7da322014-05-02 15:26:25 -0700852 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700853
Steven Thomas6d8110b2017-08-31 18:24:21 -0700854 ConditionalLock _l(mStateLock,
855 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800856 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700857 DisplayInfo info = DisplayInfo();
858
Dan Stoza9e56aa02015-11-02 13:00:03 -0800859 float xdpi = hwConfig->getDpiX();
860 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700861
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700862 info.w = hwConfig->getWidth();
863 info.h = hwConfig->getHeight();
864 // Default display viewport to display width and height
865 info.viewportW = info.w;
866 info.viewportH = info.h;
867
Dan Stoza7f7da322014-05-02 15:26:25 -0700868 if (type == DisplayDevice::DISPLAY_PRIMARY) {
869 // The density of the device is provided by a build property
870 float density = Density::getBuildDensity() / 160.0f;
871 if (density == 0) {
872 // the build doesn't provide a density -- this is wrong!
873 // use xdpi instead
874 ALOGE("ro.sf.lcd_density must be defined as a build property");
875 density = xdpi / 160.0f;
876 }
877 if (Density::getEmuDensity()) {
878 // if "qemu.sf.lcd_density" is specified, it overrides everything
879 xdpi = ydpi = density = Density::getEmuDensity();
880 density /= 160.0f;
881 }
882 info.density = density;
883
884 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700885 const auto display = getDefaultDisplayDeviceLocked();
886 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700887
888 // This is for screenrecord
889 const Rect viewport = display->getViewport();
890 if (viewport.isValid()) {
891 info.viewportW = uint32_t(viewport.getWidth());
892 info.viewportH = uint32_t(viewport.getHeight());
893 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700894 } else {
895 // TODO: where should this value come from?
896 static const int TV_DENSITY = 213;
897 info.density = TV_DENSITY / 160.0f;
898 info.orientation = 0;
899 }
900
Dan Stoza7f7da322014-05-02 15:26:25 -0700901 info.xdpi = xdpi;
902 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800903 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900904 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800905
Andy McFadden91b2ca82014-06-13 14:04:23 -0700906 // This is how far in advance a buffer must be queued for
907 // presentation at a given time. If you want a buffer to appear
908 // on the screen at time N, you must submit the buffer before
909 // (N - presentationDeadline).
910 //
911 // Normally it's one full refresh period (to give SF a chance to
912 // latch the buffer), but this can be reduced by configuring a
913 // DispSync offset. Any additional delays introduced by the hardware
914 // composer or panel must be accounted for here.
915 //
916 // We add an additional 1ms to allow for processing time and
917 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800918 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800919 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700920
921 // All non-virtual displays are currently considered secure.
922 info.secure = true;
923
Iris Chang7501ed62018-04-30 14:45:42 +0800924 if (type == DisplayDevice::DISPLAY_PRIMARY &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700925 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800926 std::swap(info.w, info.h);
927 }
928
Michael Wright28f24d02016-07-12 13:30:53 -0700929 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700930 }
931
Dan Stoza7f7da322014-05-02 15:26:25 -0700932 return NO_ERROR;
933}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700934
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700935status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
936 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700937 return BAD_VALUE;
938 }
939
940 // FIXME for now we always return stats for the primary display
941 memset(stats, 0, sizeof(*stats));
Lloyd Pique41be5d22018-06-21 13:11:48 -0700942 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
943 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700944 return NO_ERROR;
945}
946
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700947int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
948 const auto display = getDisplayDevice(displayToken);
949 if (!display) {
950 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800951 return BAD_VALUE;
952 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700953
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700954 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700955}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700956
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700957void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
958 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700959 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700960 return;
961 }
962
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700963 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700964 ALOGW("Trying to set config for virtual display");
965 return;
966 }
967
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700968 display->setActiveConfig(mode);
969 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700970}
971
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700972status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700973 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700974 Vector<DisplayInfo> configs;
975 getDisplayConfigs(displayToken, &configs);
976 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
977 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
978 configs.size());
979 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700980 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700981 const auto display = getDisplayDevice(displayToken);
982 if (!display) {
983 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
984 displayToken.get());
985 } else if (display->isVirtual()) {
986 ALOGW("Attempt to set active config %d for virtual display", mode);
987 } else {
988 setActiveConfigInternal(display, mode);
989 }
990 }));
991
Mathias Agopian888c8222012-08-04 21:10:38 -0700992 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700993}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700994status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
995 Vector<ColorMode>* outColorModes) {
996 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700997 return BAD_VALUE;
998 }
999
Michael Wright28f24d02016-07-12 13:30:53 -07001000 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001001 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
1002 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -07001003 type = i;
1004 break;
1005 }
1006 }
1007
1008 if (type < 0) {
1009 return type;
1010 }
1011
Peiyong Lina52f0292018-03-14 17:26:31 -07001012 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001013 {
1014 ConditionalLock _l(mStateLock,
1015 std::this_thread::get_id() != mMainThreadId);
1016 modes = getHwComposer().getColorModes(type);
1017 }
Michael Wright28f24d02016-07-12 13:30:53 -07001018 outColorModes->clear();
1019 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1020
1021 return NO_ERROR;
1022}
1023
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001024ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1025 if (const auto display = getDisplayDevice(displayToken)) {
1026 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001027 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001028 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001029}
1030
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001031void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1032 Dataspace dataSpace, RenderIntent renderIntent) {
1033 ColorMode currentMode = display->getActiveColorMode();
1034 Dataspace currentDataSpace = display->getCompositionDataSpace();
1035 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001036
Peiyong Lin38e9a562018-04-10 16:24:20 -07001037 if (mode == currentMode && dataSpace == currentDataSpace &&
1038 renderIntent == currentRenderIntent) {
1039 return;
1040 }
1041
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001042 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001043 ALOGW("Trying to set config for virtual display");
1044 return;
1045 }
1046
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001047 display->setActiveColorMode(mode);
1048 display->setCompositionDataSpace(dataSpace);
1049 display->setActiveRenderIntent(renderIntent);
1050 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001051
1052 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001053 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1054 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001055}
1056
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001057status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001058 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001059 Vector<ColorMode> modes;
1060 getDisplayColorModes(displayToken, &modes);
1061 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1062 if (mode < ColorMode::NATIVE || !exists) {
1063 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1064 decodeColorMode(mode).c_str(), mode, displayToken.get());
1065 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001066 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001067 const auto display = getDisplayDevice(displayToken);
1068 if (!display) {
1069 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1070 decodeColorMode(mode).c_str(), mode, displayToken.get());
1071 } else if (display->isVirtual()) {
1072 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1073 decodeColorMode(mode).c_str(), mode);
1074 } else {
1075 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1076 RenderIntent::COLORIMETRIC);
1077 }
1078 }));
1079
Michael Wright28f24d02016-07-12 13:30:53 -07001080 return NO_ERROR;
1081}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001082
Svetoslavd85084b2014-03-20 10:28:31 -07001083status_t SurfaceFlinger::clearAnimationFrameStats() {
1084 Mutex::Autolock _l(mStateLock);
1085 mAnimFrameTracker.clearStats();
1086 return NO_ERROR;
1087}
1088
1089status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1090 Mutex::Autolock _l(mStateLock);
1091 mAnimFrameTracker.getStats(outStats);
1092 return NO_ERROR;
1093}
1094
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001095status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1096 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001097 Mutex::Autolock _l(mStateLock);
1098
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001099 const auto display = getDisplayDeviceLocked(displayToken);
1100 if (!display) {
1101 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001102 return BAD_VALUE;
1103 }
1104
Peiyong Linfb069302018-04-25 14:34:31 -07001105 // At this point the DisplayDeivce should already be set up,
1106 // meaning the luminance information is already queried from
1107 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001108 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001109 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1110 capabilities.getDesiredMaxLuminance(),
1111 capabilities.getDesiredMaxAverageLuminance(),
1112 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001113
1114 return NO_ERROR;
1115}
1116
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001117status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001118 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001119 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001120
Chia-I Wu90f669f2017-10-05 14:24:41 -07001121 if (mInjectVSyncs == enable) {
1122 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001123 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001124
Ana Krulec98b5b242018-08-10 15:03:23 -07001125 // TODO(akrulec): Part of the Injector should be refactored, so that it
1126 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001127 if (enable) {
1128 ALOGV("VSync Injections enabled");
1129 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001130 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001131 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001132 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001133 impl::EventThread::InterceptVSyncsCallback(),
1134 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001135 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001136 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001137 } else {
1138 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001139 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001140 }
1141
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001142 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001143 }));
1144
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001145 return NO_ERROR;
1146}
1147
1148status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001149 Mutex::Autolock _l(mStateLock);
1150
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001151 if (!mInjectVSyncs) {
1152 ALOGE("VSync Injections not enabled");
1153 return BAD_VALUE;
1154 }
1155 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1156 ALOGV("Injecting VSync inside SurfaceFlinger");
1157 mVSyncInjector->onInjectSyncEvent(when);
1158 }
1159 return NO_ERROR;
1160}
1161
Lloyd Pique755e3192018-01-31 16:46:15 -08001162status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1163 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001164 // Try to acquire a lock for 1s, fail gracefully
1165 const status_t err = mStateLock.timedLock(s2ns(1));
1166 const bool locked = (err == NO_ERROR);
1167 if (!locked) {
1168 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1169 return TIMED_OUT;
1170 }
1171
1172 outLayers->clear();
1173 mCurrentState.traverseInZOrder([&](Layer* layer) {
1174 outLayers->push_back(layer->getLayerDebugInfo());
1175 });
1176
1177 mStateLock.unlock();
1178 return NO_ERROR;
1179}
1180
Peiyong Lin0256f722018-08-31 15:45:10 -07001181status_t SurfaceFlinger::getCompositionPreference(Dataspace* outDataSpace,
1182 ui::PixelFormat* outPixelFormat) const {
1183 *outDataSpace = compositionDataSpace;
1184 *outPixelFormat = compositionPixelFormat;
1185 return NO_ERROR;
1186}
1187
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001188// ----------------------------------------------------------------------------
1189
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001190sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1191 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001192 if (mUseScheduler) {
1193 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1194 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1195 } else {
1196 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1197 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001198 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001199 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1200 return mSFEventThread->createEventConnection();
1201 } else {
1202 return mEventThread->createEventConnection();
1203 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001204 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001205}
1206
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001207// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001208
1209void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001210 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001211}
1212
1213void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001214 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001215}
1216
1217void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001218 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001219}
1220
1221void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001222 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001223 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001224}
1225
1226status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001227 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001228 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001229}
1230
1231status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001232 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001233 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001234 if (res == NO_ERROR) {
1235 msg->wait();
1236 }
1237 return res;
1238}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001239
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001240void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001241 do {
1242 waitForEvent();
1243 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001244}
1245
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001246void SurfaceFlinger::enableHardwareVsync() {
1247 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001248 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001249 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001250 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001251 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001252 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001253}
1254
Jesse Hall948fe0c2013-10-14 12:56:09 -07001255void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001256 Mutex::Autolock _l(mHWVsyncLock);
1257
Jesse Hall948fe0c2013-10-14 12:56:09 -07001258 if (makeAvailable) {
1259 mHWVsyncAvailable = true;
1260 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001261 // Hardware vsync is not currently available, so abort the resync
1262 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001263 return;
1264 }
1265
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001266 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1267 if (!getHwComposer().isConnected(displayId)) {
1268 return;
1269 }
1270
1271 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001272 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001273
Lloyd Pique41be5d22018-06-21 13:11:48 -07001274 mPrimaryDispSync->reset();
1275 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001276
1277 if (!mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001278 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001279 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001280 mPrimaryHWVsyncEnabled = true;
1281 }
1282}
1283
Jesse Hall948fe0c2013-10-14 12:56:09 -07001284void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001285 Mutex::Autolock _l(mHWVsyncLock);
1286 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001287 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001288 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001289 mPrimaryHWVsyncEnabled = false;
1290 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001291 if (makeUnavailable) {
1292 mHWVsyncAvailable = false;
1293 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001294}
1295
Tim Murray4a4e4a22016-04-19 16:29:23 +00001296void SurfaceFlinger::resyncWithRateLimit() {
1297 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001298
1299 // No explicit locking is needed here since EventThread holds a lock while calling this method
1300 static nsecs_t sLastResyncAttempted = 0;
1301 const nsecs_t now = systemTime();
1302 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001303 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001304 }
Dan Stoza57164302017-05-08 14:03:54 -07001305 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001306}
1307
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001308void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1309 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001310 ATRACE_NAME("SF onVsync");
1311
Steven Thomas3cfac282017-02-06 12:29:30 -08001312 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001313 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001314 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001315 return;
1316 }
1317
1318 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001319 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001320 return;
1321 }
1322
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001323 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1324 // For now, we don't do anything with external display vsyncs.
1325 return;
1326 }
1327
Jamie Gennisd1700752013-10-14 12:22:52 -07001328 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001329
Jamie Gennisd1700752013-10-14 12:22:52 -07001330 { // Scope for the lock
1331 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001332 if (mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001333 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001334 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001335 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001336
1337 if (needsHwVsync) {
1338 enableHardwareVsync();
1339 } else {
1340 disableHardwareVsync(false);
1341 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001342}
1343
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001344void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001345 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1346 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001347}
1348
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001349void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001350 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001351 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001352 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001353
Lloyd Piqueba04e622017-12-14 17:11:26 -08001354 // Ignore events that do not have the right sequenceId.
1355 if (sequenceId != getBE().mComposerSequenceId) {
1356 return;
1357 }
1358
Steven Thomasb02664d2017-07-26 18:48:28 -07001359 // Only lock if we're not on the main thread. This function is normally
1360 // called on a hwbinder thread, but for the primary display it's called on
1361 // the main thread with the state lock already held, so don't attempt to
1362 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001363 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001364
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001365 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001366
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001367 if (std::this_thread::get_id() == mMainThreadId) {
1368 // Process all pending hot plug events immediately if we are on the main thread.
1369 processDisplayHotplugEventsLocked();
1370 }
1371
Lloyd Piqueba04e622017-12-14 17:11:26 -08001372 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001373}
1374
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001375void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001376 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001377 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001378 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001379 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001380 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001381}
1382
Dan Stoza9e56aa02015-11-02 13:00:03 -08001383void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001384 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001385 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001386 getHwComposer().setVsyncEnabled(disp,
1387 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001388}
1389
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001390// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001391void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001392 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001393 // Clear the drawing state so that the logic inside of
1394 // handleTransactionLocked will fire. It will determine the delta between
1395 // mCurrentState and mDrawingState and re-apply all changes when we make the
1396 // transition.
1397 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001398 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001399 mDisplays.clear();
1400}
1401
Steven Thomas050b2c82017-03-06 11:45:16 -08001402void SurfaceFlinger::updateVrFlinger() {
1403 if (!mVrFlinger)
1404 return;
1405 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001406 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001407 return;
1408 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001409
David Sodman105b7dc2017-11-04 20:28:14 -07001410 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001411 ALOGE("Vr flinger is only supported for remote hardware composer"
1412 " service connections. Ignoring request to transition to vr"
1413 " flinger.");
1414 mVrFlingerRequestsDisplay = false;
1415 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001416 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001417
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001418 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001419
Steven Thomas0123ac62018-07-12 11:32:34 -07001420 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001421 LOG_ALWAYS_FATAL_IF(!display);
1422 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001423 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1424 // called below. Clear the reference now so we don't accidentally use it
1425 // later.
1426 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001427
Steven Thomasb02664d2017-07-26 18:48:28 -07001428 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001429 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001430 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001431
Steven Thomasb02664d2017-07-26 18:48:28 -07001432 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001433 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001434 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1435 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001436 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001437
David Sodman105b7dc2017-11-04 20:28:14 -07001438 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1439 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001440
1441 if (vrFlingerRequestsDisplay) {
1442 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001443 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001444
1445 mVisibleRegionsDirty = true;
1446 invalidateHwcGeometry();
1447
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001448 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001449 display = getDefaultDisplayDeviceLocked();
1450 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001451 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001452
Steven Thomasb02664d2017-07-26 18:48:28 -07001453 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001454 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001455 const nsecs_t period = activeConfig->getVsyncPeriod();
1456 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001457
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001458 // The present fences returned from vr_hwc are not an accurate
1459 // representation of vsync times.
Lloyd Pique41be5d22018-06-21 13:11:48 -07001460 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1461 !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001462
Steven Thomasb02664d2017-07-26 18:48:28 -07001463 // Use phase of 0 since phase is not known.
1464 // Use latency of 0, which will snap to the ideal latency.
1465 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001466
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001467 resyncToHardwareVsync(false);
1468
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001469 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001470 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001471}
1472
Mathias Agopian4fec8732012-06-29 14:12:52 -07001473void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001474 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001475 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001476 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001477 bool frameMissed = !mHadClientComposition &&
1478 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001479 (mPreviousPresentFence->getSignalTime() ==
1480 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001481 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001482 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001483 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001484 mTimeStats.incrementMissedFrames();
1485 if (mPropagateBackpressure) {
1486 signalLayerUpdate();
1487 break;
1488 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001489 }
Dan Stoza50182882016-07-08 12:02:20 -07001490
Steven Thomas050b2c82017-03-06 11:45:16 -08001491 // Now that we're going to make it to the handleMessageTransaction()
1492 // call below it's safe to call updateVrFlinger(), which will
1493 // potentially trigger a display handoff.
1494 updateVrFlinger();
1495
Dan Stoza6b9454d2014-11-07 16:00:59 -08001496 bool refreshNeeded = handleMessageTransaction();
1497 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001498 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001499 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001500 // Signal a refresh if a transaction modified the window state,
1501 // a new buffer was latched, or if HWC has requested a full
1502 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001503 signalRefresh();
1504 }
1505 break;
1506 }
1507 case MessageQueue::REFRESH: {
1508 handleMessageRefresh();
1509 break;
1510 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001511 }
1512}
1513
Dan Stoza6b9454d2014-11-07 16:00:59 -08001514bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001515 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001516 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001517 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001518 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001519 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001520 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001521}
1522
Mathias Agopian4fec8732012-06-29 14:12:52 -07001523void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001524 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001525
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001526 mRefreshPending = false;
1527
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001528 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001529 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001530 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001531 calculateWorkingSet();
David Sodman10a41ff2018-08-05 12:14:17 -07001532
David Sodmanfa9b2af2017-12-24 13:28:59 -08001533 for (const auto& [token, display] : mDisplays) {
David Sodman10a41ff2018-08-05 12:14:17 -07001534 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001535 beginFrame(display);
David Sodman10a41ff2018-08-05 12:14:17 -07001536 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
1537 setUpHWComposer(compositionInfo);
1538 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001539 prepareFrame(display);
1540 doDebugFlashRegions(display, repaintEverything);
1541 doComposition(display, repaintEverything);
1542 }
1543
Adrian Roos1e1a1282017-11-01 19:05:31 +01001544 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001545 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001546
1547 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001548 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001549
Dan Stozabfbffeb2016-07-21 14:49:33 -07001550 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001551 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001552 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001553 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001554 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001555
Jorim Jaggi90535212018-05-23 23:44:06 +02001556 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001557
David Sodman7e4ae112018-02-09 15:02:28 -08001558 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001559 for (const auto& [token, display] : mDisplays) {
1560 const auto displayId = display->getId();
David Sodman7e4ae112018-02-09 15:02:28 -08001561 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[displayId]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001562 compositionInfo.hwc.hwcLayer = nullptr;
1563 }
David Sodmanba340492018-08-05 21:51:33 -07001564 }
David Sodman7e4ae112018-02-09 15:02:28 -08001565
1566 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001567}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001568
David Sodmanfa9b2af2017-12-24 13:28:59 -08001569
1570bool SurfaceFlinger::handleMessageInvalidate() {
1571 ATRACE_CALL();
1572 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001573}
1574
David Sodman79bba0e2018-08-05 18:07:49 -07001575void SurfaceFlinger::calculateWorkingSet() {
1576 ATRACE_CALL();
1577 ALOGV(__FUNCTION__);
1578
David Sodman79bba0e2018-08-05 18:07:49 -07001579 // build the h/w work list
1580 if (CC_UNLIKELY(mGeometryInvalid)) {
1581 mGeometryInvalid = false;
1582 for (const auto& [token, display] : mDisplays) {
1583 const auto displayId = display->getId();
1584 if (displayId >= 0) {
1585 const Vector<sp<Layer>>& currentLayers(
1586 display->getVisibleLayersSortedByZ());
1587 for (size_t i = 0; i < currentLayers.size(); i++) {
1588 const auto& layer = currentLayers[i];
1589
1590 if (!layer->hasHwcLayer(displayId)) {
1591 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1592 layer->forceClientComposition(displayId);
1593 continue;
1594 }
1595 }
1596
1597 layer->setGeometry(display, i);
1598 if (mDebugDisableHWC || mDebugRegion) {
1599 layer->forceClientComposition(displayId);
1600 }
1601 }
1602 }
1603 }
1604 }
1605
1606 // Set the per-frame data
1607 for (const auto& [token, display] : mDisplays) {
1608 const auto displayId = display->getId();
1609 if (displayId < 0) {
1610 continue;
1611 }
1612
1613 if (mDrawingState.colorMatrixChanged) {
1614 display->setColorTransform(mDrawingState.colorMatrix);
1615 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1616 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1617 "display %d: %d", displayId, result);
1618 }
1619 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1620 if (layer->isHdrY410()) {
1621 layer->forceClientComposition(displayId);
1622 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1623 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1624 !display->hasHDR10Support()) {
1625 layer->forceClientComposition(displayId);
1626 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1627 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1628 !display->hasHLGSupport()) {
1629 layer->forceClientComposition(displayId);
1630 }
1631
1632 if (layer->getForceClientComposition(displayId)) {
1633 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1634 layer->setCompositionType(displayId, HWC2::Composition::Client);
1635 continue;
1636 }
1637
1638 layer->setPerFrameData(display);
1639 }
1640
Peiyong Lin13effd12018-07-24 17:01:47 -07001641 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001642 ColorMode colorMode;
1643 Dataspace dataSpace;
1644 RenderIntent renderIntent;
1645 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1646 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1647 }
1648 }
1649
1650 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001651
1652 for (const auto& [token, display] : mDisplays) {
David Sodman15fb96e2018-01-07 10:23:24 -08001653 const auto displayId = display->getId();
1654 getBE().mCompositionInfo[displayId].clear();
David Sodmanba340492018-08-05 21:51:33 -07001655 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1656 auto displayId = display->getId();
1657 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1658 if (!layer->setHwcLayer(displayId)) {
1659 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1660 }
David Sodman15fb96e2018-01-07 10:23:24 -08001661 layer->getBE().compositionInfo.hwc.displayId = displayId;
1662 getBE().mCompositionInfo[displayId].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001663 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1664 }
1665 }
David Sodman79bba0e2018-08-05 18:07:49 -07001666}
1667
David Sodmanfa9b2af2017-12-24 13:28:59 -08001668void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001669{
David Sodmanfb95bcc2017-12-22 15:45:30 -08001670 const auto displayId = display->getId();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001671 // is debugging enabled
1672 if (CC_LIKELY(!mDebugRegion))
1673 return;
1674
David Sodmanfa9b2af2017-12-24 13:28:59 -08001675 if (display->isPoweredOn()) {
1676 // transform the dirty region into this screen's coordinate space
1677 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1678 if (!dirtyRegion.isEmpty()) {
1679 // redraw the whole screen
1680 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001681
David Sodmanfa9b2af2017-12-24 13:28:59 -08001682 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001683 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001684 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001685
David Sodmanfa9b2af2017-12-24 13:28:59 -08001686 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001687 }
1688 }
1689
David Sodmanfa9b2af2017-12-24 13:28:59 -08001690 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001691
1692 if (mDebugRegion > 1) {
1693 usleep(mDebugRegion * 1000);
1694 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001695
David Sodmanfa9b2af2017-12-24 13:28:59 -08001696 if (display->isPoweredOn()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08001697 status_t result = display->prepareFrame(
1698 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001699 ALOGE_IF(result != NO_ERROR,
1700 "prepareFrame for display %d failed:"
1701 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001702 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001703 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001704}
1705
Adrian Roos1e1a1282017-11-01 19:05:31 +01001706void SurfaceFlinger::doTracing(const char* where) {
1707 ATRACE_CALL();
1708 ATRACE_NAME(where);
1709 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001710 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001711 }
1712}
1713
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001714void SurfaceFlinger::logLayerStats() {
1715 ATRACE_CALL();
1716 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001717 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001718 if (display->isPrimary()) {
1719 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001720 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001721 }
1722 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001723
1724 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001725 }
1726}
1727
David Sodman2b406362017-12-15 13:33:47 -08001728void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001729{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001730 ATRACE_CALL();
1731 ALOGV("preComposition");
1732
David Sodman2b406362017-12-15 13:33:47 -08001733 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1734
Mathias Agopiancd60f992012-08-16 16:28:27 -07001735 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001736 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001737 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001738 needExtraInvalidate = true;
1739 }
Robert Carr2047fae2016-11-28 14:09:09 -08001740 });
1741
Mathias Agopiancd60f992012-08-16 16:28:27 -07001742 if (needExtraInvalidate) {
1743 signalLayerUpdate();
1744 }
1745}
1746
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001747void SurfaceFlinger::updateCompositorTiming(
1748 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1749 std::shared_ptr<FenceTime>& presentFenceTime) {
1750 // Update queue of past composite+present times and determine the
1751 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001752 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001753 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001754 while (!getBE().mCompositePresentTimes.empty()) {
1755 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001756 // Cached values should have been updated before calling this method,
1757 // which helps avoid duplicate syscalls.
1758 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1759 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1760 break;
1761 }
1762 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001763 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001764 }
1765
1766 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001767 while (getBE().mCompositePresentTimes.size() > 16) {
1768 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001769 }
1770
Brian Andersond0010582017-03-07 13:20:31 -08001771 setCompositorTimingSnapped(
1772 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1773}
1774
1775void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1776 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001777 // Integer division and modulo round toward 0 not -inf, so we need to
1778 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001779 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001780 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1781 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1782
Brian Andersond0010582017-03-07 13:20:31 -08001783 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1784 if (idealLatency <= 0) {
1785 idealLatency = vsyncInterval;
1786 }
1787
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001788 // Snap the latency to a value that removes scheduling jitter from the
1789 // composition and present times, which often have >1ms of jitter.
1790 // Reducing jitter is important if an app attempts to extrapolate
1791 // something (such as user input) to an accurate diasplay time.
1792 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1793 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001794 nsecs_t bias = vsyncInterval / 2;
1795 int64_t extraVsyncs =
1796 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1797 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1798 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001799
David Sodman99974d22017-11-28 12:04:33 -08001800 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1801 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1802 getBE().mCompositorTiming.interval = vsyncInterval;
1803 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001804}
1805
David Sodman2b406362017-12-15 13:33:47 -08001806void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001807{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001808 ATRACE_CALL();
1809 ALOGV("postComposition");
1810
Brian Anderson3546a3f2016-07-14 11:51:14 -07001811 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001812 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001813 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001814 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001815 }
1816
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001817 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001818 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001819
David Sodman73beded2017-11-15 11:56:06 -08001820 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001821 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001822 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001823 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001824 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001825 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001826 } else {
1827 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1828 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001829
David Sodman73beded2017-11-15 11:56:06 -08001830 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001831 mPreviousPresentFence =
1832 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1833 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001834 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001835
Lloyd Pique41be5d22018-06-21 13:11:48 -07001836 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1837 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001838
David Sodman2b406362017-12-15 13:33:47 -08001839 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001840 // when we started doing work for this frame, but that should be okay
1841 // since updateCompositorTiming has snapping logic.
1842 updateCompositorTiming(
David Sodman2b406362017-12-15 13:33:47 -08001843 vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001844 CompositorTiming compositorTiming;
1845 {
David Sodman99974d22017-11-28 12:04:33 -08001846 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1847 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001848 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001849
Robert Carr2047fae2016-11-28 14:09:09 -08001850 mDrawingState.traverseInZOrder([&](Layer* layer) {
1851 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001852 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001853 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001854 recordBufferingStats(layer->getName().string(),
1855 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001856 }
Robert Carr2047fae2016-11-28 14:09:09 -08001857 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001858
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001859 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001860 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001861 enableHardwareVsync();
1862 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001863 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001864 }
1865 }
1866
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001867 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001868 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001869 enableHardwareVsync();
1870 }
1871 }
1872
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001873 if (mAnimCompositionPending) {
1874 mAnimCompositionPending = false;
1875
Brian Anderson4e606e32017-03-16 15:34:57 -07001876 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001877 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001878 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001879 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001880 // The HWC doesn't support present fences, so use the refresh
1881 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001882 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001883 mAnimFrameTracker.setActualPresentTime(presentTime);
1884 }
1885 mAnimFrameTracker.advanceFrame();
1886 }
Dan Stozab90cf072015-03-05 11:05:59 -08001887
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001888 mTimeStats.incrementTotalFrames();
1889 if (mHadClientComposition) {
1890 mTimeStats.incrementClientCompositionFrames();
1891 }
1892
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001893 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001894 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001895 return;
1896 }
1897
1898 nsecs_t currentTime = systemTime();
1899 if (mHasPoweredOff) {
1900 mHasPoweredOff = false;
1901 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001902 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001903 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001904 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1905 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001906 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001907 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001908 }
David Sodman4a36e932017-11-07 14:29:47 -08001909 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001910 }
David Sodman4a36e932017-11-07 14:29:47 -08001911 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001912
1913 {
1914 std::lock_guard lock(mTexturePoolMutex);
1915 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1916 if (refillCount > 0) {
1917 const size_t offset = mTexturePool.size();
1918 mTexturePool.resize(mTexturePoolSize);
1919 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1920 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1921 }
1922 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001923}
1924
1925void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001926 ATRACE_CALL();
1927 ALOGV("rebuildLayerStacks");
1928
Mathias Agopiancd60f992012-08-16 16:28:27 -07001929 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001930 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001931 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001932 mVisibleRegionsDirty = false;
1933 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001934
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001935 for (const auto& pair : mDisplays) {
1936 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001937 Region opaqueRegion;
1938 Region dirtyRegion;
1939 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001940 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001941 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001942 const Rect bounds = display->getBounds();
1943 if (display->isPoweredOn()) {
1944 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001945
Jeff Sharkey76488112017-02-27 14:15:18 -07001946 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001947 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001948 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001949 Region drawRegion(tr.transform(
1950 layer->visibleNonTransparentRegion));
1951 drawRegion.andSelf(bounds);
1952 if (!drawRegion.isEmpty()) {
1953 layersSortedByZ.add(layer);
1954 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001955 // Clear out the HWC layer if this layer was
1956 // previously visible, but no longer is
1957 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001958 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001959 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001960 // WM changes display->layerStack upon sleep/awake.
1961 // Here we make sure we delete the HWC layers even if
1962 // WM changed their layer stack.
1963 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001964 }
1965
1966 // If a layer is not going to get a release fence because
1967 // it is invisible, but it is also going to release its
1968 // old buffer, add it to the list of layers needing
1969 // fences.
1970 if (hwcLayerDestroyed) {
1971 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1972 mLayersWithQueuedFrames.cend(), layer);
1973 if (found != mLayersWithQueuedFrames.cend()) {
1974 layersNeedingFences.add(layer);
1975 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001976 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001977 });
1978 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001979 display->setVisibleLayersSortedByZ(layersSortedByZ);
1980 display->setLayersNeedingFences(layersNeedingFences);
1981 display->undefinedRegion.set(bounds);
1982 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1983 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001984 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001985 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001986}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001987
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001988// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001989// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001990// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001991// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001992// The returned HDR data space is one of
1993// - Dataspace::UNKNOWN
1994// - Dataspace::BT2020_HLG
1995// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001996Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1997 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001998 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001999 *outHdrDataSpace = Dataspace::UNKNOWN;
2000
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002001 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002002 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002003 case Dataspace::V0_SCRGB:
2004 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002005 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002006 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002007 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002008 case Dataspace::BT2020_PQ:
2009 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002010 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002011 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002012 case Dataspace::BT2020_HLG:
2013 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002014 // When there's mixed PQ content and HLG content, we set the HDR
2015 // data space to be BT2020_PQ and convert HLG to PQ.
2016 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2017 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002018 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002019 break;
2020 default:
2021 break;
2022 }
Romain Guy54f154a2017-10-24 21:40:32 +01002023 }
2024
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002025 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002026}
2027
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002028// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002029void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2030 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002031 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2032 *outMode = ColorMode::NATIVE;
2033 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002034 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002035 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002036 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002037
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002038 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002039 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002040
Peiyong Lindfde5112018-06-05 10:58:41 -07002041 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002042 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002043 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002044 if (isHdr) {
2045 bestDataSpace = hdrDataSpace;
2046 }
2047
Chia-I Wu0d711262018-05-21 15:19:35 -07002048 RenderIntent intent;
2049 switch (mDisplayColorSetting) {
2050 case DisplayColorSetting::MANAGED:
2051 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002052 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002053 break;
2054 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002055 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002056 break;
2057 default: // vendor display color setting
2058 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2059 break;
2060 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002061
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002062 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002063}
2064
David Sodman10a41ff2018-08-05 12:14:17 -07002065void SurfaceFlinger::configureSidebandComposition(const CompositionInfo& compositionInfo) const
2066{
2067 HWC2::Error error;
2068 LOG_ALWAYS_FATAL_IF(compositionInfo.hwc.sidebandStream == nullptr,
2069 "CompositionType is sideband, but sideband stream is nullptr");
2070 error = (compositionInfo.hwc.hwcLayer)
2071 ->setSidebandStream(compositionInfo.hwc.sidebandStream->handle());
2072 if (error != HWC2::Error::None) {
2073 ALOGE("[SF] Failed to set sideband stream %p: %s (%d)",
2074 compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
2075 static_cast<int32_t>(error));
2076 }
2077}
2078
2079void SurfaceFlinger::configureHwcCommonData(const CompositionInfo& compositionInfo) const
2080{
2081 HWC2::Error error;
2082
2083 if (!compositionInfo.hwc.skipGeometry) {
2084 error = (compositionInfo.hwc.hwcLayer)->setBlendMode(compositionInfo.hwc.blendMode);
2085 ALOGE_IF(error != HWC2::Error::None,
2086 "[SF] Failed to set blend mode %s:"
2087 " %s (%d)",
2088 to_string(compositionInfo.hwc.blendMode).c_str(), to_string(error).c_str(),
2089 static_cast<int32_t>(error));
2090
2091 error = (compositionInfo.hwc.hwcLayer)->setDisplayFrame(compositionInfo.hwc.displayFrame);
2092 ALOGE_IF(error != HWC2::Error::None,
2093 "[SF] Failed to set the display frame [%d, %d, %d, %d] %s (%d)",
2094 compositionInfo.hwc.displayFrame.left,
2095 compositionInfo.hwc.displayFrame.right,
2096 compositionInfo.hwc.displayFrame.top,
2097 compositionInfo.hwc.displayFrame.bottom,
2098 to_string(error).c_str(), static_cast<int32_t>(error));
2099
2100 error = (compositionInfo.hwc.hwcLayer)->setSourceCrop(compositionInfo.hwc.sourceCrop);
2101 ALOGE_IF(error != HWC2::Error::None,
2102 "[SF] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: %s (%d)",
2103 compositionInfo.hwc.sourceCrop.left,
2104 compositionInfo.hwc.sourceCrop.right,
2105 compositionInfo.hwc.sourceCrop.top,
2106 compositionInfo.hwc.sourceCrop.bottom,
2107 to_string(error).c_str(), static_cast<int32_t>(error));
2108
2109 error = (compositionInfo.hwc.hwcLayer)->setPlaneAlpha(compositionInfo.hwc.alpha);
2110 ALOGE_IF(error != HWC2::Error::None,
2111 "[SF] Failed to set plane alpha %.3f: "
2112 "%s (%d)",
2113 compositionInfo.hwc.alpha,
2114 to_string(error).c_str(), static_cast<int32_t>(error));
2115
2116
2117 error = (compositionInfo.hwc.hwcLayer)->setZOrder(compositionInfo.hwc.z);
2118 ALOGE_IF(error != HWC2::Error::None,
2119 "[SF] Failed to set Z %u: %s (%d)",
2120 compositionInfo.hwc.z,
2121 to_string(error).c_str(), static_cast<int32_t>(error));
2122
2123 error = (compositionInfo.hwc.hwcLayer)
2124 ->setInfo(compositionInfo.hwc.type, compositionInfo.hwc.appId);
2125 ALOGE_IF(error != HWC2::Error::None,
2126 "[SF] Failed to set info (%d)",
2127 static_cast<int32_t>(error));
2128
2129 error = (compositionInfo.hwc.hwcLayer)->setTransform(compositionInfo.hwc.transform);
2130 ALOGE_IF(error != HWC2::Error::None,
2131 "[SF] Failed to set transform %s: "
2132 "%s (%d)",
2133 to_string(compositionInfo.hwc.transform).c_str(), to_string(error).c_str(),
2134 static_cast<int32_t>(error));
2135 }
2136
2137 error = (compositionInfo.hwc.hwcLayer)->setCompositionType(compositionInfo.compositionType);
2138 ALOGE_IF(error != HWC2::Error::None,
2139 "[SF] Failed to set composition type: %s (%d)",
2140 to_string(error).c_str(), static_cast<int32_t>(error));
2141
2142 error = (compositionInfo.hwc.hwcLayer)->setDataspace(compositionInfo.hwc.dataspace);
2143 ALOGE_IF(error != HWC2::Error::None,
2144 "[SF] Failed to set dataspace: %s (%d)",
2145 to_string(error).c_str(), static_cast<int32_t>(error));
2146
2147 error = (compositionInfo.hwc.hwcLayer)->setPerFrameMetadata(
2148 compositionInfo.hwc.supportedPerFrameMetadata, compositionInfo.hwc.hdrMetadata);
2149 ALOGE_IF(error != HWC2::Error::None && error != HWC2::Error::Unsupported,
2150 "[SF] Failed to set hdrMetadata: %s (%d)",
2151 to_string(error).c_str(), static_cast<int32_t>(error));
2152
2153 if (compositionInfo.compositionType == HWC2::Composition::SolidColor) {
2154 error = (compositionInfo.hwc.hwcLayer)->setColor(compositionInfo.hwc.color);
2155 ALOGE_IF(error != HWC2::Error::None,
2156 "[SF] Failed to set color: %s (%d)",
2157 to_string(error).c_str(), static_cast<int32_t>(error));
2158 }
2159
2160 error = (compositionInfo.hwc.hwcLayer)->setVisibleRegion(compositionInfo.hwc.visibleRegion);
2161 ALOGE_IF(error != HWC2::Error::None,
2162 "[SF] Failed to set visible region: %s (%d)",
2163 to_string(error).c_str(), static_cast<int32_t>(error));
2164
2165 error = (compositionInfo.hwc.hwcLayer)->setSurfaceDamage(compositionInfo.hwc.surfaceDamage);
2166 ALOGE_IF(error != HWC2::Error::None,
2167 "[SF] Failed to set surface damage: %s (%d)",
2168 to_string(error).c_str(), static_cast<int32_t>(error));
2169}
2170
2171void SurfaceFlinger::configureDeviceComposition(const CompositionInfo& compositionInfo) const
2172{
2173 HWC2::Error error;
2174
2175 if (compositionInfo.hwc.fence) {
2176 error = (compositionInfo.hwc.hwcLayer)->setBuffer(compositionInfo.mBufferSlot,
2177 compositionInfo.mBuffer, compositionInfo.hwc.fence);
2178 ALOGE_IF(error != HWC2::Error::None,
2179 "[SF] Failed to set buffer: %s (%d)",
2180 to_string(error).c_str(), static_cast<int32_t>(error));
2181 }
2182}
2183
David Sodmanfa9b2af2017-12-24 13:28:59 -08002184void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002185{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002186 bool dirty = !display->getDirtyRegion(false).isEmpty();
2187 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2188 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002189
David Sodmanfa9b2af2017-12-24 13:28:59 -08002190 // If nothing has changed (!dirty), don't recompose.
2191 // If something changed, but we don't currently have any visible layers,
2192 // and didn't when we last did a composition, then skip it this time.
2193 // The second rule does two things:
2194 // - When all layers are removed from a display, we'll emit one black
2195 // frame, then nothing more until we get new layers.
2196 // - When a display is created with a private layer stack, we won't
2197 // emit any black frames until a layer is added to the layer stack.
2198 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002199
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002200 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2201 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002202 mustRecompose ? "doing" : "skipping",
2203 dirty ? "+" : "-",
2204 empty ? "+" : "-",
2205 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002206
David Sodmanfa9b2af2017-12-24 13:28:59 -08002207 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002208
David Sodmanfa9b2af2017-12-24 13:28:59 -08002209 if (mustRecompose) {
2210 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002211 }
2212}
2213
David Sodmanfa9b2af2017-12-24 13:28:59 -08002214void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002215{
David Sodmanfb95bcc2017-12-22 15:45:30 -08002216 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002217 if (!display->isPoweredOn()) {
2218 return;
David Sodman2b406362017-12-15 13:33:47 -08002219 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002220
David Sodmanfb95bcc2017-12-22 15:45:30 -08002221 status_t result = display->prepareFrame(
2222 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08002223 ALOGE_IF(result != NO_ERROR,
2224 "prepareFrame for display %d failed:"
2225 " %d (%s)",
2226 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002227}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002228
David Sodman10a41ff2018-08-05 12:14:17 -07002229void SurfaceFlinger::setUpHWComposer(const CompositionInfo& compositionInfo) {
2230 ATRACE_CALL();
2231 ALOGV("setUpHWComposer");
2232
2233 switch (compositionInfo.compositionType)
2234 {
2235 case HWC2::Composition::Invalid:
David Sodmana6d42332018-08-29 14:07:04 -07002236 break;
2237
David Sodman10a41ff2018-08-05 12:14:17 -07002238 case HWC2::Composition::Client:
David Sodmana6d42332018-08-29 14:07:04 -07002239 if (compositionInfo.hwc.hwcLayer) {
2240 auto error = (compositionInfo.hwc.hwcLayer)->
2241 setCompositionType(compositionInfo.compositionType);
2242 ALOGE_IF(error != HWC2::Error::None,
2243 "[SF] Failed to set composition type: %s (%d)",
2244 to_string(error).c_str(), static_cast<int32_t>(error));
2245 }
David Sodman10a41ff2018-08-05 12:14:17 -07002246 break;
2247
2248 case HWC2::Composition::Sideband:
2249 configureHwcCommonData(compositionInfo);
2250 configureSidebandComposition(compositionInfo);
2251 break;
2252
2253 case HWC2::Composition::SolidColor:
2254 configureHwcCommonData(compositionInfo);
2255 break;
2256
2257 case HWC2::Composition::Device:
2258 case HWC2::Composition::Cursor:
2259 configureHwcCommonData(compositionInfo);
2260 configureDeviceComposition(compositionInfo);
2261 break;
2262 }
2263}
2264
David Sodmanfa9b2af2017-12-24 13:28:59 -08002265void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002266 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002267 ALOGV("doComposition");
2268
David Sodmanfa9b2af2017-12-24 13:28:59 -08002269 if (display->isPoweredOn()) {
2270 // transform the dirty region into this screen's coordinate space
2271 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002272
David Sodmanfa9b2af2017-12-24 13:28:59 -08002273 // repaint the framebuffer (if needed)
2274 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002275
David Sodmanfa9b2af2017-12-24 13:28:59 -08002276 display->dirtyRegion.clear();
2277 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002278 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002279 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002280}
2281
David Sodmanfa9b2af2017-12-24 13:28:59 -08002282void SurfaceFlinger::postFrame()
2283{
2284 // |mStateLock| not needed as we are on the main thread
2285 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2286 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2287 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2288 logFrameStats();
2289 }
2290 }
2291}
2292
2293void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002294{
Mathias Agopian841cde52012-03-01 15:44:37 -08002295 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002296 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002297
David Sodmanfa9b2af2017-12-24 13:28:59 -08002298 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002299
David Sodmanfa9b2af2017-12-24 13:28:59 -08002300 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002301 const auto displayId = display->getId();
2302 if (displayId >= 0) {
2303 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002304 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002305 display->onSwapBuffersCompleted();
2306 display->makeCurrent();
David Sodman10a41ff2018-08-05 12:14:17 -07002307 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002308 sp<Fence> releaseFence = Fence::NO_FENCE;
Chia-I Wu7b549592017-11-15 09:14:57 -08002309 // The layer buffer from the previous frame (if any) is released
2310 // by HWC only when the release fence from this frame (if any) is
2311 // signaled. Always get the release fence from HWC first.
David Sodman10a41ff2018-08-05 12:14:17 -07002312 auto hwcLayer = compositionInfo.hwc.hwcLayer;
2313 if ((displayId >= 0) && hwcLayer) {
2314 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer.get());
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002315 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002316
2317 // If the layer was client composited in the previous frame, we
2318 // need to merge with the previous client target acquire fence.
2319 // Since we do not track that, always merge with the current
2320 // client target acquire fence when it is available, even though
2321 // this is suboptimal.
David Sodman10a41ff2018-08-05 12:14:17 -07002322 if (compositionInfo.compositionType == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002323 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002324 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002325 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002326
David Sodman10a41ff2018-08-05 12:14:17 -07002327 if (compositionInfo.layer) {
2328 compositionInfo.layer->onLayerDisplayed(releaseFence);
2329 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002330 }
Chia-I Wu83806892017-11-16 10:50:20 -08002331
2332 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002333 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002334 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002335 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002336 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002337 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002338 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002339 }
2340 }
2341
Dominik Laskowski7e045462018-05-30 13:02:02 -07002342 if (displayId >= 0) {
2343 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002344 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002345 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002346}
2347
Mathias Agopian87baae12012-07-31 12:38:26 -07002348void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002349{
Mathias Agopian841cde52012-03-01 15:44:37 -08002350 ATRACE_CALL();
2351
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002352 // here we keep a copy of the drawing state (that is the state that's
2353 // going to be overwritten by handleTransactionLocked()) outside of
2354 // mStateLock so that the side-effects of the State assignment
2355 // don't happen with mStateLock held (which can cause deadlocks).
2356 State drawingState(mDrawingState);
2357
Mathias Agopianca4d3602011-05-19 15:38:14 -07002358 Mutex::Autolock _l(mStateLock);
2359 const nsecs_t now = systemTime();
2360 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002361
Mathias Agopianca4d3602011-05-19 15:38:14 -07002362 // Here we're guaranteed that some transaction flags are set
2363 // so we can call handleTransactionLocked() unconditionally.
2364 // We call getTransactionFlags(), which will also clear the flags,
2365 // with mStateLock held to guarantee that mCurrentState won't change
2366 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002367
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002368 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002369 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002370 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002371
Mathias Agopianca4d3602011-05-19 15:38:14 -07002372 mLastTransactionTime = systemTime() - now;
2373 mDebugInTransaction = 0;
2374 invalidateHwcGeometry();
2375 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002376}
2377
Dominik Laskowski7e045462018-05-30 13:02:02 -07002378DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002379 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002380 // Figure out whether the event is for the primary display or an
2381 // external display by matching the Hwc display id against one for a
2382 // connected display. If we did not find a match, we then check what
2383 // displays are not already connected to determine the type. If we don't
2384 // have a connected primary display, we assume the new display is meant to
2385 // be the primary display, and then if we don't have an external display,
2386 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002387 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2388 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002389 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002390 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002391 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002392 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002393 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002394 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002395 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002396 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002397 return DisplayDevice::DISPLAY_EXTERNAL;
2398 }
2399
2400 return DisplayDevice::DISPLAY_ID_INVALID;
2401}
2402
Lloyd Piqueba04e622017-12-14 17:11:26 -08002403void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2404 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002405 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002406 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002407 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002408 continue;
2409 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002410
2411 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2412 ALOGE("External displays are not supported by the vr hardware composer.");
2413 continue;
2414 }
2415
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002416 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002417 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002418 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002419 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002420 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002421
2422 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002423 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002424 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002425 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002426 DisplayDeviceState info;
2427 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002428 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2429 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002430 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002431 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002432 mInterceptor->saveDisplayCreation(info);
2433 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002434 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002435 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002436
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002437 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002438 if (idx >= 0) {
2439 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002440 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002441 mCurrentState.displays.removeItemsAt(idx);
2442 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002443 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002444 }
2445
2446 processDisplayChangesLocked();
2447 }
2448
2449 mPendingHotplugEvents.clear();
2450}
2451
Lloyd Pique99d3da52018-01-22 17:48:03 -08002452sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002453 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002454 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002455 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002456 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002457 HdrCapabilities hdrCapabilities;
2458 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002459
Peiyong Lin13effd12018-07-24 17:01:47 -07002460 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002461 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002462 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002463 if (isWideColorMode(colorMode)) {
2464 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002465 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002466
Dominik Laskowski7e045462018-05-30 13:02:02 -07002467 std::vector<RenderIntent> renderIntents =
2468 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002469 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002470 }
tangrobin6753a022018-08-10 10:58:54 +08002471 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002472
tangrobin6753a022018-08-10 10:58:54 +08002473 if (displayId >= 0) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002474 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2475 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2476 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002477
2478 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2479 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2480
2481 /*
2482 * Create our display's surface
2483 */
Peiyong Lin833074a2018-08-28 11:53:54 -07002484 std::unique_ptr<renderengine::Surface> renderSurface = getRenderEngine().createSurface();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002485 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002486 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002487 renderSurface->setNativeWindow(nativeWindow.get());
Alec Mouri05483a02018-09-10 21:03:42 +00002488 const int displayWidth = renderSurface->getWidth();
2489 const int displayHeight = renderSurface->getHeight();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002490
2491 // Make sure that composition can never be stalled by a virtual display
2492 // consumer that isn't processing buffers fast enough. We have to do this
2493 // in two places:
2494 // * Here, in case the display is composed entirely by HWC.
2495 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2496 // window's swap interval in eglMakeCurrent, so they'll override the
2497 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002498 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002499 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2500 }
2501
Chia-I Wua02871c2018-08-27 14:38:23 -07002502 const int displayInstallOrientation = state.type == DisplayDevice::DISPLAY_PRIMARY ?
2503 primaryDisplayOrientation : DisplayState::eOrientationDefault;
2504
Lloyd Pique99d3da52018-01-22 17:48:03 -08002505 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002506 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002507
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002508 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002509 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2510 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
Chia-I Wua02871c2018-08-27 14:38:23 -07002511 displayHeight, displayInstallOrientation, hasWideColorGamut,
2512 hdrCapabilities, supportedPerFrameMetadata, hwcColorModes,
2513 initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002514
2515 if (maxFrameBufferAcquiredBuffers >= 3) {
2516 nativeWindowSurface->preallocateBuffers();
2517 }
2518
2519 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002520 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2521 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002522 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002523 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002524 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002525 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002526 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002527 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002528 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002529 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002530 display->setLayerStack(state.layerStack);
2531 display->setProjection(state.orientation, state.viewport, state.frame);
2532 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002533
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002534 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002535}
2536
Lloyd Pique347200f2017-12-14 17:00:15 -08002537void SurfaceFlinger::processDisplayChangesLocked() {
2538 // here we take advantage of Vector's copy-on-write semantics to
2539 // improve performance by skipping the transaction entirely when
2540 // know that the lists are identical
2541 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2542 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2543 if (!curr.isIdenticalTo(draw)) {
2544 mVisibleRegionsDirty = true;
2545 const size_t cc = curr.size();
2546 size_t dc = draw.size();
2547
2548 // find the displays that were removed
2549 // (ie: in drawing state but not in current state)
2550 // also handle displays that changed
2551 // (ie: displays that are in both lists)
2552 for (size_t i = 0; i < dc;) {
2553 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2554 if (j < 0) {
2555 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002556 // Call makeCurrent() on the primary display so we can
2557 // be sure that nothing associated with this display
2558 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002559 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2560 defaultDisplay->makeCurrent();
2561 }
2562 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2563 display->disconnect(getHwComposer());
2564 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002565 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002566 if (mUseScheduler) {
2567 mScheduler->hotplugReceived(mAppConnectionHandle,
2568 EventThread::DisplayType::Primary, false);
2569 } else {
2570 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2571 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002572 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002573 if (mUseScheduler) {
2574 mScheduler->hotplugReceived(mAppConnectionHandle,
2575 EventThread::DisplayType::External, false);
2576 } else {
2577 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2578 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002579 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002580 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002581 } else {
2582 // this display is in both lists. see if something changed.
2583 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002584 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002585 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2586 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2587 if (state_binder != draw_binder) {
2588 // changing the surface is like destroying and
2589 // recreating the DisplayDevice, so we just remove it
2590 // from the drawing state, so that it get re-added
2591 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002592 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2593 display->disconnect(getHwComposer());
2594 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002595 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002596 mDrawingState.displays.removeItemsAt(i);
2597 dc--;
2598 // at this point we must loop to the next item
2599 continue;
2600 }
2601
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002602 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002603 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002604 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002605 }
2606 if ((state.orientation != draw[i].orientation) ||
2607 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002608 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002609 }
2610 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002611 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002612 }
2613 }
2614 }
2615 ++i;
2616 }
2617
2618 // find displays that were added
2619 // (ie: in current state but not in drawing state)
2620 for (size_t i = 0; i < cc; i++) {
2621 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2622 const DisplayDeviceState& state(curr[i]);
2623
2624 sp<DisplaySurface> dispSurface;
2625 sp<IGraphicBufferProducer> producer;
2626 sp<IGraphicBufferProducer> bqProducer;
2627 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002628 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002629
Dominik Laskowski7e045462018-05-30 13:02:02 -07002630 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002631 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002632 // Virtual displays without a surface are dormant:
2633 // they have external state (layer stack, projection,
2634 // etc.) but no internal state (i.e. a DisplayDevice).
2635 if (state.surface != nullptr) {
2636 // Allow VR composer to use virtual displays.
2637 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2638 int width = 0;
2639 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2640 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2641 int height = 0;
2642 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2643 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2644 int intFormat = 0;
2645 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2646 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002647 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002648
Dominik Laskowski7e045462018-05-30 13:02:02 -07002649 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2650 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002651 }
2652
2653 // TODO: Plumb requested format back up to consumer
2654
2655 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002656 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002657 bqProducer, bqConsumer,
2658 state.displayName);
2659
2660 dispSurface = vds;
2661 producer = vds;
2662 }
2663 } else {
2664 ALOGE_IF(state.surface != nullptr,
2665 "adding a supported display, but rendering "
2666 "surface is provided (%p), ignoring it",
2667 state.surface.get());
2668
Dominik Laskowski7e045462018-05-30 13:02:02 -07002669 displayId = state.type;
2670 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002671 producer = bqProducer;
2672 }
2673
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002674 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002675 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002676 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002677 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002678 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002679 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002680 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002681 if (mUseScheduler) {
2682 mScheduler->hotplugReceived(mAppConnectionHandle,
2683 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002684 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002685 } else {
2686 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2687 true);
2688 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002689 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002690 if (mUseScheduler) {
2691 mScheduler->hotplugReceived(mAppConnectionHandle,
2692 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002693 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002694 } else {
2695 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2696 true);
2697 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002698 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002699 }
2700 }
2701 }
2702 }
2703 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002704
2705 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002706}
2707
Mathias Agopian87baae12012-07-31 12:38:26 -07002708void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002709{
Dan Stoza7dde5992015-05-22 09:51:44 -07002710 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002711 mCurrentState.traverseInZOrder([](Layer* layer) {
2712 layer->notifyAvailableFrames();
2713 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002714
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002715 /*
2716 * Traversal of the children
2717 * (perform the transaction for each of them if needed)
2718 */
2719
Mathias Agopian3559b072012-08-15 13:46:03 -07002720 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002721 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002722 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002723 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002724
2725 const uint32_t flags = layer->doTransaction(0);
2726 if (flags & Layer::eVisibleRegion)
2727 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002728 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002729 }
2730
2731 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002732 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002733 */
2734
Mathias Agopiane57f2922012-08-09 16:29:12 -07002735 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002736 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002737 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002738 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002739
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002740 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002741 // The transform hint might have changed for some layers
2742 // (either because a display has changed, or because a layer
2743 // as changed).
2744 //
2745 // Walk through all the layers in currentLayers,
2746 // and update their transform hint.
2747 //
2748 // If a layer is visible only on a single display, then that
2749 // display is used to calculate the hint, otherwise we use the
2750 // default display.
2751 //
2752 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2753 // the hint is set before we acquire a buffer from the surface texture.
2754 //
2755 // NOTE: layer transactions have taken place already, so we use their
2756 // drawing state. However, SurfaceFlinger's own transaction has not
2757 // happened yet, so we must use the current state layer list
2758 // (soon to become the drawing state list).
2759 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002760 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002761 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002762 bool first = true;
2763 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002764 // NOTE: we rely on the fact that layers are sorted by
2765 // layerStack first (so we don't have to traverse the list
2766 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002767 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002768 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002769 currentlayerStack = layerStack;
2770 // figure out if this layerstack is mirrored
2771 // (more than one display) if so, pick the default display,
2772 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002773 hintDisplay = nullptr;
2774 for (const auto& [token, display] : mDisplays) {
2775 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2776 if (hintDisplay) {
2777 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002778 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002779 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002780 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002781 }
2782 }
2783 }
2784 }
Chet Haase91d25932013-04-11 15:24:55 -07002785
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002786 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002787 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2788 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002789
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002790 // could be null when this layer is using a layerStack
2791 // that is not visible on any display. Also can occur at
2792 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002793 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002794 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002795
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002796 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002797 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002798 if (hintDisplay) {
2799 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002800 }
Robert Carr2047fae2016-11-28 14:09:09 -08002801
2802 first = false;
2803 });
Mathias Agopian84300952012-11-21 16:02:13 -08002804 }
2805
2806
Mathias Agopian3559b072012-08-15 13:46:03 -07002807 /*
2808 * Perform our own transaction if needed
2809 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002810
2811 if (mLayersAdded) {
2812 mLayersAdded = false;
2813 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002814 mVisibleRegionsDirty = true;
2815 }
2816
2817 // some layers might have been removed, so
2818 // we need to update the regions they're exposing.
2819 if (mLayersRemoved) {
2820 mLayersRemoved = false;
2821 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002822 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002823 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002824 // this layer is not visible anymore
2825 // TODO: we could traverse the tree from front to back and
2826 // compute the actual visible region
2827 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002828 Region visibleReg;
2829 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002830 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002831 }
Robert Carr2047fae2016-11-28 14:09:09 -08002832 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002833 }
2834
2835 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002836
2837 updateCursorAsync();
2838}
2839
2840void SurfaceFlinger::updateCursorAsync()
2841{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002842 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002843 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002844 continue;
2845 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002846
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002847 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2848 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002849 }
2850 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002851}
2852
2853void SurfaceFlinger::commitTransaction()
2854{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002855 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002856 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002857 for (const auto& l : mLayersPendingRemoval) {
2858 recordBufferingStats(l->getName().string(),
2859 l->getOccupancyHistory(true));
2860 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002861 }
2862 mLayersPendingRemoval.clear();
2863 }
2864
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002865 // If this transaction is part of a window animation then the next frame
2866 // we composite should be considered an animation as well.
2867 mAnimCompositionPending = mAnimTransactionPending;
2868
Mathias Agopian4fec8732012-06-29 14:12:52 -07002869 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002870 // clear the "changed" flags in current state
2871 mCurrentState.colorMatrixChanged = false;
2872
Robert Carr1f0a16a2016-10-24 16:27:39 -07002873 mDrawingState.traverseInZOrder([](Layer* layer) {
2874 layer->commitChildList();
2875 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002876 mTransactionPending = false;
2877 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002878 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002879}
2880
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002881void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2882 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002883 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002884 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002885
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002886 Region aboveOpaqueLayers;
2887 Region aboveCoveredLayers;
2888 Region dirty;
2889
Mathias Agopian87baae12012-07-31 12:38:26 -07002890 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002891
Robert Carr2047fae2016-11-28 14:09:09 -08002892 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002893 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002894 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002895
Jesse Hall01e29052013-02-19 16:13:35 -08002896 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002897 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002898 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002899 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002900
Mathias Agopianab028732010-03-16 16:41:46 -07002901 /*
2902 * opaqueRegion: area of a surface that is fully opaque.
2903 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002904 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002905
2906 /*
2907 * visibleRegion: area of a surface that is visible on screen
2908 * and not fully transparent. This is essentially the layer's
2909 * footprint minus the opaque regions above it.
2910 * Areas covered by a translucent surface are considered visible.
2911 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002912 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002913
2914 /*
2915 * coveredRegion: area of a surface that is covered by all
2916 * visible regions above it (which includes the translucent areas).
2917 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002918 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002919
Jesse Halla8026d22012-09-25 13:25:04 -07002920 /*
2921 * transparentRegion: area of a surface that is hinted to be completely
2922 * transparent. This is only used to tell when the layer has no visible
2923 * non-transparent regions and can be removed from the layer list. It
2924 * does not affect the visibleRegion of this layer or any layers
2925 * beneath it. The hint may not be correct if apps don't respect the
2926 * SurfaceView restrictions (which, sadly, some don't).
2927 */
2928 Region transparentRegion;
2929
Mathias Agopianab028732010-03-16 16:41:46 -07002930
2931 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002932 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002933 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002934 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002935 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002936 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002937 if (!visibleRegion.isEmpty()) {
2938 // Remove the transparent area from the visible region
2939 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002940 if (tr.preserveRects()) {
2941 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002942 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002943 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002944 // transformation too complex, can't do the
2945 // transparent region optimization.
2946 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002947 }
Mathias Agopianab028732010-03-16 16:41:46 -07002948 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002949
Mathias Agopianab028732010-03-16 16:41:46 -07002950 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002951 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002952 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002953 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002954 // the opaque region is the layer's footprint
2955 opaqueRegion = visibleRegion;
2956 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002957 }
2958 }
2959
Robert Carre5f4f692018-01-12 13:12:28 -08002960 if (visibleRegion.isEmpty()) {
2961 layer->clearVisibilityRegions();
2962 return;
2963 }
2964
Mathias Agopianab028732010-03-16 16:41:46 -07002965 // Clip the covered region to the visible region
2966 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2967
2968 // Update aboveCoveredLayers for next (lower) layer
2969 aboveCoveredLayers.orSelf(visibleRegion);
2970
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002971 // subtract the opaque region covered by the layers above us
2972 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002973
2974 // compute this layer's dirty region
2975 if (layer->contentDirty) {
2976 // we need to invalidate the whole region
2977 dirty = visibleRegion;
2978 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002979 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002980 layer->contentDirty = false;
2981 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002982 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002983 * the exposed region consists of two components:
2984 * 1) what's VISIBLE now and was COVERED before
2985 * 2) what's EXPOSED now less what was EXPOSED before
2986 *
2987 * note that (1) is conservative, we start with the whole
2988 * visible region but only keep what used to be covered by
2989 * something -- which mean it may have been exposed.
2990 *
2991 * (2) handles areas that were not covered by anything but got
2992 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002993 */
Mathias Agopianab028732010-03-16 16:41:46 -07002994 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002995 const Region oldVisibleRegion = layer->visibleRegion;
2996 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002997 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2998 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002999 }
3000 dirty.subtractSelf(aboveOpaqueLayers);
3001
3002 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003003 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003004
Mathias Agopianab028732010-03-16 16:41:46 -07003005 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003006 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003007
Jesse Halla8026d22012-09-25 13:25:04 -07003008 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003009 layer->setVisibleRegion(visibleRegion);
3010 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003011 layer->setVisibleNonTransparentRegion(
3012 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003013 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003014
Mathias Agopian87baae12012-07-31 12:38:26 -07003015 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003016}
3017
Chia-I Wuab0c3192017-08-01 11:29:00 -07003018void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003019 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003020 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
3021 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003022 }
3023 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003024}
3025
Dan Stoza6b9454d2014-11-07 16:00:59 -08003026bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003027{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003028 ALOGV("handlePageFlip");
3029
Brian Andersond6927fb2016-07-23 23:37:30 -07003030 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003031
Mathias Agopian4fec8732012-06-29 14:12:52 -07003032 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003033 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003034 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003035
3036 // Store the set of layers that need updates. This set must not change as
3037 // buffers are being latched, as this could result in a deadlock.
3038 // Example: Two producers share the same command stream and:
3039 // 1.) Layer 0 is latched
3040 // 2.) Layer 0 gets a new frame
3041 // 2.) Layer 1 gets a new frame
3042 // 3.) Layer 1 is latched.
3043 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3044 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003045 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003046 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003047 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07003048 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003049 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003050 } else {
3051 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003052 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003053 } else {
3054 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003055 }
Robert Carr2047fae2016-11-28 14:09:09 -08003056 });
3057
Dan Stoza9e56aa02015-11-02 13:00:03 -08003058 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07003059 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07003060 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003061 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07003062 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06003063 newDataLatched = true;
3064 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003065 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003066
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003067 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003068
3069 // If we will need to wake up at some time in the future to deal with a
3070 // queued frame that shouldn't be displayed during this vsync period, wake
3071 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003072 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003073 signalLayerUpdate();
3074 }
3075
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003076 // enter boot animation on first buffer latch
3077 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3078 ALOGI("Enter boot animation");
3079 mBootStage = BootStage::BOOTANIMATION;
3080 }
3081
Dan Stoza6b9454d2014-11-07 16:00:59 -08003082 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003083 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003084}
3085
Mathias Agopianad456f92011-01-13 17:53:01 -08003086void SurfaceFlinger::invalidateHwcGeometry()
3087{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003088 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003089}
3090
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003091void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
3092 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003093 // We only need to actually compose the display if:
3094 // 1) It is being handled by hardware composer, which may need this to
3095 // keep its virtual display state machine in sync, or
3096 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07003097 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08003098 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003099 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003100 return;
3101 }
3102
Dan Stoza9e56aa02015-11-02 13:00:03 -08003103 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003104 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003105
3106 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003107 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003108}
3109
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003110bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003111 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003112
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003113 const Region bounds(display->bounds());
3114 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003115 const auto displayId = display->getId();
3116 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003117 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003118
Chia-I Wu8e50e692018-05-04 10:12:37 -07003119 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003120 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003121
Dan Stoza9e56aa02015-11-02 13:00:03 -08003122 if (hasClientComposition) {
3123 ALOGV("hasClientComposition");
3124
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003125 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003126 if (display->hasWideColorGamut()) {
3127 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003128 }
3129 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003130 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003131 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003132
Dominik Laskowski7e045462018-05-30 13:02:02 -07003133 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003134 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3135 HWC2::Capability::SkipClientColorTransform);
3136
Chia-I Wud49d6692018-06-27 07:17:41 +08003137 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003138 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3139 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003140 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003141 }
3142
Chia-I Wud49d6692018-06-27 07:17:41 +08003143 // The current enhanced saturation matrix is designed to enhance Display P3,
3144 // thus we only apply this matrix when the render intent is not colorimetric
3145 // and the output color space is Display P3.
3146 needsEnhancedColorMatrix =
3147 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3148 outputDataspace == Dataspace::DISPLAY_P3);
3149 if (needsEnhancedColorMatrix) {
3150 colorMatrix *= mEnhancedSaturationMatrix;
3151 }
3152
3153 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003154
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003155 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003156 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003157 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003158 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003159
3160 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003161 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3162 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3163 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003164 }
3165 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003166 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003167
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003168 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003169 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003170 // when using overlays, we assume a fully transparent framebuffer
3171 // NOTE: we could reduce how much we need to clear, for instance
3172 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003173 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003174 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003175 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003176 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003177 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003178 // we're left with the letterbox region
3179 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003180 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003181
3182 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003183 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003184
Mathias Agopianb9494d52012-04-18 02:28:45 -07003185 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003186 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003187 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003188 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003189 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003190 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003191
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003192 const Rect& bounds = display->getBounds();
3193 const Rect& scissor = display->getScissor();
3194 if (scissor != bounds) {
3195 // scissor doesn't match the screen's dimensions, so we
3196 // need to clear everything outside of it and enable
3197 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003198
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003199 // enable scissor for this frame
Alec Mouri05483a02018-09-10 21:03:42 +00003200 getBE().mRenderEngine->setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003201 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003202 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003203
Mathias Agopian85d751c2012-08-29 16:59:24 -07003204 /*
3205 * and then, render the layers targeted at the framebuffer
3206 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003207
Dan Stoza9e56aa02015-11-02 13:00:03 -08003208 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003209 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003210 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003211 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003212 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003213 displayTransform.transform(layer->visibleRegion)));
3214 ALOGV("Layer: %s", layer->getName().string());
3215 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003216 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003217 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003218 case HWC2::Composition::Cursor:
3219 case HWC2::Composition::Device:
3220 case HWC2::Composition::Sideband:
3221 case HWC2::Composition::SolidColor: {
David Sodmanc1498e62018-09-12 14:36:26 -07003222 const Layer::State& state(layer->getDrawingState());
3223 if (layer->getClearClientTarget(displayId) && !firstLayer &&
3224 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3225 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003226 // never clear the very first layer since we're
3227 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003228 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003229 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003230 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003231 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003232 case HWC2::Composition::Client: {
David Sodmanc1498e62018-09-12 14:36:26 -07003233 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003234 break;
3235 }
3236 default:
3237 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003238 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003239 } else {
3240 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003241 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003242 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003243 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003244
Chia-I Wud49d6692018-06-27 07:17:41 +08003245 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003246 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003247 }
3248
Mathias Agopianf45c5102012-10-24 16:29:17 -07003249 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003250 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003251 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003252}
3253
Chia-I Wu28e3a252018-09-07 12:05:02 -07003254void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003255 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003256 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003257}
3258
Dan Stoza7d89d062015-04-30 13:29:25 -07003259status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003260 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003261 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003262 const sp<Layer>& lbc,
3263 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003264{
Dan Stoza7d89d062015-04-30 13:29:25 -07003265 // add this layer to the current state list
3266 {
3267 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003268 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003269 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3270 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003271 return NO_MEMORY;
3272 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003273 if (parent == nullptr) {
3274 mCurrentState.layersSortedByZ.add(lbc);
3275 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003276 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003277 ALOGE("addClientLayer called with a removed parent");
3278 return NAME_NOT_FOUND;
3279 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003280 parent->addChild(lbc);
3281 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003282
Yiwei Zhang243b3782018-05-15 17:40:04 -07003283 if (gbc != nullptr) {
3284 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3285 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3286 mMaxGraphicBufferProducerListSize,
3287 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3288 mGraphicBufferProducerList.size(),
3289 mMaxGraphicBufferProducerListSize, mNumLayers);
3290 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003291 mLayersAdded = true;
3292 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003293 }
3294
Mathias Agopian96f08192010-06-02 23:28:45 -07003295 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003296 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003297
Dan Stoza7d89d062015-04-30 13:29:25 -07003298 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003299}
3300
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003301status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003302 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003303 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3304}
Robert Carr7f9b8992017-03-10 11:08:39 -08003305
chaviwca27f252018-02-06 16:46:39 -08003306status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3307 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003308 if (layer->isPendingRemoval()) {
3309 return NO_ERROR;
3310 }
3311
Robert Carr1f0a16a2016-10-24 16:27:39 -07003312 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003313 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003314 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003315 if (topLevelOnly) {
3316 return NO_ERROR;
3317 }
3318
Chia-I Wu98f1c102017-05-30 14:54:08 -07003319 sp<Layer> ancestor = p;
3320 while (ancestor->getParent() != nullptr) {
3321 ancestor = ancestor->getParent();
3322 }
3323 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3324 ALOGE("removeLayer called with a layer whose parent has been removed");
3325 return NAME_NOT_FOUND;
3326 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003327
3328 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003329 } else {
3330 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003331 }
3332
Robert Carr136e2f62017-02-08 17:54:29 -08003333 // As a matter of normal operation, the LayerCleaner will produce a second
3334 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3335 // so we will succeed in promoting it, but it's already been removed
3336 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3337 // otherwise something has gone wrong and we are leaking the layer.
3338 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003339 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3340 layer->getName().string(),
3341 (p != nullptr) ? p->getName().string() : "no-parent");
3342 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003343 } else if (index < 0) {
3344 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003345 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003346
Chia-I Wuc6657022017-08-15 11:18:17 -07003347 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003348 mLayersPendingRemoval.add(layer);
3349 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003350 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003351 setTransactionFlags(eTransactionNeeded);
3352 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003353}
3354
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003355uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003356 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003357}
3358
Mathias Agopian3f844832013-08-07 21:24:32 -07003359uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003360 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003361}
3362
Mathias Agopian3f844832013-08-07 21:24:32 -07003363uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003364 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3365}
3366
3367uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3368 VSyncModulator::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003369 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003370 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003371 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003372 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003373 }
3374 return old;
3375}
3376
chaviwca27f252018-02-06 16:46:39 -08003377bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3378 for (const ComposerState& state : states) {
3379 // Here we need to check that the interface we're given is indeed
3380 // one of our own. A malicious client could give us a nullptr
3381 // IInterface, or one of its own or even one of our own but a
3382 // different type. All these situations would cause us to crash.
3383 if (state.client == nullptr) {
3384 return true;
3385 }
3386
3387 sp<IBinder> binder = IInterface::asBinder(state.client);
3388 if (binder == nullptr) {
3389 return true;
3390 }
3391
3392 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3393 return true;
3394 }
3395 }
3396 return false;
3397}
3398
Mathias Agopian8b33f032012-07-24 20:43:54 -07003399void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003400 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003401 const Vector<DisplayState>& displays,
3402 uint32_t flags)
3403{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003404 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003405 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003406 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003407
chaviwca27f252018-02-06 16:46:39 -08003408 if (containsAnyInvalidClientState(states)) {
3409 return;
3410 }
3411
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003412 if (flags & eAnimation) {
3413 // For window updates that are part of an animation we must wait for
3414 // previous animation "frames" to be handled.
3415 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003416 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003417 if (CC_UNLIKELY(err != NO_ERROR)) {
3418 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003419 // caller after a few seconds.
3420 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3421 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003422 mAnimTransactionPending = false;
3423 break;
3424 }
3425 }
3426 }
3427
chaviwca27f252018-02-06 16:46:39 -08003428 for (const DisplayState& display : displays) {
3429 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003430 }
3431
chaviwca27f252018-02-06 16:46:39 -08003432 for (const ComposerState& state : states) {
3433 transactionFlags |= setClientStateLocked(state);
3434 }
3435
3436 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3437 // as destroyed should only occur after setting all other states. This is to allow for a
3438 // child re-parent to happen before marking its original parent as destroyed (which would
3439 // then mark the child as destroyed).
3440 for (const ComposerState& state : states) {
3441 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003442 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003443
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003444 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3445 // anyway. This can be used as a flush mechanism for previous async transactions.
3446 // Empty animation transaction can be used to simulate back-pressure, so also force a
3447 // transaction for empty animation transactions.
3448 if (transactionFlags == 0 &&
3449 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003450 transactionFlags = eTransactionNeeded;
3451 }
3452
Mathias Agopian386aa982011-11-07 21:58:03 -08003453 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003454 if (mInterceptor->isEnabled()) {
3455 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003456 }
Irvel468051e2016-06-13 16:44:44 -07003457
Mathias Agopian386aa982011-11-07 21:58:03 -08003458 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003459 const auto start = (flags & eEarlyWakeup)
3460 ? VSyncModulator::TransactionStart::EARLY
3461 : VSyncModulator::TransactionStart::NORMAL;
3462 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003463
3464 // if this is a synchronous transaction, wait for it to take effect
3465 // before returning.
3466 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003467 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003468 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003469 if (flags & eAnimation) {
3470 mAnimTransactionPending = true;
3471 }
3472 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003473 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3474 if (CC_UNLIKELY(err != NO_ERROR)) {
3475 // just in case something goes wrong in SF, return to the
3476 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003477 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3478 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003479 break;
3480 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003481 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003482 }
3483}
3484
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003485uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3486 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3487 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003488
Mathias Agopiane57f2922012-08-09 16:29:12 -07003489 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003490 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3491
3492 const uint32_t what = s.what;
3493 if (what & DisplayState::eSurfaceChanged) {
3494 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3495 state.surface = s.surface;
3496 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003497 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003498 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003499 if (what & DisplayState::eLayerStackChanged) {
3500 if (state.layerStack != s.layerStack) {
3501 state.layerStack = s.layerStack;
3502 flags |= eDisplayTransactionNeeded;
3503 }
3504 }
3505 if (what & DisplayState::eDisplayProjectionChanged) {
3506 if (state.orientation != s.orientation) {
3507 state.orientation = s.orientation;
3508 flags |= eDisplayTransactionNeeded;
3509 }
3510 if (state.frame != s.frame) {
3511 state.frame = s.frame;
3512 flags |= eDisplayTransactionNeeded;
3513 }
3514 if (state.viewport != s.viewport) {
3515 state.viewport = s.viewport;
3516 flags |= eDisplayTransactionNeeded;
3517 }
3518 }
3519 if (what & DisplayState::eDisplaySizeChanged) {
3520 if (state.width != s.width) {
3521 state.width = s.width;
3522 flags |= eDisplayTransactionNeeded;
3523 }
3524 if (state.height != s.height) {
3525 state.height = s.height;
3526 flags |= eDisplayTransactionNeeded;
3527 }
3528 }
3529
Mathias Agopiane57f2922012-08-09 16:29:12 -07003530 return flags;
3531}
3532
Robert Carrd4ae7f32018-06-07 16:10:57 -07003533bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3534 IPCThreadState* ipc = IPCThreadState::self();
3535 const int pid = ipc->getCallingPid();
3536 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003537 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003538 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003539 return false;
3540 }
3541 return true;
3542}
3543
chaviwca27f252018-02-06 16:46:39 -08003544uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3545 const layer_state_t& s = composerState.state;
3546 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3547
Mathias Agopian13127d82013-03-05 17:47:11 -08003548 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003549 if (layer == nullptr) {
3550 return 0;
3551 }
3552
3553 if (layer->isPendingRemoval()) {
3554 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3555 return 0;
3556 }
3557
3558 uint32_t flags = 0;
3559
3560 const uint32_t what = s.what;
3561 bool geometryAppliesWithResize =
3562 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003563
3564 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3565 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003566 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003567 layer->pushPendingState();
3568 }
3569
chaviw8b3871a2017-11-01 17:41:01 -07003570 if (what & layer_state_t::ePositionChanged) {
3571 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3572 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003573 }
chaviw8b3871a2017-11-01 17:41:01 -07003574 }
3575 if (what & layer_state_t::eLayerChanged) {
3576 // NOTE: index needs to be calculated before we update the state
3577 const auto& p = layer->getParent();
3578 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003579 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003580 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003581 mCurrentState.layersSortedByZ.removeAt(idx);
3582 mCurrentState.layersSortedByZ.add(layer);
3583 // we need traversal (state changed)
3584 // AND transaction (list changed)
3585 flags |= eTransactionNeeded|eTraversalNeeded;
3586 }
chaviw8b3871a2017-11-01 17:41:01 -07003587 } else {
3588 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003589 flags |= eTransactionNeeded|eTraversalNeeded;
3590 }
3591 }
chaviw8b3871a2017-11-01 17:41:01 -07003592 }
3593 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003594 // NOTE: index needs to be calculated before we update the state
3595 const auto& p = layer->getParent();
3596 if (p == nullptr) {
3597 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3598 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3599 mCurrentState.layersSortedByZ.removeAt(idx);
3600 mCurrentState.layersSortedByZ.add(layer);
3601 // we need traversal (state changed)
3602 // AND transaction (list changed)
3603 flags |= eTransactionNeeded|eTraversalNeeded;
3604 }
3605 } else {
3606 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3607 flags |= eTransactionNeeded|eTraversalNeeded;
3608 }
chaviw8b3871a2017-11-01 17:41:01 -07003609 }
3610 }
3611 if (what & layer_state_t::eSizeChanged) {
3612 if (layer->setSize(s.w, s.h)) {
3613 flags |= eTraversalNeeded;
3614 }
3615 }
3616 if (what & layer_state_t::eAlphaChanged) {
3617 if (layer->setAlpha(s.alpha))
3618 flags |= eTraversalNeeded;
3619 }
3620 if (what & layer_state_t::eColorChanged) {
3621 if (layer->setColor(s.color))
3622 flags |= eTraversalNeeded;
3623 }
3624 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003625 // TODO: b/109894387
3626 //
3627 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3628 // rotation. To see the problem observe that if we have a square parent, and a child
3629 // of the same size, then we rotate the child 45 degrees around it's center, the child
3630 // must now be cropped to a non rectangular 8 sided region.
3631 //
3632 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3633 // private API, and the WindowManager only uses rotation in one case, which is on a top
3634 // level layer in which cropping is not an issue.
3635 //
3636 // However given that abuse of rotation matrices could lead to surfaces extending outside
3637 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3638 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3639 // transformations.
3640 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003641 flags |= eTraversalNeeded;
3642 }
3643 if (what & layer_state_t::eTransparentRegionChanged) {
3644 if (layer->setTransparentRegionHint(s.transparentRegion))
3645 flags |= eTraversalNeeded;
3646 }
3647 if (what & layer_state_t::eFlagsChanged) {
3648 if (layer->setFlags(s.flags, s.mask))
3649 flags |= eTraversalNeeded;
3650 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003651 if (what & layer_state_t::eCropChanged_legacy) {
3652 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003653 flags |= eTraversalNeeded;
3654 }
chaviw8b3871a2017-11-01 17:41:01 -07003655 if (what & layer_state_t::eLayerStackChanged) {
3656 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3657 // We only allow setting layer stacks for top level layers,
3658 // everything else inherits layer stack from its parent.
3659 if (layer->hasParent()) {
3660 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3661 layer->getName().string());
3662 } else if (idx < 0) {
3663 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3664 "that also does not appear in the top level layer list. Something"
3665 " has gone wrong.", layer->getName().string());
3666 } else if (layer->setLayerStack(s.layerStack)) {
3667 mCurrentState.layersSortedByZ.removeAt(idx);
3668 mCurrentState.layersSortedByZ.add(layer);
3669 // we need traversal (state changed)
3670 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003671 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003672 }
3673 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003674 if (what & layer_state_t::eDeferTransaction_legacy) {
3675 if (s.barrierHandle_legacy != nullptr) {
3676 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3677 } else if (s.barrierGbp_legacy != nullptr) {
3678 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003679 if (authenticateSurfaceTextureLocked(gbp)) {
3680 const auto& otherLayer =
3681 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003682 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003683 } else {
3684 ALOGE("Attempt to defer transaction to to an"
3685 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003686 }
3687 }
chaviw8b3871a2017-11-01 17:41:01 -07003688 // We don't trigger a traversal here because if no other state is
3689 // changed, we don't want this to cause any more work
3690 }
3691 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003692 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003693 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003694 if (!hadParent) {
3695 mCurrentState.layersSortedByZ.remove(layer);
3696 }
chaviw8b3871a2017-11-01 17:41:01 -07003697 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003698 }
chaviw8b3871a2017-11-01 17:41:01 -07003699 }
3700 if (what & layer_state_t::eReparentChildren) {
3701 if (layer->reparentChildren(s.reparentHandle)) {
3702 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003703 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003704 }
chaviw8b3871a2017-11-01 17:41:01 -07003705 if (what & layer_state_t::eDetachChildren) {
3706 layer->detachChildren();
3707 }
3708 if (what & layer_state_t::eOverrideScalingModeChanged) {
3709 layer->setOverrideScalingMode(s.overrideScalingMode);
3710 // We don't trigger a traversal here because if no other state is
3711 // changed, we don't want this to cause any more work
3712 }
Marissa Wall61c58622018-07-18 10:12:20 -07003713 if (what & layer_state_t::eTransformChanged) {
3714 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3715 }
3716 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3717 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3718 flags |= eTraversalNeeded;
3719 }
3720 if (what & layer_state_t::eCropChanged) {
3721 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3722 }
3723 if (what & layer_state_t::eBufferChanged) {
3724 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3725 }
3726 if (what & layer_state_t::eAcquireFenceChanged) {
3727 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3728 }
3729 if (what & layer_state_t::eDataspaceChanged) {
3730 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3731 }
3732 if (what & layer_state_t::eHdrMetadataChanged) {
3733 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3734 }
3735 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3736 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3737 }
3738 if (what & layer_state_t::eApiChanged) {
3739 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3740 }
3741 if (what & layer_state_t::eSidebandStreamChanged) {
3742 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3743 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003744 return flags;
3745}
3746
chaviwca27f252018-02-06 16:46:39 -08003747void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3748 const layer_state_t& state = composerState.state;
3749 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3750
3751 sp<Layer> layer(client->getLayerUser(state.surface));
3752 if (layer == nullptr) {
3753 return;
3754 }
3755
3756 if (layer->isPendingRemoval()) {
3757 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3758 return;
3759 }
3760
3761 if (state.what & layer_state_t::eDestroySurface) {
3762 removeLayerLocked(mStateLock, layer);
3763 }
3764}
3765
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003766status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003767 const String8& name,
3768 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003769 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003770 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003771 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003772{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003773 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003774 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003775 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003776 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003777 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003778
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003779 status_t result = NO_ERROR;
3780
3781 sp<Layer> layer;
3782
Cody Northropbc755282017-03-31 12:00:08 -06003783 String8 uniqueName = getUniqueLayerName(name);
3784
Mathias Agopian3165cc22012-08-08 19:42:09 -07003785 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003786 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003787 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3788 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003789
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003790 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003791 case ISurfaceComposerClient::eFXSurfaceBufferState:
3792 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3793 break;
chaviw13fdc492017-06-27 12:40:18 -07003794 case ISurfaceComposerClient::eFXSurfaceColor:
3795 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003796 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003797 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003798 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003799 case ISurfaceComposerClient::eFXSurfaceContainer:
3800 result = createContainerLayer(client,
3801 uniqueName, w, h, flags,
3802 handle, &layer);
3803 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003804 default:
3805 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003806 break;
3807 }
3808
Dan Stoza7d89d062015-04-30 13:29:25 -07003809 if (result != NO_ERROR) {
3810 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003811 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003812
Chia-I Wuab0c3192017-08-01 11:29:00 -07003813 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3814 // TODO b/64227542
3815 if (windowType == 441731) {
3816 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3817 layer->setPrimaryDisplayOnly();
3818 }
3819
Albert Chaulk479c60c2017-01-27 14:21:34 -05003820 layer->setInfo(windowType, ownerUid);
3821
Robert Carr1f0a16a2016-10-24 16:27:39 -07003822 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003823 if (result != NO_ERROR) {
3824 return result;
3825 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003826 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003827
3828 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003829 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003830}
3831
Cody Northropbc755282017-03-31 12:00:08 -06003832String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3833{
3834 bool matchFound = true;
3835 uint32_t dupeCounter = 0;
3836
3837 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3838 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3839
Dan Stoza436ccf32018-06-21 12:10:12 -07003840 // Grab the state lock since we're accessing mCurrentState
3841 Mutex::Autolock lock(mStateLock);
3842
Cody Northropbc755282017-03-31 12:00:08 -06003843 // Loop over layers until we're sure there is no matching name
3844 while (matchFound) {
3845 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003846 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003847 if (layer->getName() == uniqueName) {
3848 matchFound = true;
3849 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3850 }
3851 });
3852 }
3853
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003854 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3855 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003856
3857 return uniqueName;
3858}
3859
Marissa Wallfd668622018-05-10 10:21:13 -07003860status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3861 uint32_t w, uint32_t h, uint32_t flags,
3862 PixelFormat& format, sp<IBinder>* handle,
3863 sp<IGraphicBufferProducer>* gbp,
3864 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003865 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003866 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003867 case PIXEL_FORMAT_TRANSPARENT:
3868 case PIXEL_FORMAT_TRANSLUCENT:
3869 format = PIXEL_FORMAT_RGBA_8888;
3870 break;
3871 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003872 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003873 break;
3874 }
3875
Marissa Wallfd668622018-05-10 10:21:13 -07003876 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3877 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003878 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003879 *handle = layer->getHandle();
3880 *gbp = layer->getProducer();
3881 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003882 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003883
Marissa Wallfd668622018-05-10 10:21:13 -07003884 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003885 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003886}
3887
Marissa Wall61c58622018-07-18 10:12:20 -07003888status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3889 uint32_t w, uint32_t h, uint32_t flags,
3890 sp<IBinder>* handle, sp<Layer>* outLayer) {
3891 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3892 *handle = layer->getHandle();
3893 *outLayer = layer;
3894
3895 return NO_ERROR;
3896}
3897
chaviw13fdc492017-06-27 12:40:18 -07003898status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003899 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003900 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003901{
chaviw13fdc492017-06-27 12:40:18 -07003902 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003903 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003904 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003905}
3906
Robert Carr6b3f6c52018-08-13 13:05:17 -07003907status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3908 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3909 sp<IBinder>* handle, sp<Layer>* outLayer)
3910{
3911 *outLayer = new ContainerLayer(this, client, name, w, h, flags);
3912 *handle = (*outLayer)->getHandle();
3913 return NO_ERROR;
3914}
3915
3916
Mathias Agopianac9fa422013-02-11 16:40:36 -08003917status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003918{
Robert Carr9524cb32017-02-13 11:32:32 -08003919 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003920 status_t err = NO_ERROR;
3921 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003922 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003923 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003924 err = removeLayer(l);
3925 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3926 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003927 }
3928 return err;
3929}
3930
Mathias Agopian13127d82013-03-05 17:47:11 -08003931status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003932{
Mathias Agopian67106042013-03-14 19:18:13 -07003933 // called by ~LayerCleaner() when all references to the IBinder (handle)
3934 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003935 sp<Layer> l = layer.promote();
3936 if (l == nullptr) {
3937 // The layer has already been removed, carry on
3938 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003939 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003940 // If we have a parent, then we can continue to live as long as it does.
3941 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003942}
3943
Mathias Agopianb60314a2012-04-10 22:09:54 -07003944// ---------------------------------------------------------------------------
3945
Andy McFadden13a082e2012-08-24 10:16:42 -07003946void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003947 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3948 if (!displayToken) return;
3949
Jesse Hall01e29052013-02-19 16:13:35 -08003950 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003951 Vector<ComposerState> state;
3952 Vector<DisplayState> displays;
3953 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003954 d.what = DisplayState::eDisplayProjectionChanged |
3955 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003956 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003957 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003958 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003959 d.frame.makeInvalid();
3960 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003961 d.width = 0;
3962 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003963 displays.add(d);
3964 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003965
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003966 const auto display = getDisplayDevice(displayToken);
3967 if (!display) return;
3968
3969 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3970
3971 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003972 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003973 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003974
Brian Andersond0010582017-03-07 13:20:31 -08003975 // Use phase of 0 since phase is not known.
3976 // Use latency of 0, which will snap to the ideal latency.
3977 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003978}
3979
3980void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003981 // Async since we may be called from the main thread.
3982 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003983}
3984
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003985void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3986 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003987 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003988 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003989
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003990 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003991 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003992 return;
3993 }
3994
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003995 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003996 ALOGW("Trying to set power mode for virtual display");
3997 return;
3998 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003999
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004000 display->setPowerMode(mode);
4001
Lloyd Pique4dccc412018-01-22 17:21:36 -08004002 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07004003 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004004 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07004005 if (idx < 0) {
4006 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
4007 return;
4008 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07004009 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07004010 }
4011
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004012 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004013 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004014 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004015 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004016 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004017 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004018 if (mUseScheduler) {
4019 mScheduler->onScreenAcquired(mAppConnectionHandle);
4020 } else {
4021 mEventThread->onScreenAcquired();
4022 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07004023 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004024 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004025
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004026 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004027 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004028 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004029
4030 struct sched_param param = {0};
4031 param.sched_priority = 1;
4032 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4033 ALOGW("Couldn't set SCHED_FIFO on display on");
4034 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004035 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004036 // Turn off the display
4037 struct sched_param param = {0};
4038 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4039 ALOGW("Couldn't set SCHED_OTHER on display off");
4040 }
4041
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004042 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07004043 disableHardwareVsync(true); // also cancels any in-progress resync
4044
Mathias Agopiancde87a32012-09-13 14:09:01 -07004045 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004046 if (mUseScheduler) {
4047 mScheduler->onScreenReleased(mAppConnectionHandle);
4048 } else {
4049 mEventThread->onScreenReleased();
4050 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004051 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004052
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004053 getHwComposer().setPowerMode(type, mode);
4054 mVisibleRegionsDirty = true;
4055 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004056 } else if (mode == HWC_POWER_MODE_DOZE ||
4057 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004058 // Update display while dozing
4059 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004060 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004061 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004062 if (mUseScheduler) {
4063 mScheduler->onScreenAcquired(mAppConnectionHandle);
4064 } else {
4065 mEventThread->onScreenAcquired();
4066 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004067 resyncToHardwareVsync(true);
4068 }
4069 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4070 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004071 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004072 disableHardwareVsync(true); // also cancels any in-progress resync
4073 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004074 if (mUseScheduler) {
4075 mScheduler->onScreenReleased(mAppConnectionHandle);
4076 } else {
4077 mEventThread->onScreenReleased();
4078 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004079 }
4080 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004081 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004082 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004083 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004084 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004085
4086 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004087}
4088
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004089void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004090 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004091 const auto display = getDisplayDevice(displayToken);
4092 if (!display) {
4093 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4094 displayToken.get());
4095 } else if (display->isVirtual()) {
4096 ALOGW("Attempt to set power mode %d for virtual display", mode);
4097 } else {
4098 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004099 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004100 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004101}
4102
4103// ---------------------------------------------------------------------------
4104
Lloyd Pique755e3192018-01-31 16:46:15 -08004105status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4106 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004107 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004108
Mathias Agopianbd115332013-04-18 16:41:04 -07004109 IPCThreadState* ipc = IPCThreadState::self();
4110 const int pid = ipc->getCallingPid();
4111 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004112
Mathias Agopianbd115332013-04-18 16:41:04 -07004113 if ((uid != AID_SHELL) &&
4114 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004115 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07004116 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004117 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004118 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004119 // (this would indicate SF is stuck, but we want to be able to
4120 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004121 status_t err = mStateLock.timedLock(s2ns(1));
4122 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004123 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004124 result.appendFormat(
4125 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4126 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004127 }
4128
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004129 bool dumpAll = true;
4130 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004131 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004132
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004133 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004134 if ((index < numArgs) &&
4135 (args[index] == String16("--list"))) {
4136 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004137 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004138 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004139 }
4140
4141 if ((index < numArgs) &&
4142 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004143 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004144 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004145 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004146 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004147
4148 if ((index < numArgs) &&
4149 (args[index] == String16("--latency-clear"))) {
4150 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004151 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004152 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004153 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004154
4155 if ((index < numArgs) &&
4156 (args[index] == String16("--dispsync"))) {
4157 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004158 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004159 dumpAll = false;
4160 }
Dan Stozab90cf072015-03-05 11:05:59 -08004161
4162 if ((index < numArgs) &&
4163 (args[index] == String16("--static-screen"))) {
4164 index++;
4165 dumpStaticScreenStats(result);
4166 dumpAll = false;
4167 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004168
4169 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004170 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004171 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004172 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004173 dumpAll = false;
4174 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004175
4176 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4177 index++;
4178 dumpWideColorInfo(result);
4179 dumpAll = false;
4180 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004181
4182 if ((index < numArgs) &&
4183 (args[index] == String16("--enable-layer-stats"))) {
4184 index++;
4185 mLayerStats.enable();
4186 dumpAll = false;
4187 }
4188
4189 if ((index < numArgs) &&
4190 (args[index] == String16("--disable-layer-stats"))) {
4191 index++;
4192 mLayerStats.disable();
4193 dumpAll = false;
4194 }
4195
4196 if ((index < numArgs) &&
4197 (args[index] == String16("--clear-layer-stats"))) {
4198 index++;
4199 mLayerStats.clear();
4200 dumpAll = false;
4201 }
4202
4203 if ((index < numArgs) &&
4204 (args[index] == String16("--dump-layer-stats"))) {
4205 index++;
4206 mLayerStats.dump(result);
4207 dumpAll = false;
4208 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004209
4210 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004211 (args[index] == String16("--frame-composition"))) {
4212 index++;
4213 dumpFrameCompositionInfo(result);
4214 dumpAll = false;
4215 }
4216
4217 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004218 (args[index] == String16("--display-identification"))) {
4219 index++;
4220 dumpDisplayIdentificationData(result);
4221 dumpAll = false;
4222 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004223
4224 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4225 index++;
4226 mTimeStats.parseArgs(asProto, args, index, result);
4227 dumpAll = false;
4228 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004229 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004230
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004231 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004232 if (asProto) {
4233 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4234 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4235 } else {
4236 dumpAllLocked(args, index, result);
4237 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004238 }
4239
Mathias Agopian9795c422009-08-26 16:36:26 -07004240 if (locked) {
4241 mStateLock.unlock();
4242 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004243 }
4244 write(fd, result.string(), result.size());
4245 return NO_ERROR;
4246}
4247
Dan Stozac7014012014-02-14 15:03:43 -08004248void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4249 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004250{
Robert Carr2047fae2016-11-28 14:09:09 -08004251 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004252 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004253 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004254}
4255
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004256void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004257 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004258{
4259 String8 name;
4260 if (index < args.size()) {
4261 name = String8(args[index]);
4262 index++;
4263 }
4264
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004265 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4266 getHwComposer().isConnected(displayId)) {
4267 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4268 const nsecs_t period = activeConfig->getVsyncPeriod();
4269 result.appendFormat("%" PRId64 "\n", period);
4270 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004271
4272 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004273 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004274 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004275 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004276 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004277 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004278 }
Robert Carr2047fae2016-11-28 14:09:09 -08004279 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004280 }
4281}
4282
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004283void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004284 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004285{
4286 String8 name;
4287 if (index < args.size()) {
4288 name = String8(args[index]);
4289 index++;
4290 }
4291
Robert Carr2047fae2016-11-28 14:09:09 -08004292 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004293 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004294 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004295 }
Robert Carr2047fae2016-11-28 14:09:09 -08004296 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004297
Svetoslavd85084b2014-03-20 10:28:31 -07004298 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004299}
4300
Jamie Gennis6547ff42013-07-16 20:12:42 -07004301// This should only be called from the main thread. Otherwise it would need
4302// the lock and should use mCurrentState rather than mDrawingState.
4303void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004304 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004305 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004306 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004307
4308 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4309}
4310
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004311void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004312{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004313 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004314
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004315 if (isLayerTripleBufferingDisabled())
4316 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004317
4318 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004319 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004320 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004321 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004322 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4323 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004324 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004325}
4326
Dan Stozab90cf072015-03-05 11:05:59 -08004327void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4328{
4329 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004330 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4331 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004332 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004333 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004334 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4335 b + 1, bucketTimeSec, percent);
4336 }
David Sodman4a36e932017-11-07 14:29:47 -08004337 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004338 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004339 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004340 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004341 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004342}
4343
Dan Stozae77c7662016-05-13 11:37:28 -07004344void SurfaceFlinger::recordBufferingStats(const char* layerName,
4345 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004346 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4347 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004348 for (const auto& segment : history) {
4349 if (!segment.usedThirdBuffer) {
4350 stats.twoBufferTime += segment.totalTime;
4351 }
4352 if (segment.occupancyAverage < 1.0f) {
4353 stats.doubleBufferedTime += segment.totalTime;
4354 } else if (segment.occupancyAverage < 2.0f) {
4355 stats.tripleBufferedTime += segment.totalTime;
4356 }
4357 ++stats.numSegments;
4358 stats.totalTime += segment.totalTime;
4359 }
4360}
4361
Brian Andersond6927fb2016-07-23 23:37:30 -07004362void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4363 result.appendFormat("Layer frame timestamps:\n");
4364
4365 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4366 const size_t count = currentLayers.size();
4367 for (size_t i=0 ; i<count ; i++) {
4368 currentLayers[i]->dumpFrameEvents(result);
4369 }
4370}
4371
Dan Stozae77c7662016-05-13 11:37:28 -07004372void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4373 result.append("Buffering stats:\n");
4374 result.append(" [Layer name] <Active time> <Two buffer> "
4375 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004376 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004377 typedef std::tuple<std::string, float, float, float> BufferTuple;
4378 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004379 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004380 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004381 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004382 if (stats.numSegments == 0) {
4383 continue;
4384 }
4385 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4386 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4387 stats.totalTime;
4388 float doubleBufferRatio = static_cast<float>(
4389 stats.doubleBufferedTime) / stats.totalTime;
4390 float tripleBufferRatio = static_cast<float>(
4391 stats.tripleBufferedTime) / stats.totalTime;
4392 sorted.insert({activeTime, {name, twoBufferRatio,
4393 doubleBufferRatio, tripleBufferRatio}});
4394 }
4395 for (const auto& sortedPair : sorted) {
4396 float activeTime = sortedPair.first;
4397 const BufferTuple& values = sortedPair.second;
4398 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4399 std::get<0>(values).c_str(), activeTime,
4400 std::get<1>(values), std::get<2>(values),
4401 std::get<3>(values));
4402 }
4403 result.append("\n");
4404}
4405
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004406void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004407 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004408 const int32_t displayId = display->getId();
4409 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4410 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004411 continue;
4412 }
4413
Dominik Laskowski7e045462018-05-30 13:02:02 -07004414 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004415 uint8_t port;
4416 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004417 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004418 result.append("no identification data\n");
4419 continue;
4420 }
4421
4422 if (!isEdid(data)) {
4423 result.append("unknown identification data: ");
4424 for (uint8_t byte : data) {
4425 result.appendFormat("%x ", byte);
4426 }
4427 result.append("\n");
4428 continue;
4429 }
4430
4431 const auto edid = parseEdid(data);
4432 if (!edid) {
4433 result.append("invalid EDID: ");
4434 for (uint8_t byte : data) {
4435 result.appendFormat("%x ", byte);
4436 }
4437 result.append("\n");
4438 continue;
4439 }
4440
4441 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4442 result.append(edid->displayName.data(), edid->displayName.length());
4443 result.append("\"\n");
4444 }
4445 result.append("\n");
4446}
4447
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004448void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004449 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4450 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004451 result.appendFormat("DisplayColorSetting: %s\n",
4452 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004453
4454 // TODO: print out if wide-color mode is active or not
4455
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004456 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004457 const int32_t displayId = display->getId();
4458 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004459 continue;
4460 }
4461
Dominik Laskowski7e045462018-05-30 13:02:02 -07004462 result.appendFormat("Display %d color modes:\n", displayId);
4463 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004464 for (auto&& mode : modes) {
4465 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4466 }
4467
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004468 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004469 result.appendFormat(" Current color mode: %s (%d)\n",
4470 decodeColorMode(currentMode).c_str(), currentMode);
4471 }
4472 result.append("\n");
4473}
4474
David Sodman7e4ae112018-02-09 15:02:28 -08004475void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4476 std::string stringResult;
4477
4478 for (const auto& [token, display] : mDisplays) {
4479 const auto displayId = display->getId();
4480 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
4481 continue;
4482 }
4483
4484 const auto& compositionInfoIt = getBE().mEndOfFrameCompositionInfo.find(displayId);
4485 if (compositionInfoIt == getBE().mEndOfFrameCompositionInfo.end()) {
4486 break;
4487 }
4488 const auto& compositionInfoList = compositionInfoIt->second;
4489 stringResult += base::StringPrintf("Display: %d\n", displayId);
4490 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4491 for (const auto& compositionInfo : compositionInfoList) {
4492 compositionInfo.dump(stringResult, nullptr);
4493 stringResult += base::StringPrintf("\n");
4494 }
4495 }
4496
4497 result.append(stringResult.c_str());
4498}
4499
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004500LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004501 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004502 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4503 const State& state = useDrawing ? mDrawingState : mCurrentState;
4504 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004505 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004506 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004507 });
4508
4509 return layersProto;
4510}
4511
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004512LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004513 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004514
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004515 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004516 resolution->set_w(display.getWidth());
4517 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004518
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004519 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4520 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4521 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004522
Dominik Laskowski7e045462018-05-30 13:02:02 -07004523 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004524 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004525 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004526 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004527 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004528 }
4529 });
4530
4531 return layersProto;
4532}
4533
Mathias Agopian74d211a2013-04-22 16:55:35 +02004534void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4535 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004536{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004537 bool colorize = false;
4538 if (index < args.size()
4539 && (args[index] == String16("--color"))) {
4540 colorize = true;
4541 index++;
4542 }
4543
4544 Colorizer colorizer(colorize);
4545
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004546 // figure out if we're stuck somewhere
4547 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004548 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004549 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4550
4551 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004552 * Dump library configuration.
4553 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004554
4555 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004556 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004557 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004558 appendSfConfigString(result);
4559 appendUiConfigString(result);
4560 appendGuiConfigString(result);
4561 result.append("\n");
4562
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004563 result.append("\nDisplay identification data:\n");
4564 dumpDisplayIdentificationData(result);
4565
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004566 result.append("\nWide-Color information:\n");
4567 dumpWideColorInfo(result);
4568
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004569 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004570 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004571 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004572 result.append(SyncFeatures::getInstance().toString());
4573 result.append("\n");
4574
Andy McFadden41d67d72014-04-25 16:58:34 -07004575 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004576 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004577 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004578
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004579 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4580 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004581 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4582 getHwComposer().isConnected(displayId)) {
4583 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004584 result.appendFormat("Display %d: "
4585 "app phase %" PRId64 " ns, "
4586 "sf phase %" PRId64 " ns, "
4587 "early app phase %" PRId64 " ns, "
4588 "early sf phase %" PRId64 " ns, "
4589 "early app gl phase %" PRId64 " ns, "
4590 "early sf gl phase %" PRId64 " ns, "
4591 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4592 displayId,
4593 vsyncPhaseOffsetNs,
4594 sfVsyncPhaseOffsetNs,
4595 appEarlyOffset,
4596 sfEarlyOffset,
4597 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004598 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004599 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004600 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004601 result.append("\n");
4602
Dan Stozab90cf072015-03-05 11:05:59 -08004603 // Dump static screen stats
4604 result.append("\n");
4605 dumpStaticScreenStats(result);
4606 result.append("\n");
4607
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004608 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4609
Dan Stozae77c7662016-05-13 11:37:28 -07004610 dumpBufferingStats(result);
4611
Andy McFadden4803b742012-09-24 19:07:20 -07004612 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004613 * Dump the visible layer list
4614 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004615 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004616 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004617 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4618 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004619 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004620
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004621 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004622 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004623 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004624 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004625
David Sodman7e4ae112018-02-09 15:02:28 -08004626 result.append("\nFrame-Composition information:\n");
4627 dumpFrameCompositionInfo(result);
4628 result.append("\n");
4629
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004630 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004631 * Dump Display state
4632 */
4633
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004634 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004635 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004636 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004637 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004638 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004639 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004640 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004641
4642 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004643 * Dump SurfaceFlinger global state
4644 */
4645
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004646 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004647 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004648 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004649
Mathias Agopian888c8222012-08-04 21:10:38 -07004650 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004651 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004652
David Sodmanbc815282017-11-05 18:57:52 -08004653 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004654
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004655 if (display) {
4656 display->undefinedRegion.dump(result, "undefinedRegion");
4657 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4658 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004659 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004660 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004661 " gpu_to_cpu_unsupported : %d\n",
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004662 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004663
4664 if (display) {
4665 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4666 result.appendFormat(" refresh-rate : %f fps\n"
4667 " x-dpi : %f\n"
4668 " y-dpi : %f\n",
4669 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4670 activeConfig->getDpiY());
4671 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004672
Mathias Agopian74d211a2013-04-22 16:55:35 +02004673 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004674 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004675
Ana Krulec98b5b242018-08-10 15:03:23 -07004676 result.appendFormat(" use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004677 /*
4678 * VSYNC state
4679 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004680 if (mUseScheduler) {
4681 mScheduler->dump(mAppConnectionHandle, result);
4682 } else {
4683 mEventThread->dump(result);
4684 }
Dan Stozae22aec72016-08-01 13:20:59 -07004685 result.append("\n");
4686
4687 /*
4688 * HWC layer minidump
4689 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004690 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004691 const int32_t displayId = display->getId();
4692 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004693 continue;
4694 }
4695
Dominik Laskowski7e045462018-05-30 13:02:02 -07004696 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004697 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004698 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004699 result.append("\n");
4700 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004701
4702 /*
4703 * Dump HWComposer state
4704 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004705 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004706 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004707 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004708 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004709 result.appendFormat(" h/w composer %s\n",
4710 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004711 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004712
4713 /*
4714 * Dump gralloc state
4715 */
4716 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4717 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004718
4719 /*
4720 * Dump VrFlinger state if in use.
4721 */
4722 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4723 result.append("VrFlinger state:\n");
4724 result.append(mVrFlinger->Dump().c_str());
4725 result.append("\n");
4726 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004727}
4728
Dominik Laskowski7e045462018-05-30 13:02:02 -07004729const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004730 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004731 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004732 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004733 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004734 }
4735 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004736
4737 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4738 static const Vector<sp<Layer>> empty;
4739 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004740}
4741
Keun young Park63f165f2012-08-31 10:53:36 -07004742bool SurfaceFlinger::startDdmConnection()
4743{
4744 void* libddmconnection_dso =
4745 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4746 if (!libddmconnection_dso) {
4747 return false;
4748 }
4749 void (*DdmConnection_start)(const char* name);
4750 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004751 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004752 if (!DdmConnection_start) {
4753 dlclose(libddmconnection_dso);
4754 return false;
4755 }
4756 (*DdmConnection_start)(getServiceName());
4757 return true;
4758}
4759
Chia-I Wu28f320b2018-05-03 11:02:56 -07004760void SurfaceFlinger::updateColorMatrixLocked() {
4761 mat4 colorMatrix;
4762 if (mGlobalSaturationFactor != 1.0f) {
4763 // Rec.709 luma coefficients
4764 float3 luminance{0.213f, 0.715f, 0.072f};
4765 luminance *= 1.0f - mGlobalSaturationFactor;
4766 mat4 saturationMatrix = mat4(
4767 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4768 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4769 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4770 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4771 );
4772 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4773 } else {
4774 colorMatrix = mClientColorMatrix * mDaltonizer();
4775 }
4776
4777 if (mCurrentState.colorMatrix != colorMatrix) {
4778 mCurrentState.colorMatrix = colorMatrix;
4779 mCurrentState.colorMatrixChanged = true;
4780 setTransactionFlags(eTransactionNeeded);
4781 }
4782}
4783
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004784status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004785#pragma clang diagnostic push
4786#pragma clang diagnostic error "-Wswitch-enum"
4787 switch (static_cast<ISurfaceComposerTag>(code)) {
4788 // These methods should at minimum make sure that the client requested
4789 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004790 case BOOT_FINISHED:
4791 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004792 case CREATE_CONNECTION:
4793 case CREATE_DISPLAY:
4794 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004795 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004796 case GET_ACTIVE_COLOR_MODE:
4797 case GET_ANIMATION_FRAME_STATS:
4798 case GET_HDR_CAPABILITIES:
4799 case SET_ACTIVE_CONFIG:
4800 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004801 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004802 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004803 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4804 IPCThreadState* ipc = IPCThreadState::self();
4805 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4806 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004807 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004808 }
Robert Carr1db73f62016-12-21 12:58:51 -08004809 return OK;
4810 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004811 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004812 IPCThreadState* ipc = IPCThreadState::self();
4813 const int pid = ipc->getCallingPid();
4814 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004815 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4816 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004817 return PERMISSION_DENIED;
4818 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004819 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004820 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004821 // Used by apps to hook Choreographer to SurfaceFlinger.
4822 case CREATE_DISPLAY_EVENT_CONNECTION:
4823 // The following calls are currently used by clients that do not
4824 // request necessary permissions. However, they do not expose any secret
4825 // information, so it is OK to pass them.
4826 case AUTHENTICATE_SURFACE:
4827 case GET_ACTIVE_CONFIG:
4828 case GET_BUILT_IN_DISPLAY:
4829 case GET_DISPLAY_COLOR_MODES:
4830 case GET_DISPLAY_CONFIGS:
4831 case GET_DISPLAY_STATS:
4832 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4833 // Calling setTransactionState is safe, because you need to have been
4834 // granted a reference to Client* and Handle* to do anything with it.
4835 case SET_TRANSACTION_STATE:
4836 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004837 case CREATE_SCOPED_CONNECTION:
4838 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004839 return OK;
4840 }
4841 case CAPTURE_LAYERS:
4842 case CAPTURE_SCREEN: {
4843 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004844 IPCThreadState* ipc = IPCThreadState::self();
4845 const int pid = ipc->getCallingPid();
4846 const int uid = ipc->getCallingUid();
4847 if ((uid != AID_GRAPHICS) &&
4848 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4849 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4850 return PERMISSION_DENIED;
4851 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004852 return OK;
4853 }
4854 // The following codes are deprecated and should never be allowed to access SF.
4855 case CONNECT_DISPLAY_UNUSED:
4856 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4857 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4858 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004859 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004860 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004861
4862 // These codes are used for the IBinder protocol to either interrogate the recipient
4863 // side of the transaction for its canonical interface descriptor or to dump its state.
4864 // We let them pass by default.
4865 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4866 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4867 code == IBinder::SYSPROPS_TRANSACTION) {
4868 return OK;
4869 }
4870 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4871 // in onTransact verifies that the user is root, and has access to use SF.
4872 if (code >= 1000 && code <= 1029) {
4873 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4874 return OK;
4875 }
4876 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4877 return PERMISSION_DENIED;
4878#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004879}
4880
Ana Krulec13be8ad2018-08-21 02:43:56 +00004881status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4882 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004883 status_t credentialCheck = CheckTransactCodeCredentials(code);
4884 if (credentialCheck != OK) {
4885 return credentialCheck;
4886 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004887
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004888 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4889 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004890 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004891 IPCThreadState* ipc = IPCThreadState::self();
4892 const int uid = ipc->getCallingUid();
4893 if (CC_UNLIKELY(uid != AID_SYSTEM
4894 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004895 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004896 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004897 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004898 return PERMISSION_DENIED;
4899 }
4900 int n;
4901 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004902 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004903 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004904 return NO_ERROR;
4905 case 1002: // SHOW_UPDATES
4906 n = data.readInt32();
4907 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004908 invalidateHwcGeometry();
4909 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004910 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004911 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004912 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004913 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004914 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004915 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004916 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004917 setTransactionFlags(
4918 eTransactionNeeded|
4919 eDisplayTransactionNeeded|
4920 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004921 return NO_ERROR;
4922 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004923 case 1006:{ // send empty update
4924 signalRefresh();
4925 return NO_ERROR;
4926 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004927 case 1008: // toggle use of hw composer
4928 n = data.readInt32();
4929 mDebugDisableHWC = n ? 1 : 0;
4930 invalidateHwcGeometry();
4931 repaintEverything();
4932 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004933 case 1009: // toggle use of transform hint
4934 n = data.readInt32();
4935 mDebugDisableTransformHint = n ? 1 : 0;
4936 invalidateHwcGeometry();
4937 repaintEverything();
4938 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004939 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004940 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004941 reply->writeInt32(0);
4942 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004943 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004944 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004945 return NO_ERROR;
4946 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004947 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004948 if (!display) {
4949 return NAME_NOT_FOUND;
4950 }
4951
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004952 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004953 return NO_ERROR;
4954 }
4955 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004956 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004957 // daltonize
4958 n = data.readInt32();
4959 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004960 case 1:
4961 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4962 break;
4963 case 2:
4964 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4965 break;
4966 case 3:
4967 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4968 break;
4969 default:
4970 mDaltonizer.setType(ColorBlindnessType::None);
4971 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004972 }
4973 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004974 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004975 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004976 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004977 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004978
4979 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004980 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004981 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004982 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004983 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004984 // apply a color matrix
4985 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004986 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004987 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004988 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004989 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004990 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004991 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004992 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004993 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004994 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004995 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004996
4997 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4998 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004999 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005000 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5001 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5002 }
5003
Chia-I Wu28f320b2018-05-03 11:02:56 -07005004 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005005 return NO_ERROR;
5006 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005007 // This is an experimental interface
5008 // Needs to be shifted to proper binder interface when we productize
5009 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005010 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07005011 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005012 return NO_ERROR;
5013 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005014 case 1017: {
5015 n = data.readInt32();
5016 mForceFullDamage = static_cast<bool>(n);
5017 return NO_ERROR;
5018 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005019 case 1018: { // Modify Choreographer's phase offset
5020 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005021 if (mUseScheduler) {
5022 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5023 } else {
5024 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5025 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005026 return NO_ERROR;
5027 }
5028 case 1019: { // Modify SurfaceFlinger's phase offset
5029 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005030 if (mUseScheduler) {
5031 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5032 } else {
5033 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5034 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005035 return NO_ERROR;
5036 }
Irvel468051e2016-06-13 16:44:44 -07005037 case 1020: { // Layer updates interceptor
5038 n = data.readInt32();
5039 if (n) {
5040 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005041 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005042 }
5043 else{
5044 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005045 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005046 }
5047 return NO_ERROR;
5048 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005049 case 1021: { // Disable HWC virtual displays
5050 n = data.readInt32();
5051 mUseHwcVirtualDisplays = !n;
5052 return NO_ERROR;
5053 }
Romain Guy0147a172017-06-01 13:53:56 -07005054 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005055 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005056 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005057
Chia-I Wu28f320b2018-05-03 11:02:56 -07005058 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005059 return NO_ERROR;
5060 }
Romain Guy54f154a2017-10-24 21:40:32 +01005061 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005062 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005063 invalidateHwcGeometry();
5064 repaintEverything();
5065 return NO_ERROR;
5066 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005067 // TODO(b/111505327): Find out whether the usage of 1024 can switch to 1030,
5068 // deprecate 1024 if they can.
5069 case 1024: { // Does device have wide color gamut display?
Romain Guy54f154a2017-10-24 21:40:32 +01005070 reply->writeBool(hasWideColorDisplay);
5071 return NO_ERROR;
5072 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005073 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005074 n = data.readInt32();
5075 if (n) {
5076 ALOGV("LayerTracing enabled");
5077 mTracing.enable();
5078 doTracing("tracing.enable");
5079 reply->writeInt32(NO_ERROR);
5080 } else {
5081 ALOGV("LayerTracing disabled");
5082 status_t err = mTracing.disable();
5083 reply->writeInt32(err);
5084 }
5085 return NO_ERROR;
5086 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005087 case 1026: { // Get layer tracing status
5088 reply->writeBool(mTracing.isEnabled());
5089 return NO_ERROR;
5090 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005091 // Is a DisplayColorSetting supported?
5092 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005093 const auto display = getDefaultDisplayDevice();
5094 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005095 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005096 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005097
5098 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5099 switch (setting) {
5100 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005101 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005102 break;
5103 case DisplayColorSetting::UNMANAGED:
5104 reply->writeBool(true);
5105 break;
5106 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005107 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005108 break;
5109 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005110 reply->writeBool(
5111 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005112 break;
5113 }
5114 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005115 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005116 // Is VrFlinger active?
5117 case 1028: {
5118 Mutex::Autolock _l(mStateLock);
5119 reply->writeBool(getBE().mHwc->isUsingVrComposer());
5120 return NO_ERROR;
5121 }
David Sodman6d46c1e2018-07-13 12:59:48 -07005122 case 1029: {
5123 // Code 1029 is an experimental feature that allows applications to
5124 // simulate a high frequency panel by setting a multiplier and divisor
5125 // on the VSYNC-sf clock. If either the multiplier or divisor are
David Sodman44b5de02018-08-21 16:28:53 -07005126 // 0, then the code simply return the current multiplier and divisor.
5127 HWC2::Device::FrequencyScaler frequencyScaler;
5128 frequencyScaler.multiplier = data.readInt32();
5129 frequencyScaler.divisor = data.readInt32();
David Sodman6d46c1e2018-07-13 12:59:48 -07005130
David Sodman44b5de02018-08-21 16:28:53 -07005131 if ((frequencyScaler.multiplier == 0) || (frequencyScaler.divisor == 0)) {
5132 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5133 reply->writeInt32(frequencyScaler.multiplier);
5134 reply->writeInt32(frequencyScaler.divisor);
5135 return NO_ERROR;
David Sodman6d46c1e2018-07-13 12:59:48 -07005136 }
5137
David Sodman44b5de02018-08-21 16:28:53 -07005138 if ((frequencyScaler.multiplier == 1) && (frequencyScaler.divisor == 1)) {
David Sodman6d46c1e2018-07-13 12:59:48 -07005139 enableHardwareVsync();
5140 } else {
5141 disableHardwareVsync(true);
5142 }
David Sodman44b5de02018-08-21 16:28:53 -07005143 mPrimaryDispSync->scalePeriod(frequencyScaler);
5144 getBE().mHwc->setDisplayFrequencyScaleParameters(frequencyScaler);
David Sodman6d46c1e2018-07-13 12:59:48 -07005145
David Sodman44b5de02018-08-21 16:28:53 -07005146 ATRACE_INT("PeriodMultiplier", frequencyScaler.multiplier);
5147 ATRACE_INT("PeriodDivisor", frequencyScaler.divisor);
5148
5149 const hwc2_display_t hwcDisplayId = getBE().mHwc->getActiveConfig(
5150 DisplayDevice::DISPLAY_PRIMARY)->getDisplayId();
5151
5152 onHotplugReceived(getBE().mComposerSequenceId,
5153 hwcDisplayId, HWC2::Connection::Disconnected);
5154 onHotplugReceived(getBE().mComposerSequenceId,
5155 hwcDisplayId, HWC2::Connection::Connected);
5156 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5157 reply->writeInt32(frequencyScaler.multiplier);
5158 reply->writeInt32(frequencyScaler.divisor);
5159
David Sodman6d46c1e2018-07-13 12:59:48 -07005160 return NO_ERROR;
5161 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005162 // Is device color managed?
5163 case 1030: {
5164 reply->writeBool(useColorManagement);
5165 return NO_ERROR;
5166 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005167 }
5168 }
5169 return err;
5170}
5171
Steven Thomas6d8110b2017-08-31 18:24:21 -07005172void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005173 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005174 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005175}
5176
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005177// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5178class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005179public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005180 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5181 ~WindowDisconnector() {
5182 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005183 }
5184
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005185private:
5186 ANativeWindow* mWindow;
5187 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005188};
5189
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005190status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
5191 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
5192 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
5193 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005194 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005195 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005196
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005197 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005198
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005199 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5200
Chia-I Wu20261cb2018-08-23 12:55:44 -07005201 sp<DisplayDevice> display;
5202 {
5203 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005204
Chia-I Wu20261cb2018-08-23 12:55:44 -07005205 display = getDisplayDeviceLocked(displayToken);
5206 if (!display) return BAD_VALUE;
5207
Chia-I Wu8730ba82018-08-29 09:25:59 -07005208 // ignore sourceCrop (i.e., use the projected logical display
5209 // viewport) until the framework is fixed
5210 sourceCrop.clear();
Chia-I Wucb023152018-08-28 12:57:23 -07005211
5212 // set the requested width/height to the logical display viewport size
5213 // by default
5214 if (reqWidth == 0 || reqHeight == 0) {
5215 reqWidth = uint32_t(display->getViewport().width());
5216 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005217 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005218 }
5219
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005220 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005221
5222 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005223 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005224 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005225}
5226
5227status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08005228 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005229 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005230 ATRACE_CALL();
5231
5232 class LayerRenderArea : public RenderArea {
5233 public:
Robert Carr578038f2018-03-09 12:25:24 -08005234 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
5235 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
Chia-I Wu9d1abea2018-08-23 13:44:43 -07005236 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08005237 mLayer(layer),
5238 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005239 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005240 mFlinger(flinger),
5241 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005242 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005243 Rect getBounds() const override {
5244 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005245 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005246 }
Marissa Wall61c58622018-07-18 10:12:20 -07005247 int getHeight() const override {
5248 return mLayer->getActiveHeight(mLayer->getDrawingState());
5249 }
5250 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005251 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005252 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005253 Rect getSourceCrop() const override {
5254 if (mCrop.isEmpty()) {
5255 return getBounds();
5256 } else {
5257 return mCrop;
5258 }
5259 }
Robert Carr578038f2018-03-09 12:25:24 -08005260 class ReparentForDrawing {
5261 public:
5262 const sp<Layer>& oldParent;
5263 const sp<Layer>& newParent;
5264
5265 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5266 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005267 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005268 }
Robert Carr15eae092018-03-23 13:43:53 -07005269 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005270 };
5271
5272 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005273 const Rect sourceCrop = getSourceCrop();
5274 // no need to check rotation because there is none
5275 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5276 sourceCrop.height() != getReqHeight();
5277
Robert Carr578038f2018-03-09 12:25:24 -08005278 if (!mChildrenOnly) {
5279 mTransform = mLayer->getTransform().inverse();
5280 drawLayers();
5281 } else {
5282 Rect bounds = getBounds();
5283 screenshotParentLayer =
5284 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
5285 bounds.getWidth(), bounds.getHeight(), 0);
5286
5287 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5288 drawLayers();
5289 }
5290 }
chaviwa76b2712017-09-20 12:02:26 -07005291
chaviwa76b2712017-09-20 12:02:26 -07005292 private:
chaviw7206d492017-11-10 16:16:12 -08005293 const sp<Layer> mLayer;
5294 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005295
5296 // In the "childrenOnly" case we reparent the children to a screenshot
5297 // layer which has no properties set and which does not draw.
5298 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005299 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005300 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005301
5302 SurfaceFlinger* mFlinger;
5303 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005304 };
5305
5306 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5307 auto parent = layerHandle->owner.promote();
5308
chaviw7206d492017-11-10 16:16:12 -08005309 if (parent == nullptr || parent->isPendingRemoval()) {
5310 ALOGE("captureLayers called with a removed parent");
5311 return NAME_NOT_FOUND;
5312 }
5313
Robert Carr578038f2018-03-09 12:25:24 -08005314 const int uid = IPCThreadState::self()->getCallingUid();
5315 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5316 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5317 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5318 return PERMISSION_DENIED;
5319 }
5320
chaviw7206d492017-11-10 16:16:12 -08005321 Rect crop(sourceCrop);
5322 if (sourceCrop.width() <= 0) {
5323 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005324 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005325 }
5326
5327 if (sourceCrop.height() <= 0) {
5328 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005329 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005330 }
5331
5332 int32_t reqWidth = crop.width() * frameScale;
5333 int32_t reqHeight = crop.height() * frameScale;
5334
Chia-I Wu20261cb2018-08-23 12:55:44 -07005335 // really small crop or frameScale
5336 if (reqWidth <= 0) {
5337 reqWidth = 1;
5338 }
5339 if (reqHeight <= 0) {
5340 reqHeight = 1;
5341 }
5342
Robert Carr578038f2018-03-09 12:25:24 -08005343 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005344
Robert Carr578038f2018-03-09 12:25:24 -08005345 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005346 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5347 if (!layer->isVisible()) {
5348 return;
Robert Carr578038f2018-03-09 12:25:24 -08005349 } else if (childrenOnly && layer == parent.get()) {
5350 return;
chaviwa76b2712017-09-20 12:02:26 -07005351 }
5352 visitor(layer);
5353 });
5354 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005355 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005356}
5357
5358status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5359 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005360 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005361 bool useIdentityTransform) {
5362 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005363
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005364 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5365 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5366 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5367 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005368
5369 // This mutex protects syncFd and captureResult for communication of the return values from the
5370 // main thread back to this Binder thread
5371 std::mutex captureMutex;
5372 std::condition_variable captureCondition;
5373 std::unique_lock<std::mutex> captureLock(captureMutex);
5374 int syncFd = -1;
5375 std::optional<status_t> captureResult;
5376
Robert Carr03480e22018-01-04 16:02:06 -08005377 const int uid = IPCThreadState::self()->getCallingUid();
5378 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5379
Dominik Laskowski8c001672018-05-30 16:52:06 -07005380 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005381 // If there is a refresh pending, bug out early and tell the binder thread to try again
5382 // after the refresh.
5383 if (mRefreshPending) {
5384 ATRACE_NAME("Skipping screenshot for now");
5385 std::unique_lock<std::mutex> captureLock(captureMutex);
5386 captureResult = std::make_optional<status_t>(EAGAIN);
5387 captureCondition.notify_one();
5388 return;
5389 }
5390
5391 status_t result = NO_ERROR;
5392 int fd = -1;
5393 {
5394 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005395 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005396 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5397 useIdentityTransform, forSystem, &fd);
5398 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005399 }
5400
5401 {
5402 std::unique_lock<std::mutex> captureLock(captureMutex);
5403 syncFd = fd;
5404 captureResult = std::make_optional<status_t>(result);
5405 captureCondition.notify_one();
5406 }
5407 });
5408
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005409 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005410 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005411 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005412 while (*captureResult == EAGAIN) {
5413 captureResult.reset();
5414 result = postMessageAsync(message);
5415 if (result != NO_ERROR) {
5416 return result;
5417 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005418 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005419 }
5420 result = *captureResult;
5421 }
5422
5423 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005424 sync_wait(syncFd, -1);
5425 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005426 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005427
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005428 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005429}
5430
chaviwa76b2712017-09-20 12:02:26 -07005431void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005432 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005433 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005434 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005435
Lloyd Pique144e1162017-12-20 16:44:52 -08005436 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005437
chaviwa76b2712017-09-20 12:02:26 -07005438 const auto reqWidth = renderArea.getReqWidth();
5439 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005440 const auto sourceCrop = renderArea.getSourceCrop();
5441 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005442
Chia-I Wu36574d92018-05-16 10:54:36 -07005443 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5444 engine.setOutputDataSpace(Dataspace::SRGB);
5445 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005446
Mathias Agopian180f10d2013-04-10 22:55:41 -07005447 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005448 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005449
5450 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005451 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005452 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005453
chaviw50da5042018-04-09 13:49:37 -07005454 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005455 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005456 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005457
chaviwa76b2712017-09-20 12:02:26 -07005458 traverseLayers([&](Layer* layer) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08005459 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005460 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005461}
5462
chaviwa76b2712017-09-20 12:02:26 -07005463status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5464 TraverseLayersFunction traverseLayers,
5465 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005466 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005467 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005468 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005469 ATRACE_CALL();
5470
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005471 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005472
5473 traverseLayers([&](Layer* layer) {
5474 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5475 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005476
Robert Carr03480e22018-01-04 16:02:06 -08005477 // We allow the system server to take screenshots of secure layers for
5478 // use in situations like the Screen-rotation animation and place
5479 // the impetus on WindowManager to not persist them.
5480 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005481 ALOGW("FB is protected: PERMISSION_DENIED");
5482 return PERMISSION_DENIED;
5483 }
5484
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005485 // this binds the given EGLImage as a framebuffer for the
5486 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005487 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005488 if (bufferBond.getStatus() != NO_ERROR) {
5489 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005490 return INVALID_OPERATION;
5491 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005492
Dan Stozaabcda352017-06-01 14:37:39 -07005493 // this will in fact render into our dequeued buffer
5494 // via an FBO, which means we didn't have to create
5495 // an EGLSurface and therefore we're not
5496 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005497 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005498
Alec Mouri492bc572018-09-11 21:40:04 +00005499 base::unique_fd syncFd = getRenderEngine().flush();
5500 if (syncFd < 0) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005501 getRenderEngine().finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005502 }
Alec Mouri492bc572018-09-11 21:40:04 +00005503 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005504
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005505 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005506}
5507
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005508// ---------------------------------------------------------------------------
5509
Dan Stoza412903f2017-04-27 13:42:17 -07005510void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5511 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005512}
5513
Dan Stoza412903f2017-04-27 13:42:17 -07005514void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5515 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005516}
5517
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005518void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5519 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005520 const LayerVector::Visitor& visitor) {
5521 // We loop through the first level of layers without traversing,
5522 // as we need to interpret min/max layer Z in the top level Z space.
5523 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005524 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005525 continue;
5526 }
5527 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005528 // relative layers are traversed in Layer::traverseInZOrder
5529 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005530 continue;
5531 }
5532 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005533 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005534 return;
5535 }
chaviwa76b2712017-09-20 12:02:26 -07005536 if (!layer->isVisible()) {
5537 return;
5538 }
5539 visitor(layer);
5540 });
5541 }
5542}
5543
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005544}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005545
Lloyd Pique074e8122018-07-26 12:57:23 -07005546
Mathias Agopian3f844832013-08-07 21:24:32 -07005547#if defined(__gl_h_)
5548#error "don't include gl/gl.h in this file"
5549#endif
5550
5551#if defined(__gl2_h_)
5552#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005553#endif