blob: 64520d0979cb8ff14ef8bd5f8a30336c29f7b5fb [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Chia-I Wud49d6692018-06-27 07:17:41 +080040#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060041#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070043#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080048#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070050
51#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Robert Carr578038f2018-03-09 12:25:24 -080065#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070066#include "BufferQueueLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020067#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080068#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020069#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080070#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080071#include "DdmConnection.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070072#include "DispSync.h"
Robert Carr578038f2018-03-09 12:25:24 -080073#include "DisplayDevice.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070074#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080075#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070077#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080078#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079#include "SurfaceFlinger.h"
Robert Carr578038f2018-03-09 12:25:24 -080080#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081
Steven Thomasb02664d2017-07-26 18:48:28 -070082#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070083#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070084#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070085#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070086#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080087
Mathias Agopianff2ed702013-09-01 21:36:12 -070088#include "Effects/Daltonizer.h"
89
Mathias Agopian875d8e12013-06-07 15:35:48 -070090#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070091#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070092
Jiyong Park4b20c2e2017-01-14 19:45:11 +090093#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080094#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
95#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090096#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090097
chaviw1d044282017-09-27 12:19:28 -070098#include <layerproto/LayerProtoParser.h>
99
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800100#define DISPLAY_COUNT 1
101
Mathias Agopianfee2b462013-07-03 12:34:01 -0700102/*
103 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
104 * black pixels.
105 */
106#define DEBUG_SCREENSHOTS false
107
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800108namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700109
Jaesoo Lee43518572017-01-23 19:03:16 +0900110using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900111using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700112using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700113using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700114using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700115using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900116
Steven Thomasb02664d2017-07-26 18:48:28 -0700117namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700118
119#pragma clang diagnostic push
120#pragma clang diagnostic error "-Wswitch-enum"
121
122bool isWideColorMode(const ColorMode colorMode) {
123 switch (colorMode) {
124 case ColorMode::DISPLAY_P3:
125 case ColorMode::ADOBE_RGB:
126 case ColorMode::DCI_P3:
127 case ColorMode::BT2020:
128 case ColorMode::BT2100_PQ:
129 case ColorMode::BT2100_HLG:
130 return true;
131 case ColorMode::NATIVE:
132 case ColorMode::STANDARD_BT601_625:
133 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
134 case ColorMode::STANDARD_BT601_525:
135 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
136 case ColorMode::STANDARD_BT709:
137 case ColorMode::SRGB:
138 return false;
139 }
140 return false;
141}
142
143#pragma clang diagnostic pop
144
Steven Thomasb02664d2017-07-26 18:48:28 -0700145class ConditionalLock {
146public:
147 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
148 if (lock) {
149 mMutex.lock();
150 }
151 }
152 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
153private:
154 Mutex& mMutex;
155 bool mLocked;
156};
Peiyong Linfca547f2018-07-09 13:03:33 -0700157
Steven Thomasb02664d2017-07-26 18:48:28 -0700158} // namespace anonymous
159
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800160// ---------------------------------------------------------------------------
161
Mathias Agopian99b49842011-06-27 16:05:52 -0700162const String16 sHardwareTest("android.permission.HARDWARE_TEST");
163const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
164const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
165const String16 sDump("android.permission.DUMP");
166
167// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800168int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
169int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700170int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700171bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800172uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800173bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800174bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800175int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800176// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600177bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700178
Kalle Raitaa099a242017-01-11 11:17:29 -0800179
180std::string getHwcServiceName() {
181 char value[PROPERTY_VALUE_MAX] = {};
182 property_get("debug.sf.hwc_service_name", value, "default");
183 ALOGI("Using HWComposer service: '%s'", value);
184 return std::string(value);
185}
186
187bool useTrebleTestingOverride() {
188 char value[PROPERTY_VALUE_MAX] = {};
189 property_get("debug.sf.treble_testing_override", value, "false");
190 ALOGI("Treble testing override: '%s'", value);
191 return std::string(value) == "true";
192}
193
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800194std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
195 switch(displayColorSetting) {
196 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700197 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800198 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700199 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800200 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700201 return std::string("Enhanced");
202 default:
203 return std::string("Unknown ") +
204 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800205 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800206}
207
Lloyd Pique99d3da52018-01-22 17:48:03 -0800208NativeWindowSurface::~NativeWindowSurface() = default;
209
210namespace impl {
211
212class NativeWindowSurface final : public android::NativeWindowSurface {
213public:
214 static std::unique_ptr<android::NativeWindowSurface> create(
215 const sp<IGraphicBufferProducer>& producer) {
216 return std::make_unique<NativeWindowSurface>(producer);
217 }
218
219 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
220 : surface(new Surface(producer, false)) {}
221
222 ~NativeWindowSurface() override = default;
223
224private:
225 sp<ANativeWindow> getNativeWindow() const override { return surface; }
226
227 void preallocateBuffers() override { surface->allocateBuffers(); }
228
229 sp<Surface> surface;
230};
231
232} // namespace impl
233
David Sodmanbc815282017-11-05 18:57:52 -0800234SurfaceFlingerBE::SurfaceFlingerBE()
235 : mHwcServiceName(getHwcServiceName()),
236 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800237 mFrameBuckets(),
238 mTotalTime(0),
239 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800240 mComposerSequenceId(0) {
241}
242
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800243SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800244 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800245 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700246 mTransactionPending(false),
247 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700248 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700249 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700250 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800251 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700252 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800253 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800254 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800255 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800256 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700258 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700259 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700260 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700261 mDebugInSwapBuffers(0),
262 mLastSwapBufferTime(0),
263 mDebugInTransaction(0),
264 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700265 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000266 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700267 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700268 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800269 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800270 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700271 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800272 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800273 mCreateBufferQueue(&BufferQueue::createBufferQueue),
274 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800275
276SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800277 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800278
279 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
280 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
281
282 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
283 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
284
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800285 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
286 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800287
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700288 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
289 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
290
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700291 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
292 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
293
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800294 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
295 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
296
Steven Thomas050b2c82017-03-06 11:45:16 -0800297 // Vr flinger is only enabled on Daydream ready devices.
298 useVrFlinger = getBool< ISurfaceFlingerConfigs,
299 &ISurfaceFlingerConfigs::useVrFlinger>(false);
300
Fabien Sanglard1971b632017-03-10 14:50:03 -0800301 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
302 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
303
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600304 hasWideColorDisplay =
305 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
306
Iris Chang7501ed62018-04-30 14:45:42 +0800307 V1_1::DisplayOrientation primaryDisplayOrientation =
308 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
309 V1_1::DisplayOrientation::ORIENTATION_0);
310
311 switch (primaryDisplayOrientation) {
312 case V1_1::DisplayOrientation::ORIENTATION_90:
313 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
314 break;
315 case V1_1::DisplayOrientation::ORIENTATION_180:
316 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
317 break;
318 case V1_1::DisplayOrientation::ORIENTATION_270:
319 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
320 break;
321 default:
322 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
323 break;
324 }
325 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
326
David Sodman99974d22017-11-28 12:04:33 -0800327 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700328
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800329 // debugging stuff...
330 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700331
Mathias Agopianb4b17302013-03-20 18:36:41 -0700332 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700333 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700334
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800335 property_get("debug.sf.showupdates", value, "0");
336 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700337
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700338 property_get("debug.sf.ddms", value, "0");
339 mDebugDDMS = atoi(value);
340 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700341 if (!startDdmConnection()) {
342 // start failed, and DDMS debugging not enabled
343 mDebugDDMS = 0;
344 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700345 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700346 ALOGI_IF(mDebugRegion, "showupdates enabled");
347 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700348
349 property_get("debug.sf.disable_backpressure", value, "0");
350 mPropagateBackpressure = !atoi(value);
351 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700352
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800353 property_get("debug.sf.enable_hwc_vds", value, "0");
354 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800355 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800356
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800357 property_get("ro.sf.disable_triple_buffer", value, "1");
358 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800359 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700360
Yiwei Zhang243b3782018-05-15 17:40:04 -0700361 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700362 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
363 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
364
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200365 property_get("debug.sf.early_phase_offset_ns", value, "-1");
366 const int earlySfOffsetNs = atoi(value);
367
368 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
369 const int earlyGlSfOffsetNs = atoi(value);
370
371 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
372 const int earlyAppOffsetNs = atoi(value);
373
374 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
375 const int earlyGlAppOffsetNs = atoi(value);
376
377 const VSyncModulator::Offsets earlyOffsets =
378 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
379 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
380 const VSyncModulator::Offsets earlyGlOffsets =
381 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
382 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
383 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
384 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700385
Romain Guy11d63f42017-07-20 12:47:14 -0700386 // We should be reading 'persist.sys.sf.color_saturation' here
387 // but since /data may be encrypted, we need to wait until after vold
388 // comes online to attempt to read the property. The property is
389 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800390
391 if (useTrebleTestingOverride()) {
392 // Without the override SurfaceFlinger cannot connect to HIDL
393 // services that are not listed in the manifests. Considered
394 // deriving the setting from the set service name, but it
395 // would be brittle if the name that's not 'default' is used
396 // for production purposes later on.
397 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
398 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800399}
400
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800401void SurfaceFlinger::onFirstRef()
402{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800403 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800404}
405
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800406SurfaceFlinger::~SurfaceFlinger()
407{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800408}
409
Dan Stozac7014012014-02-14 15:03:43 -0800410void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800411{
412 // the window manager died on us. prepare its eulogy.
413
Andy McFadden13a082e2012-08-24 10:16:42 -0700414 // restore initial conditions (default device unblank, etc)
415 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800416
417 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700418 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800419}
420
Robert Carr1db73f62016-12-21 12:58:51 -0800421static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700422 status_t err = client->initCheck();
423 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800424 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800425 }
Robert Carr1db73f62016-12-21 12:58:51 -0800426 return nullptr;
427}
428
429sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
430 return initClient(new Client(this));
431}
432
433sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
434 const sp<IGraphicBufferProducer>& gbp) {
435 if (authenticateSurfaceTexture(gbp) == false) {
436 return nullptr;
437 }
438 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
439 if (layer == nullptr) {
440 return nullptr;
441 }
442
443 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800444}
445
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700446sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
447 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700448{
449 class DisplayToken : public BBinder {
450 sp<SurfaceFlinger> flinger;
451 virtual ~DisplayToken() {
452 // no more references, this display must be terminated
453 Mutex::Autolock _l(flinger->mStateLock);
454 flinger->mCurrentState.displays.removeItem(this);
455 flinger->setTransactionFlags(eDisplayTransactionNeeded);
456 }
457 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700458 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700459 : flinger(flinger) {
460 }
461 };
462
463 sp<BBinder> token = new DisplayToken(this);
464
465 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700466 DisplayDeviceState info;
467 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700468 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700469 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700470 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800471 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700472 return token;
473}
474
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700475void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700476 Mutex::Autolock _l(mStateLock);
477
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700478 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700479 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700480 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700481 return;
482 }
483
484 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700485 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700486 ALOGE("destroyDisplay called for non-virtual display");
487 return;
488 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700489 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700490 mCurrentState.displays.removeItemsAt(idx);
491 setTransactionFlags(eDisplayTransactionNeeded);
492}
493
Mathias Agopiane57f2922012-08-09 16:29:12 -0700494sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700495 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700496 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800497 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700498 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700499 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700500}
501
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800502void SurfaceFlinger::bootFinished()
503{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700504 if (mStartPropertySetThread->join() != NO_ERROR) {
505 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800506 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800507 const nsecs_t now = systemTime();
508 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000509 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700510
511 // wait patiently for the window manager death
512 const String16 name("window");
513 sp<IBinder> window(defaultServiceManager()->getService(name));
514 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700515 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700516 }
517
Steven Thomas050b2c82017-03-06 11:45:16 -0800518 if (mVrFlinger) {
519 mVrFlinger->OnBootFinished();
520 }
521
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700522 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700523 // formerly we would just kill the process, but we now ask it to exit so it
524 // can choose where to stop the animation.
525 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700526
527 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
528 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
529 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700530
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800531 postMessageAsync(new LambdaMessage([this] {
532 readPersistentProperties();
533 mBootStage = BootStage::FINISHED;
534 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800535}
536
Dan Stoza436ccf32018-06-21 12:10:12 -0700537uint32_t SurfaceFlinger::getNewTexture() {
538 {
539 std::lock_guard lock(mTexturePoolMutex);
540 if (!mTexturePool.empty()) {
541 uint32_t name = mTexturePool.back();
542 mTexturePool.pop_back();
543 ATRACE_INT("TexturePoolSize", mTexturePool.size());
544 return name;
545 }
546
547 // The pool was too small, so increase it for the future
548 ++mTexturePoolSize;
549 }
550
551 // The pool was empty, so we need to get a new texture name directly using a
552 // blocking call to the main thread
553 uint32_t name = 0;
554 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
555 return name;
556}
557
Mathias Agopian3f844832013-08-07 21:24:32 -0700558void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700559 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700560}
561
Lloyd Piquee83f9312018-02-01 12:53:17 -0800562class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700563public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700564 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000565 const char* name) :
566 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700567 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700568 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000569 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
570 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700571 mDispSync(dispSync),
572 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700573 mVsyncMutex(),
574 mPhaseOffset(phaseOffset),
575 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700576
Lloyd Piquee83f9312018-02-01 12:53:17 -0800577 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700578
Lloyd Piquee83f9312018-02-01 12:53:17 -0800579 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700580 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700581 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000582 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700583 static_cast<DispSync::Callback*>(this));
584 if (err != NO_ERROR) {
585 ALOGE("error registering vsync callback: %s (%d)",
586 strerror(-err), err);
587 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700588 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700589 } else {
590 status_t err = mDispSync->removeEventListener(
591 static_cast<DispSync::Callback*>(this));
592 if (err != NO_ERROR) {
593 ALOGE("error unregistering vsync callback: %s (%d)",
594 strerror(-err), err);
595 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700596 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700597 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700598 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700599 }
600
Lloyd Piquee83f9312018-02-01 12:53:17 -0800601 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700602 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700603 mCallback = callback;
604 }
605
Lloyd Piquee83f9312018-02-01 12:53:17 -0800606 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700607 Mutex::Autolock lock(mVsyncMutex);
608
609 // Normalize phaseOffset to [0, period)
610 auto period = mDispSync->getPeriod();
611 phaseOffset %= period;
612 if (phaseOffset < 0) {
613 // If we're here, then phaseOffset is in (-period, 0). After this
614 // operation, it will be in (0, period)
615 phaseOffset += period;
616 }
617 mPhaseOffset = phaseOffset;
618
619 // If we're not enabled, we don't need to mess with the listeners
620 if (!mEnabled) {
621 return;
622 }
623
Dan Stoza84d619e2018-03-28 17:07:36 -0700624 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
625 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700626 if (err != NO_ERROR) {
Dan Stoza84d619e2018-03-28 17:07:36 -0700627 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700628 strerror(-err), err);
629 }
630 }
631
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700632private:
633 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800634 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700635 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700636 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700637 callback = mCallback;
638
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700639 if (mTraceVsync) {
640 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700641 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700642 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700643 }
644
Peiyong Lin566a3b42018-01-09 18:22:43 -0800645 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700646 callback->onVSyncEvent(when);
647 }
648 }
649
Tim Murray4a4e4a22016-04-19 16:29:23 +0000650 const char* const mName;
651
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700652 int mValue;
653
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700654 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700655 const String8 mVsyncOnLabel;
656 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700657
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700658 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700659
660 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800661 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700662
663 Mutex mVsyncMutex; // Protects the following
664 nsecs_t mPhaseOffset;
665 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700666};
667
Lloyd Piquee83f9312018-02-01 12:53:17 -0800668class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700669public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800670 InjectVSyncSource() = default;
671 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700672
Lloyd Piquee83f9312018-02-01 12:53:17 -0800673 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700674 std::lock_guard<std::mutex> lock(mCallbackMutex);
675 mCallback = callback;
676 }
677
Lloyd Piquee83f9312018-02-01 12:53:17 -0800678 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700679 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700680 if (mCallback) {
681 mCallback->onVSyncEvent(when);
682 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700683 }
684
Lloyd Piquee83f9312018-02-01 12:53:17 -0800685 void setVSyncEnabled(bool) override {}
686 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700687
688private:
689 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800690 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700691};
692
Wei Wangf9b05ee2017-07-19 20:59:39 -0700693// Do not call property_set on main thread which will be blocked by init
694// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700695void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700696 ALOGI( "SurfaceFlinger's main thread ready to run. "
697 "Initializing graphics H/W...");
698
Thierry Strudel2924d012017-08-14 15:19:37 -0700699 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900700
Steven Thomasb02664d2017-07-26 18:48:28 -0700701 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800702
Steven Thomasb02664d2017-07-26 18:48:28 -0700703 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800704 mEventThreadSource =
705 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
706 true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800707 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700708 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800709 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800710 "appEventThread");
711 mSfEventThreadSource =
712 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
713 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800714
Lloyd Pique24b0a482018-03-09 18:52:26 -0800715 mSFEventThread =
716 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700717 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800718 [this](nsecs_t timestamp) {
719 mInterceptor->saveVSyncEvent(timestamp);
720 },
721 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800722 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200723 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800724
Steven Thomasb02664d2017-07-26 18:48:28 -0700725 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800726 getBE().mRenderEngine =
727 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
728 hasWideColorDisplay
729 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
730 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800731 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700732
733 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
734 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800735 getBE().mHwc.reset(
736 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700737 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800738 // Process any initial hotplug and resulting display changes.
739 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700740 const auto display = getDefaultDisplayDeviceLocked();
741 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
742 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
743 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800744
Lloyd Piquefcd86612017-12-14 17:15:36 -0800745 // make the default display GLContext current so that we can create textures
746 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700747 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800748
Steven Thomas050b2c82017-03-06 11:45:16 -0800749 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700750 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700751 // This callback is called from the vr flinger dispatch thread. We
752 // need to call signalTransaction(), which requires holding
753 // mStateLock when we're not on the main thread. Acquiring
754 // mStateLock from the vr flinger dispatch thread might trigger a
755 // deadlock in surface flinger (see b/66916578), so post a message
756 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700757 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700758 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
759 mVrFlingerRequestsDisplay = requestDisplay;
760 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700761 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800762 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700763 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
764 getHwComposer()
765 .getHwcDisplayId(display->getId())
766 .value_or(0),
767 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800768 if (!mVrFlinger) {
769 ALOGE("Failed to start vrflinger");
770 }
771 }
772
Lloyd Pique379adc12018-01-22 17:31:47 -0800773 mEventControlThread = std::make_unique<impl::EventControlThread>(
774 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700775
Mathias Agopian92a979a2012-08-02 18:32:23 -0700776 // initialize our drawing state
777 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700778
Andy McFadden13a082e2012-08-24 10:16:42 -0700779 // set initial conditions (e.g. unblank default device)
780 initializeDisplays();
781
David Sodmanbc815282017-11-05 18:57:52 -0800782 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700783
Wei Wangf9b05ee2017-07-19 20:59:39 -0700784 // Inform native graphics APIs whether the present timestamp is supported:
785 if (getHwComposer().hasCapability(
786 HWC2::Capability::PresentFenceIsNotReliable)) {
787 mStartPropertySetThread = new StartPropertySetThread(false);
788 } else {
789 mStartPropertySetThread = new StartPropertySetThread(true);
790 }
791
792 if (mStartPropertySetThread->Start() != NO_ERROR) {
793 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800794 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800795
Chia-I Wud49d6692018-06-27 07:17:41 +0800796 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
797 // is used to saturate legacy sRGB content. However, to make sure the same color under
798 // Display P3 will be saturated to the same color, we intentionally break the API spec
799 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
800 // such saturation matrix on Display P3 is understood fully, the API should always return
801 // identify matrix.
802 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
803 Dataspace::SRGB_LINEAR);
804
805 // we will apply this on Display P3.
806 if (mEnhancedSaturationMatrix != mat4()) {
807 ColorSpace srgb(ColorSpace::sRGB());
808 ColorSpace displayP3(ColorSpace::DisplayP3());
809 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
810 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
811 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
812 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800813
Dan Stoza9e56aa02015-11-02 13:00:03 -0800814 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700815}
816
Romain Guy11d63f42017-07-20 12:47:14 -0700817void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700818 Mutex::Autolock _l(mStateLock);
819
Romain Guy11d63f42017-07-20 12:47:14 -0700820 char value[PROPERTY_VALUE_MAX];
821
822 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800823 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700824 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800825 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100826
827 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700828 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700829}
830
Mathias Agopiana67e4182012-06-19 17:26:12 -0700831void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800832 // Start boot animation service by setting a property mailbox
833 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700834 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800835 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700836 if (mStartPropertySetThread->join() != NO_ERROR) {
837 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800838 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700839}
840
Mathias Agopian875d8e12013-06-07 15:35:48 -0700841size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800842 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700843}
844
Mathias Agopian875d8e12013-06-07 15:35:48 -0700845size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800846 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700847}
848
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800849// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800850
Jamie Gennis582270d2011-08-17 18:19:00 -0700851bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800852 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800853 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800854 return authenticateSurfaceTextureLocked(bufferProducer);
855}
856
857bool SurfaceFlinger::authenticateSurfaceTextureLocked(
858 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800859 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800860 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800861}
862
Brian Anderson6b376712017-04-04 10:51:39 -0700863status_t SurfaceFlinger::getSupportedFrameTimestamps(
864 std::vector<FrameEvent>* outSupported) const {
865 *outSupported = {
866 FrameEvent::REQUESTED_PRESENT,
867 FrameEvent::ACQUIRE,
868 FrameEvent::LATCH,
869 FrameEvent::FIRST_REFRESH_START,
870 FrameEvent::LAST_REFRESH_START,
871 FrameEvent::GPU_COMPOSITION_DONE,
872 FrameEvent::DEQUEUE_READY,
873 FrameEvent::RELEASE,
874 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700875 ConditionalLock _l(mStateLock,
876 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700877 if (!getHwComposer().hasCapability(
878 HWC2::Capability::PresentFenceIsNotReliable)) {
879 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
880 }
881 return NO_ERROR;
882}
883
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700884status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
885 Vector<DisplayInfo>* configs) {
886 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700887 return BAD_VALUE;
888 }
889
Jesse Hall692c7232012-11-08 15:41:56 -0800890 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700891 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
892 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700893 type = i;
894 break;
895 }
896 }
897
898 if (type < 0) {
899 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700900 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700901
Mathias Agopian8b736f12012-08-13 17:54:26 -0700902 // TODO: Not sure if display density should handled by SF any longer
903 class Density {
904 static int getDensityFromProperty(char const* propName) {
905 char property[PROPERTY_VALUE_MAX];
906 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800907 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700908 density = atoi(property);
909 }
910 return density;
911 }
912 public:
913 static int getEmuDensity() {
914 return getDensityFromProperty("qemu.sf.lcd_density"); }
915 static int getBuildDensity() {
916 return getDensityFromProperty("ro.sf.lcd_density"); }
917 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700918
Dan Stoza7f7da322014-05-02 15:26:25 -0700919 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700920
Steven Thomas6d8110b2017-08-31 18:24:21 -0700921 ConditionalLock _l(mStateLock,
922 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800923 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700924 DisplayInfo info = DisplayInfo();
925
Dan Stoza9e56aa02015-11-02 13:00:03 -0800926 float xdpi = hwConfig->getDpiX();
927 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700928
929 if (type == DisplayDevice::DISPLAY_PRIMARY) {
930 // The density of the device is provided by a build property
931 float density = Density::getBuildDensity() / 160.0f;
932 if (density == 0) {
933 // the build doesn't provide a density -- this is wrong!
934 // use xdpi instead
935 ALOGE("ro.sf.lcd_density must be defined as a build property");
936 density = xdpi / 160.0f;
937 }
938 if (Density::getEmuDensity()) {
939 // if "qemu.sf.lcd_density" is specified, it overrides everything
940 xdpi = ydpi = density = Density::getEmuDensity();
941 density /= 160.0f;
942 }
943 info.density = density;
944
945 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700946 const auto display = getDefaultDisplayDeviceLocked();
947 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700948 } else {
949 // TODO: where should this value come from?
950 static const int TV_DENSITY = 213;
951 info.density = TV_DENSITY / 160.0f;
952 info.orientation = 0;
953 }
954
Dan Stoza9e56aa02015-11-02 13:00:03 -0800955 info.w = hwConfig->getWidth();
956 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700957 info.xdpi = xdpi;
958 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800959 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900960 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800961
Andy McFadden91b2ca82014-06-13 14:04:23 -0700962 // This is how far in advance a buffer must be queued for
963 // presentation at a given time. If you want a buffer to appear
964 // on the screen at time N, you must submit the buffer before
965 // (N - presentationDeadline).
966 //
967 // Normally it's one full refresh period (to give SF a chance to
968 // latch the buffer), but this can be reduced by configuring a
969 // DispSync offset. Any additional delays introduced by the hardware
970 // composer or panel must be accounted for here.
971 //
972 // We add an additional 1ms to allow for processing time and
973 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800974 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800975 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700976
977 // All non-virtual displays are currently considered secure.
978 info.secure = true;
979
Iris Chang7501ed62018-04-30 14:45:42 +0800980 if (type == DisplayDevice::DISPLAY_PRIMARY &&
981 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
982 std::swap(info.w, info.h);
983 }
984
Michael Wright28f24d02016-07-12 13:30:53 -0700985 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700986 }
987
Dan Stoza7f7da322014-05-02 15:26:25 -0700988 return NO_ERROR;
989}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700990
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700991status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
992 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700993 return BAD_VALUE;
994 }
995
996 // FIXME for now we always return stats for the primary display
997 memset(stats, 0, sizeof(*stats));
998 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
999 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
1000 return NO_ERROR;
1001}
1002
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001003int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
1004 const auto display = getDisplayDevice(displayToken);
1005 if (!display) {
1006 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +08001007 return BAD_VALUE;
1008 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001009
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001010 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -07001011}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001012
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001013void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
1014 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001015 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001016 return;
1017 }
1018
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001019 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001020 ALOGW("Trying to set config for virtual display");
1021 return;
1022 }
1023
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001024 display->setActiveConfig(mode);
1025 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001026}
1027
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001028status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001029 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001030 Vector<DisplayInfo> configs;
1031 getDisplayConfigs(displayToken, &configs);
1032 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
1033 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
1034 configs.size());
1035 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001036 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001037 const auto display = getDisplayDevice(displayToken);
1038 if (!display) {
1039 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
1040 displayToken.get());
1041 } else if (display->isVirtual()) {
1042 ALOGW("Attempt to set active config %d for virtual display", mode);
1043 } else {
1044 setActiveConfigInternal(display, mode);
1045 }
1046 }));
1047
Mathias Agopian888c8222012-08-04 21:10:38 -07001048 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001049}
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001050status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1051 Vector<ColorMode>* outColorModes) {
1052 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001053 return BAD_VALUE;
1054 }
1055
Michael Wright28f24d02016-07-12 13:30:53 -07001056 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001057 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
1058 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -07001059 type = i;
1060 break;
1061 }
1062 }
1063
1064 if (type < 0) {
1065 return type;
1066 }
1067
Peiyong Lina52f0292018-03-14 17:26:31 -07001068 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001069 {
1070 ConditionalLock _l(mStateLock,
1071 std::this_thread::get_id() != mMainThreadId);
1072 modes = getHwComposer().getColorModes(type);
1073 }
Michael Wright28f24d02016-07-12 13:30:53 -07001074 outColorModes->clear();
1075 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1076
1077 return NO_ERROR;
1078}
1079
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001080ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1081 if (const auto display = getDisplayDevice(displayToken)) {
1082 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001083 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001084 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001085}
1086
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001087void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1088 Dataspace dataSpace, RenderIntent renderIntent) {
1089 ColorMode currentMode = display->getActiveColorMode();
1090 Dataspace currentDataSpace = display->getCompositionDataSpace();
1091 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001092
Peiyong Lin38e9a562018-04-10 16:24:20 -07001093 if (mode == currentMode && dataSpace == currentDataSpace &&
1094 renderIntent == currentRenderIntent) {
1095 return;
1096 }
1097
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001098 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001099 ALOGW("Trying to set config for virtual display");
1100 return;
1101 }
1102
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001103 display->setActiveColorMode(mode);
1104 display->setCompositionDataSpace(dataSpace);
1105 display->setActiveRenderIntent(renderIntent);
1106 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001107
1108 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001109 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1110 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001111}
1112
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001113status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001114 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001115 Vector<ColorMode> modes;
1116 getDisplayColorModes(displayToken, &modes);
1117 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1118 if (mode < ColorMode::NATIVE || !exists) {
1119 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1120 decodeColorMode(mode).c_str(), mode, displayToken.get());
1121 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001122 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001123 const auto display = getDisplayDevice(displayToken);
1124 if (!display) {
1125 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1126 decodeColorMode(mode).c_str(), mode, displayToken.get());
1127 } else if (display->isVirtual()) {
1128 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1129 decodeColorMode(mode).c_str(), mode);
1130 } else {
1131 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1132 RenderIntent::COLORIMETRIC);
1133 }
1134 }));
1135
Michael Wright28f24d02016-07-12 13:30:53 -07001136 return NO_ERROR;
1137}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001138
Svetoslavd85084b2014-03-20 10:28:31 -07001139status_t SurfaceFlinger::clearAnimationFrameStats() {
1140 Mutex::Autolock _l(mStateLock);
1141 mAnimFrameTracker.clearStats();
1142 return NO_ERROR;
1143}
1144
1145status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1146 Mutex::Autolock _l(mStateLock);
1147 mAnimFrameTracker.getStats(outStats);
1148 return NO_ERROR;
1149}
1150
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001151status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1152 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001153 Mutex::Autolock _l(mStateLock);
1154
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001155 const auto display = getDisplayDeviceLocked(displayToken);
1156 if (!display) {
1157 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001158 return BAD_VALUE;
1159 }
1160
Peiyong Linfb069302018-04-25 14:34:31 -07001161 // At this point the DisplayDeivce should already be set up,
1162 // meaning the luminance information is already queried from
1163 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001164 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001165 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1166 capabilities.getDesiredMaxLuminance(),
1167 capabilities.getDesiredMaxAverageLuminance(),
1168 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001169
1170 return NO_ERROR;
1171}
1172
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001173status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001174 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001175 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001176
Chia-I Wu90f669f2017-10-05 14:24:41 -07001177 if (mInjectVSyncs == enable) {
1178 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001179 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001180
1181 if (enable) {
1182 ALOGV("VSync Injections enabled");
1183 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001184 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001185 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001186 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001187 impl::EventThread::InterceptVSyncsCallback(),
1188 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001189 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001190 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001191 } else {
1192 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001193 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001194 }
1195
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001196 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001197 }));
1198
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001199 return NO_ERROR;
1200}
1201
1202status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001203 Mutex::Autolock _l(mStateLock);
1204
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001205 if (!mInjectVSyncs) {
1206 ALOGE("VSync Injections not enabled");
1207 return BAD_VALUE;
1208 }
1209 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1210 ALOGV("Injecting VSync inside SurfaceFlinger");
1211 mVSyncInjector->onInjectSyncEvent(when);
1212 }
1213 return NO_ERROR;
1214}
1215
Lloyd Pique755e3192018-01-31 16:46:15 -08001216status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1217 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001218 IPCThreadState* ipc = IPCThreadState::self();
1219 const int pid = ipc->getCallingPid();
1220 const int uid = ipc->getCallingUid();
1221 if ((uid != AID_SHELL) &&
1222 !PermissionCache::checkPermission(sDump, pid, uid)) {
1223 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1224 return PERMISSION_DENIED;
1225 }
1226
1227 // Try to acquire a lock for 1s, fail gracefully
1228 const status_t err = mStateLock.timedLock(s2ns(1));
1229 const bool locked = (err == NO_ERROR);
1230 if (!locked) {
1231 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1232 return TIMED_OUT;
1233 }
1234
1235 outLayers->clear();
1236 mCurrentState.traverseInZOrder([&](Layer* layer) {
1237 outLayers->push_back(layer->getLayerDebugInfo());
1238 });
1239
1240 mStateLock.unlock();
1241 return NO_ERROR;
1242}
1243
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001244// ----------------------------------------------------------------------------
1245
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001246sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1247 ISurfaceComposer::VsyncSource vsyncSource) {
1248 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1249 return mSFEventThread->createEventConnection();
1250 } else {
1251 return mEventThread->createEventConnection();
1252 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001253}
1254
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001255// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001256
1257void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001258 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001259}
1260
1261void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001262 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001263}
1264
1265void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001266 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001267}
1268
1269void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001270 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001271 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001272}
1273
1274status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001275 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001276 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001277}
1278
1279status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001280 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001281 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001282 if (res == NO_ERROR) {
1283 msg->wait();
1284 }
1285 return res;
1286}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001287
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001288void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001289 do {
1290 waitForEvent();
1291 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001292}
1293
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001294void SurfaceFlinger::enableHardwareVsync() {
1295 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001296 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001297 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001298 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001299 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001300 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001301}
1302
Jesse Hall948fe0c2013-10-14 12:56:09 -07001303void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001304 Mutex::Autolock _l(mHWVsyncLock);
1305
Jesse Hall948fe0c2013-10-14 12:56:09 -07001306 if (makeAvailable) {
1307 mHWVsyncAvailable = true;
1308 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001309 // Hardware vsync is not currently available, so abort the resync
1310 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001311 return;
1312 }
1313
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001314 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1315 if (!getHwComposer().isConnected(displayId)) {
1316 return;
1317 }
1318
1319 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001320 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001321
1322 mPrimaryDispSync.reset();
1323 mPrimaryDispSync.setPeriod(period);
1324
1325 if (!mPrimaryHWVsyncEnabled) {
1326 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001327 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001328 mPrimaryHWVsyncEnabled = true;
1329 }
1330}
1331
Jesse Hall948fe0c2013-10-14 12:56:09 -07001332void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001333 Mutex::Autolock _l(mHWVsyncLock);
1334 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001335 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001336 mPrimaryDispSync.endResync();
1337 mPrimaryHWVsyncEnabled = false;
1338 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001339 if (makeUnavailable) {
1340 mHWVsyncAvailable = false;
1341 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001342}
1343
Tim Murray4a4e4a22016-04-19 16:29:23 +00001344void SurfaceFlinger::resyncWithRateLimit() {
1345 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001346
1347 // No explicit locking is needed here since EventThread holds a lock while calling this method
1348 static nsecs_t sLastResyncAttempted = 0;
1349 const nsecs_t now = systemTime();
1350 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001351 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001352 }
Dan Stoza57164302017-05-08 14:03:54 -07001353 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001354}
1355
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001356void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1357 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001358 ATRACE_NAME("SF onVsync");
1359
Steven Thomas3cfac282017-02-06 12:29:30 -08001360 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001361 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001362 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001363 return;
1364 }
1365
1366 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001367 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001368 return;
1369 }
1370
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001371 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1372 // For now, we don't do anything with external display vsyncs.
1373 return;
1374 }
1375
Jamie Gennisd1700752013-10-14 12:22:52 -07001376 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001377
Jamie Gennisd1700752013-10-14 12:22:52 -07001378 { // Scope for the lock
1379 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001380 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001381 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001382 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001383 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001384
1385 if (needsHwVsync) {
1386 enableHardwareVsync();
1387 } else {
1388 disableHardwareVsync(false);
1389 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001390}
1391
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001392void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001393 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1394 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001395}
1396
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001397void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001398 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001399 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001400 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001401
Lloyd Piqueba04e622017-12-14 17:11:26 -08001402 // Ignore events that do not have the right sequenceId.
1403 if (sequenceId != getBE().mComposerSequenceId) {
1404 return;
1405 }
1406
Steven Thomasb02664d2017-07-26 18:48:28 -07001407 // Only lock if we're not on the main thread. This function is normally
1408 // called on a hwbinder thread, but for the primary display it's called on
1409 // the main thread with the state lock already held, so don't attempt to
1410 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001411 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001412
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001413 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001414
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001415 if (std::this_thread::get_id() == mMainThreadId) {
1416 // Process all pending hot plug events immediately if we are on the main thread.
1417 processDisplayHotplugEventsLocked();
1418 }
1419
Lloyd Piqueba04e622017-12-14 17:11:26 -08001420 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001421}
1422
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001423void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001424 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001425 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001426 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001427 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001428 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001429}
1430
Dan Stoza9e56aa02015-11-02 13:00:03 -08001431void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001432 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001433 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001434 getHwComposer().setVsyncEnabled(disp,
1435 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001436}
1437
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001438// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001439void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001440 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001441 // Clear the drawing state so that the logic inside of
1442 // handleTransactionLocked will fire. It will determine the delta between
1443 // mCurrentState and mDrawingState and re-apply all changes when we make the
1444 // transition.
1445 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001446 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001447 mDisplays.clear();
1448}
1449
Steven Thomas050b2c82017-03-06 11:45:16 -08001450void SurfaceFlinger::updateVrFlinger() {
1451 if (!mVrFlinger)
1452 return;
1453 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001454 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001455 return;
1456 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001457
David Sodman105b7dc2017-11-04 20:28:14 -07001458 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001459 ALOGE("Vr flinger is only supported for remote hardware composer"
1460 " service connections. Ignoring request to transition to vr"
1461 " flinger.");
1462 mVrFlingerRequestsDisplay = false;
1463 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001464 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001465
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001466 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001467
Steven Thomas0123ac62018-07-12 11:32:34 -07001468 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001469 LOG_ALWAYS_FATAL_IF(!display);
1470 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001471 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1472 // called below. Clear the reference now so we don't accidentally use it
1473 // later.
1474 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001475
Steven Thomasb02664d2017-07-26 18:48:28 -07001476 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001477 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001478 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001479
Steven Thomasb02664d2017-07-26 18:48:28 -07001480 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001481 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001482 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1483 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001484 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001485
David Sodman105b7dc2017-11-04 20:28:14 -07001486 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1487 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001488
1489 if (vrFlingerRequestsDisplay) {
1490 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001491 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001492
1493 mVisibleRegionsDirty = true;
1494 invalidateHwcGeometry();
1495
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001496 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001497 display = getDefaultDisplayDeviceLocked();
1498 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001499 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001500
Steven Thomasb02664d2017-07-26 18:48:28 -07001501 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001502 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001503 const nsecs_t period = activeConfig->getVsyncPeriod();
1504 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001505
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001506 // The present fences returned from vr_hwc are not an accurate
1507 // representation of vsync times.
1508 mPrimaryDispSync.setIgnorePresentFences(
1509 getBE().mHwc->isUsingVrComposer() || !hasSyncFramework);
1510
Steven Thomasb02664d2017-07-26 18:48:28 -07001511 // Use phase of 0 since phase is not known.
1512 // Use latency of 0, which will snap to the ideal latency.
1513 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001514
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001515 resyncToHardwareVsync(false);
1516
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001517 android_atomic_or(1, &mRepaintEverything);
1518 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001519}
1520
Mathias Agopian4fec8732012-06-29 14:12:52 -07001521void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001522 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001523 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001524 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001525 bool frameMissed = !mHadClientComposition &&
1526 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001527 (mPreviousPresentFence->getSignalTime() ==
1528 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001529 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001530 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001531 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001532 mTimeStats.incrementMissedFrames();
1533 if (mPropagateBackpressure) {
1534 signalLayerUpdate();
1535 break;
1536 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001537 }
Dan Stoza50182882016-07-08 12:02:20 -07001538
Steven Thomas050b2c82017-03-06 11:45:16 -08001539 // Now that we're going to make it to the handleMessageTransaction()
1540 // call below it's safe to call updateVrFlinger(), which will
1541 // potentially trigger a display handoff.
1542 updateVrFlinger();
1543
Dan Stoza6b9454d2014-11-07 16:00:59 -08001544 bool refreshNeeded = handleMessageTransaction();
1545 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001546 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001547 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001548 // Signal a refresh if a transaction modified the window state,
1549 // a new buffer was latched, or if HWC has requested a full
1550 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001551 signalRefresh();
1552 }
1553 break;
1554 }
1555 case MessageQueue::REFRESH: {
1556 handleMessageRefresh();
1557 break;
1558 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001559 }
1560}
1561
Dan Stoza6b9454d2014-11-07 16:00:59 -08001562bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001563 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001564 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001565 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001566 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001567 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001568 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001569}
1570
Dan Stoza6b9454d2014-11-07 16:00:59 -08001571bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001572 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001573 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001574}
1575
1576void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001577 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001578
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001579 mRefreshPending = false;
1580
Lloyd Pique074e8122018-07-26 12:57:23 -07001581 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1582
1583 preComposition(refreshStartTime);
1584 rebuildLayerStacks();
1585 setUpHWComposer();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001586 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001587 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001588 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001589 doComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001590 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001591
Dan Stozabfbffeb2016-07-21 14:49:33 -07001592 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001593 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001594 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001595 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001596 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001597 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001598
Dan Stoza9e56aa02015-11-02 13:00:03 -08001599 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001600}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001601
Mathias Agopiancd60f992012-08-16 16:28:27 -07001602void SurfaceFlinger::doDebugFlashRegions()
1603{
1604 // is debugging enabled
1605 if (CC_LIKELY(!mDebugRegion))
1606 return;
1607
1608 const bool repaintEverything = mRepaintEverything;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001609 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001610 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001611 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001612 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001613 if (!dirtyRegion.isEmpty()) {
1614 // redraw the whole screen
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001615 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001616
1617 // and draw the dirty region
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001618 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001619 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001620 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1621
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001622 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001623 }
1624 }
1625 }
1626
1627 postFramebuffer();
1628
1629 if (mDebugRegion > 1) {
1630 usleep(mDebugRegion * 1000);
1631 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001632
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001633 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001634 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001635 continue;
1636 }
1637
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001638 status_t result = display->prepareFrame(*getBE().mHwc);
1639 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001640 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001641 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001642}
1643
Adrian Roos1e1a1282017-11-01 19:05:31 +01001644void SurfaceFlinger::doTracing(const char* where) {
1645 ATRACE_CALL();
1646 ATRACE_NAME(where);
1647 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001648 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001649 }
1650}
1651
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001652void SurfaceFlinger::logLayerStats() {
1653 ATRACE_CALL();
1654 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001655 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001656 if (display->isPrimary()) {
1657 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001658 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001659 }
1660 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001661
1662 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001663 }
1664}
1665
Lloyd Pique074e8122018-07-26 12:57:23 -07001666void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001667{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001668 ATRACE_CALL();
1669 ALOGV("preComposition");
1670
Mathias Agopiancd60f992012-08-16 16:28:27 -07001671 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001672 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique074e8122018-07-26 12:57:23 -07001673 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001674 needExtraInvalidate = true;
1675 }
Robert Carr2047fae2016-11-28 14:09:09 -08001676 });
1677
Mathias Agopiancd60f992012-08-16 16:28:27 -07001678 if (needExtraInvalidate) {
1679 signalLayerUpdate();
1680 }
1681}
1682
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001683void SurfaceFlinger::updateCompositorTiming(
1684 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1685 std::shared_ptr<FenceTime>& presentFenceTime) {
1686 // Update queue of past composite+present times and determine the
1687 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001688 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001689 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001690 while (!getBE().mCompositePresentTimes.empty()) {
1691 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001692 // Cached values should have been updated before calling this method,
1693 // which helps avoid duplicate syscalls.
1694 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1695 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1696 break;
1697 }
1698 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001699 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001700 }
1701
1702 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001703 while (getBE().mCompositePresentTimes.size() > 16) {
1704 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001705 }
1706
Brian Andersond0010582017-03-07 13:20:31 -08001707 setCompositorTimingSnapped(
1708 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1709}
1710
1711void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1712 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001713 // Integer division and modulo round toward 0 not -inf, so we need to
1714 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001715 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001716 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1717 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1718
Brian Andersond0010582017-03-07 13:20:31 -08001719 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1720 if (idealLatency <= 0) {
1721 idealLatency = vsyncInterval;
1722 }
1723
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001724 // Snap the latency to a value that removes scheduling jitter from the
1725 // composition and present times, which often have >1ms of jitter.
1726 // Reducing jitter is important if an app attempts to extrapolate
1727 // something (such as user input) to an accurate diasplay time.
1728 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1729 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001730 nsecs_t bias = vsyncInterval / 2;
1731 int64_t extraVsyncs =
1732 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1733 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1734 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001735
David Sodman99974d22017-11-28 12:04:33 -08001736 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1737 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1738 getBE().mCompositorTiming.interval = vsyncInterval;
1739 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001740}
1741
Lloyd Pique074e8122018-07-26 12:57:23 -07001742void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001743{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001744 ATRACE_CALL();
1745 ALOGV("postComposition");
1746
Brian Anderson3546a3f2016-07-14 11:51:14 -07001747 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001748 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001749 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001750 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001751 }
1752
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001753 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001754 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001755
David Sodman73beded2017-11-15 11:56:06 -08001756 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001757 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001758 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001759 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001760 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001761 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001762 } else {
1763 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1764 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001765
David Sodman73beded2017-11-15 11:56:06 -08001766 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001767 mPreviousPresentFence =
1768 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1769 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001770 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001771
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001772 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1773 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1774
Lloyd Pique074e8122018-07-26 12:57:23 -07001775 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001776 // when we started doing work for this frame, but that should be okay
1777 // since updateCompositorTiming has snapping logic.
1778 updateCompositorTiming(
Lloyd Pique074e8122018-07-26 12:57:23 -07001779 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001780 CompositorTiming compositorTiming;
1781 {
David Sodman99974d22017-11-28 12:04:33 -08001782 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1783 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001784 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001785
Robert Carr2047fae2016-11-28 14:09:09 -08001786 mDrawingState.traverseInZOrder([&](Layer* layer) {
1787 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001788 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001789 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001790 recordBufferingStats(layer->getName().string(),
1791 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001792 }
Robert Carr2047fae2016-11-28 14:09:09 -08001793 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001794
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001795 if (presentFenceTime->isValid()) {
1796 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001797 enableHardwareVsync();
1798 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001799 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001800 }
1801 }
1802
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001803 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001804 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001805 enableHardwareVsync();
1806 }
1807 }
1808
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001809 if (mAnimCompositionPending) {
1810 mAnimCompositionPending = false;
1811
Brian Anderson4e606e32017-03-16 15:34:57 -07001812 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001813 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001814 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001815 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001816 // The HWC doesn't support present fences, so use the refresh
1817 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001818 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001819 mAnimFrameTracker.setActualPresentTime(presentTime);
1820 }
1821 mAnimFrameTracker.advanceFrame();
1822 }
Dan Stozab90cf072015-03-05 11:05:59 -08001823
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001824 mTimeStats.incrementTotalFrames();
1825 if (mHadClientComposition) {
1826 mTimeStats.incrementClientCompositionFrames();
1827 }
1828
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001829 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001830 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001831 return;
1832 }
1833
1834 nsecs_t currentTime = systemTime();
1835 if (mHasPoweredOff) {
1836 mHasPoweredOff = false;
1837 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001838 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001839 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001840 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1841 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001842 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001843 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001844 }
David Sodman4a36e932017-11-07 14:29:47 -08001845 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001846 }
David Sodman4a36e932017-11-07 14:29:47 -08001847 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001848
1849 {
1850 std::lock_guard lock(mTexturePoolMutex);
1851 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1852 if (refillCount > 0) {
1853 const size_t offset = mTexturePool.size();
1854 mTexturePool.resize(mTexturePoolSize);
1855 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1856 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1857 }
1858 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001859}
1860
1861void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001862 ATRACE_CALL();
1863 ALOGV("rebuildLayerStacks");
1864
Mathias Agopiancd60f992012-08-16 16:28:27 -07001865 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001866 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001867 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001868 mVisibleRegionsDirty = false;
1869 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001870
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001871 for (const auto& pair : mDisplays) {
1872 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001873 Region opaqueRegion;
1874 Region dirtyRegion;
1875 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001876 Vector<sp<Layer>> layersNeedingFences;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001877 const Transform& tr = display->getTransform();
1878 const Rect bounds = display->getBounds();
1879 if (display->isPoweredOn()) {
1880 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001881
Jeff Sharkey76488112017-02-27 14:15:18 -07001882 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001883 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001884 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001885 Region drawRegion(tr.transform(
1886 layer->visibleNonTransparentRegion));
1887 drawRegion.andSelf(bounds);
1888 if (!drawRegion.isEmpty()) {
1889 layersSortedByZ.add(layer);
1890 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001891 // Clear out the HWC layer if this layer was
1892 // previously visible, but no longer is
1893 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001894 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001895 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001896 // WM changes display->layerStack upon sleep/awake.
1897 // Here we make sure we delete the HWC layers even if
1898 // WM changed their layer stack.
1899 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001900 }
1901
1902 // If a layer is not going to get a release fence because
1903 // it is invisible, but it is also going to release its
1904 // old buffer, add it to the list of layers needing
1905 // fences.
1906 if (hwcLayerDestroyed) {
1907 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1908 mLayersWithQueuedFrames.cend(), layer);
1909 if (found != mLayersWithQueuedFrames.cend()) {
1910 layersNeedingFences.add(layer);
1911 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001912 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001913 });
1914 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001915 display->setVisibleLayersSortedByZ(layersSortedByZ);
1916 display->setLayersNeedingFences(layersNeedingFences);
1917 display->undefinedRegion.set(bounds);
1918 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1919 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001920 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001921 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001922}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001923
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001924// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001925// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001926// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001927// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001928// The returned HDR data space is one of
1929// - Dataspace::UNKNOWN
1930// - Dataspace::BT2020_HLG
1931// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001932Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1933 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001934 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001935 *outHdrDataSpace = Dataspace::UNKNOWN;
1936
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001937 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001938 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001939 case Dataspace::V0_SCRGB:
1940 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001941 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001942 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001943 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001944 case Dataspace::BT2020_PQ:
1945 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001946 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001947 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001948 case Dataspace::BT2020_HLG:
1949 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001950 // When there's mixed PQ content and HLG content, we set the HDR
1951 // data space to be BT2020_PQ and convert HLG to PQ.
1952 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1953 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001954 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001955 break;
1956 default:
1957 break;
1958 }
Romain Guy54f154a2017-10-24 21:40:32 +01001959 }
1960
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001961 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001962}
1963
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001964// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001965void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1966 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001967 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1968 *outMode = ColorMode::NATIVE;
1969 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001970 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001971 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001972 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001973
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001974 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001975 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001976
Peiyong Lindfde5112018-06-05 10:58:41 -07001977 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001978 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001979 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001980 if (isHdr) {
1981 bestDataSpace = hdrDataSpace;
1982 }
1983
Chia-I Wu0d711262018-05-21 15:19:35 -07001984 RenderIntent intent;
1985 switch (mDisplayColorSetting) {
1986 case DisplayColorSetting::MANAGED:
1987 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001988 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001989 break;
1990 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001991 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001992 break;
1993 default: // vendor display color setting
1994 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1995 break;
1996 }
Chia-I Wube02ec02018-05-18 10:59:36 -07001997
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001998 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001999}
2000
Lloyd Pique074e8122018-07-26 12:57:23 -07002001void SurfaceFlinger::setUpHWComposer() {
2002 ATRACE_CALL();
2003 ALOGV("setUpHWComposer");
Lloyd Piqueb7d12302018-07-26 12:56:47 -07002004
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002005 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002006 bool dirty = !display->getDirtyRegion(mRepaintEverything).isEmpty();
2007 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2008 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
Jesse Hallb7a05492014-08-14 15:45:06 -07002009
2010 // If nothing has changed (!dirty), don't recompose.
2011 // If something changed, but we don't currently have any visible layers,
2012 // and didn't when we last did a composition, then skip it this time.
2013 // The second rule does two things:
2014 // - When all layers are removed from a display, we'll emit one black
2015 // frame, then nothing more until we get new layers.
2016 // - When a display is created with a private layer stack, we won't
2017 // emit any black frames until a layer is added to the layer stack.
2018 bool mustRecompose = dirty && !(empty && wasEmpty);
2019
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002020 ALOGV_IF(display->isVirtual(), "Display %d: %s composition (%sdirty %sempty %swasEmpty)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002021 display->getId(), mustRecompose ? "doing" : "skipping", dirty ? "+" : "-",
2022 empty ? "+" : "-", wasEmpty ? "+" : "-");
Jesse Hallb7a05492014-08-14 15:45:06 -07002023
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002024 display->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07002025
2026 if (mustRecompose) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002027 display->lastCompositionHadVisibleLayers = !empty;
Jesse Hallb7a05492014-08-14 15:45:06 -07002028 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07002029 }
2030
Lloyd Pique074e8122018-07-26 12:57:23 -07002031 // build the h/w work list
2032 if (CC_UNLIKELY(mGeometryInvalid)) {
2033 mGeometryInvalid = false;
2034 for (const auto& [token, display] : mDisplays) {
2035 const auto displayId = display->getId();
2036 if (displayId >= 0) {
2037 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
2038 for (size_t i = 0; i < currentLayers.size(); i++) {
2039 const auto& layer = currentLayers[i];
2040 if (!layer->hasHwcLayer(displayId)) {
2041 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
2042 layer->forceClientComposition(displayId);
2043 continue;
2044 }
2045 }
2046
2047 layer->setGeometry(display, i);
2048 if (mDebugDisableHWC || mDebugRegion) {
2049 layer->forceClientComposition(displayId);
2050 }
2051 }
2052 }
2053 }
2054 }
2055
2056 // Set the per-frame data
2057 for (const auto& [token, display] : mDisplays) {
2058 const auto displayId = display->getId();
2059 if (displayId < 0) {
2060 continue;
2061 }
2062
2063 if (mDrawingState.colorMatrixChanged) {
2064 display->setColorTransform(mDrawingState.colorMatrix);
2065 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
2066 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %d: %d",
2067 displayId, result);
2068 }
2069 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2070 if (layer->isHdrY410()) {
2071 layer->forceClientComposition(displayId);
2072 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2073 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
2074 !display->hasHDR10Support()) {
2075 layer->forceClientComposition(displayId);
2076 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2077 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
2078 !display->hasHLGSupport()) {
2079 layer->forceClientComposition(displayId);
2080 }
2081
2082 if (layer->getForceClientComposition(displayId)) {
2083 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2084 layer->setCompositionType(displayId, HWC2::Composition::Client);
2085 continue;
2086 }
2087
2088 layer->setPerFrameData(display);
2089 }
2090
2091 if (hasWideColorDisplay) {
2092 ColorMode colorMode;
2093 Dataspace dataSpace;
2094 RenderIntent renderIntent;
2095 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
2096 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
2097 }
2098 }
2099
2100 mDrawingState.colorMatrixChanged = false;
2101
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002102 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002103 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002104 continue;
2105 }
2106
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002107 status_t result = display->prepareFrame(*getBE().mHwc);
2108 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002109 display->getId(), result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002110 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002111}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002112
Mathias Agopiancd60f992012-08-16 16:28:27 -07002113void SurfaceFlinger::doComposition() {
2114 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002115 ALOGV("doComposition");
2116
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002117 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002118 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002119 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002120 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002121 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002122
2123 // repaint the framebuffer (if needed)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002124 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002125
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002126 display->dirtyRegion.clear();
2127 display->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002128 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002129 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002130 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002131}
2132
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002133void SurfaceFlinger::postFramebuffer()
2134{
Mathias Agopian841cde52012-03-01 15:44:37 -08002135 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002136 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002137
Mathias Agopiana44b0412011-10-16 18:46:35 -07002138 const nsecs_t now = systemTime();
2139 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002140
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002141 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002142 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002143 continue;
2144 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07002145 const auto displayId = display->getId();
2146 if (displayId >= 0) {
2147 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002148 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002149 display->onSwapBuffersCompleted();
2150 display->makeCurrent();
2151 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002152 sp<Fence> releaseFence = Fence::NO_FENCE;
2153
Chia-I Wu7b549592017-11-15 09:14:57 -08002154 // The layer buffer from the previous frame (if any) is released
2155 // by HWC only when the release fence from this frame (if any) is
2156 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002157 auto hwcLayer = layer->getHwcLayer(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002158 if (displayId >= 0) {
2159 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
2160 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002161
2162 // If the layer was client composited in the previous frame, we
2163 // need to merge with the previous client target acquire fence.
2164 // Since we do not track that, always merge with the current
2165 // client target acquire fence when it is available, even though
2166 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002167 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002168 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002169 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002170 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002171
David Sodmanb8af7922017-12-21 15:17:55 -08002172 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002173 }
Chia-I Wu83806892017-11-16 10:50:20 -08002174
2175 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002176 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002177 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002178 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002179 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002180 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002181 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002182 }
2183 }
2184
Dominik Laskowski7e045462018-05-30 13:02:02 -07002185 if (displayId >= 0) {
2186 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002187 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002188 }
2189
Mathias Agopiana44b0412011-10-16 18:46:35 -07002190 mLastSwapBufferTime = systemTime() - now;
2191 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002192
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002193 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002194 const auto display = getDefaultDisplayDeviceLocked();
2195 if (display && getHwComposer().isConnected(display->getId())) {
2196 const uint32_t flipCount = display->getPageFlipCount();
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002197 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2198 logFrameStats();
2199 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002200 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002201}
2202
Mathias Agopian87baae12012-07-31 12:38:26 -07002203void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002204{
Mathias Agopian841cde52012-03-01 15:44:37 -08002205 ATRACE_CALL();
2206
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002207 // here we keep a copy of the drawing state (that is the state that's
2208 // going to be overwritten by handleTransactionLocked()) outside of
2209 // mStateLock so that the side-effects of the State assignment
2210 // don't happen with mStateLock held (which can cause deadlocks).
2211 State drawingState(mDrawingState);
2212
Mathias Agopianca4d3602011-05-19 15:38:14 -07002213 Mutex::Autolock _l(mStateLock);
2214 const nsecs_t now = systemTime();
2215 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002216
Mathias Agopianca4d3602011-05-19 15:38:14 -07002217 // Here we're guaranteed that some transaction flags are set
2218 // so we can call handleTransactionLocked() unconditionally.
2219 // We call getTransactionFlags(), which will also clear the flags,
2220 // with mStateLock held to guarantee that mCurrentState won't change
2221 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002222
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002223 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002224 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002225 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002226
Mathias Agopianca4d3602011-05-19 15:38:14 -07002227 mLastTransactionTime = systemTime() - now;
2228 mDebugInTransaction = 0;
2229 invalidateHwcGeometry();
2230 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002231}
2232
Dominik Laskowski7e045462018-05-30 13:02:02 -07002233DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002234 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002235 // Figure out whether the event is for the primary display or an
2236 // external display by matching the Hwc display id against one for a
2237 // connected display. If we did not find a match, we then check what
2238 // displays are not already connected to determine the type. If we don't
2239 // have a connected primary display, we assume the new display is meant to
2240 // be the primary display, and then if we don't have an external display,
2241 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002242 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2243 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002244 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002245 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002246 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002247 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002248 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002249 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002250 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002251 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002252 return DisplayDevice::DISPLAY_EXTERNAL;
2253 }
2254
2255 return DisplayDevice::DISPLAY_ID_INVALID;
2256}
2257
Lloyd Piqueba04e622017-12-14 17:11:26 -08002258void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2259 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002260 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002261 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002262 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002263 continue;
2264 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002265
2266 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2267 ALOGE("External displays are not supported by the vr hardware composer.");
2268 continue;
2269 }
2270
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002271 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002272 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002273 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002274 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002275 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002276
2277 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002278 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002279 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002280 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002281 DisplayDeviceState info;
2282 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002283 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2284 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002285 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002286 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002287 mInterceptor->saveDisplayCreation(info);
2288 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002289 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002290 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002291
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002292 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002293 if (idx >= 0) {
2294 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002295 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002296 mCurrentState.displays.removeItemsAt(idx);
2297 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002298 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002299 }
2300
2301 processDisplayChangesLocked();
2302 }
2303
2304 mPendingHotplugEvents.clear();
2305}
2306
Lloyd Pique99d3da52018-01-22 17:48:03 -08002307sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002308 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002309 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002310 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002311 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002312 HdrCapabilities hdrCapabilities;
2313 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002314
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002315 if (hasWideColorDisplay && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002316 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002317 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002318 if (isWideColorMode(colorMode)) {
2319 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002320 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002321
Dominik Laskowski7e045462018-05-30 13:02:02 -07002322 std::vector<RenderIntent> renderIntents =
2323 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002324 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002325 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002326
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002327 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2328 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2329 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002330
2331 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2332 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2333
2334 /*
2335 * Create our display's surface
2336 */
2337 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2338 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002339 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002340 renderSurface->setNativeWindow(nativeWindow.get());
2341 const int displayWidth = renderSurface->queryWidth();
2342 const int displayHeight = renderSurface->queryHeight();
2343
2344 // Make sure that composition can never be stalled by a virtual display
2345 // consumer that isn't processing buffers fast enough. We have to do this
2346 // in two places:
2347 // * Here, in case the display is composed entirely by HWC.
2348 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2349 // window's swap interval in eglMakeCurrent, so they'll override the
2350 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002351 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002352 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2353 }
2354
2355 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002356 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002357
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002358 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002359 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2360 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2361 displayHeight, hasWideColorGamut, hdrCapabilities,
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002362 supportedPerFrameMetadata, hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002363
2364 if (maxFrameBufferAcquiredBuffers >= 3) {
2365 nativeWindowSurface->preallocateBuffers();
2366 }
2367
2368 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002369 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2370 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002371 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002372 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002373 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002374 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002375 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002376 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002377 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002378 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002379 display->setLayerStack(state.layerStack);
2380 display->setProjection(state.orientation, state.viewport, state.frame);
2381 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002382
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002383 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002384}
2385
Lloyd Pique347200f2017-12-14 17:00:15 -08002386void SurfaceFlinger::processDisplayChangesLocked() {
2387 // here we take advantage of Vector's copy-on-write semantics to
2388 // improve performance by skipping the transaction entirely when
2389 // know that the lists are identical
2390 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2391 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2392 if (!curr.isIdenticalTo(draw)) {
2393 mVisibleRegionsDirty = true;
2394 const size_t cc = curr.size();
2395 size_t dc = draw.size();
2396
2397 // find the displays that were removed
2398 // (ie: in drawing state but not in current state)
2399 // also handle displays that changed
2400 // (ie: displays that are in both lists)
2401 for (size_t i = 0; i < dc;) {
2402 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2403 if (j < 0) {
2404 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002405 // Call makeCurrent() on the primary display so we can
2406 // be sure that nothing associated with this display
2407 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002408 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2409 defaultDisplay->makeCurrent();
2410 }
2411 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2412 display->disconnect(getHwComposer());
2413 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002414 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2415 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2416 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2417 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2418 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002419 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002420 } else {
2421 // this display is in both lists. see if something changed.
2422 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002423 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002424 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2425 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2426 if (state_binder != draw_binder) {
2427 // changing the surface is like destroying and
2428 // recreating the DisplayDevice, so we just remove it
2429 // from the drawing state, so that it get re-added
2430 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002431 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2432 display->disconnect(getHwComposer());
2433 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002434 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002435 mDrawingState.displays.removeItemsAt(i);
2436 dc--;
2437 // at this point we must loop to the next item
2438 continue;
2439 }
2440
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002441 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002442 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002443 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002444 }
2445 if ((state.orientation != draw[i].orientation) ||
2446 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002447 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002448 }
2449 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002450 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002451 }
2452 }
2453 }
2454 ++i;
2455 }
2456
2457 // find displays that were added
2458 // (ie: in current state but not in drawing state)
2459 for (size_t i = 0; i < cc; i++) {
2460 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2461 const DisplayDeviceState& state(curr[i]);
2462
2463 sp<DisplaySurface> dispSurface;
2464 sp<IGraphicBufferProducer> producer;
2465 sp<IGraphicBufferProducer> bqProducer;
2466 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002467 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002468
Dominik Laskowski7e045462018-05-30 13:02:02 -07002469 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002470 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002471 // Virtual displays without a surface are dormant:
2472 // they have external state (layer stack, projection,
2473 // etc.) but no internal state (i.e. a DisplayDevice).
2474 if (state.surface != nullptr) {
2475 // Allow VR composer to use virtual displays.
2476 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2477 int width = 0;
2478 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2479 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2480 int height = 0;
2481 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2482 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2483 int intFormat = 0;
2484 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2485 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002486 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002487
Dominik Laskowski7e045462018-05-30 13:02:02 -07002488 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2489 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002490 }
2491
2492 // TODO: Plumb requested format back up to consumer
2493
2494 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002495 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002496 bqProducer, bqConsumer,
2497 state.displayName);
2498
2499 dispSurface = vds;
2500 producer = vds;
2501 }
2502 } else {
2503 ALOGE_IF(state.surface != nullptr,
2504 "adding a supported display, but rendering "
2505 "surface is provided (%p), ignoring it",
2506 state.surface.get());
2507
Dominik Laskowski7e045462018-05-30 13:02:02 -07002508 displayId = state.type;
2509 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002510 producer = bqProducer;
2511 }
2512
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002513 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002514 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002515 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002516 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002517 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002518 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002519 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2520 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2521 true);
2522 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2523 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2524 true);
2525 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002526 }
2527 }
2528 }
2529 }
2530 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002531
2532 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002533}
2534
Mathias Agopian87baae12012-07-31 12:38:26 -07002535void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002536{
Dan Stoza7dde5992015-05-22 09:51:44 -07002537 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002538 mCurrentState.traverseInZOrder([](Layer* layer) {
2539 layer->notifyAvailableFrames();
2540 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002541
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002542 /*
2543 * Traversal of the children
2544 * (perform the transaction for each of them if needed)
2545 */
2546
Mathias Agopian3559b072012-08-15 13:46:03 -07002547 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002548 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002549 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002550 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002551
2552 const uint32_t flags = layer->doTransaction(0);
2553 if (flags & Layer::eVisibleRegion)
2554 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002555 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002556 }
2557
2558 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002559 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002560 */
2561
Mathias Agopiane57f2922012-08-09 16:29:12 -07002562 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002563 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002564 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002565 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002566
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002567 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002568 // The transform hint might have changed for some layers
2569 // (either because a display has changed, or because a layer
2570 // as changed).
2571 //
2572 // Walk through all the layers in currentLayers,
2573 // and update their transform hint.
2574 //
2575 // If a layer is visible only on a single display, then that
2576 // display is used to calculate the hint, otherwise we use the
2577 // default display.
2578 //
2579 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2580 // the hint is set before we acquire a buffer from the surface texture.
2581 //
2582 // NOTE: layer transactions have taken place already, so we use their
2583 // drawing state. However, SurfaceFlinger's own transaction has not
2584 // happened yet, so we must use the current state layer list
2585 // (soon to become the drawing state list).
2586 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002587 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002588 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002589 bool first = true;
2590 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002591 // NOTE: we rely on the fact that layers are sorted by
2592 // layerStack first (so we don't have to traverse the list
2593 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002594 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002595 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002596 currentlayerStack = layerStack;
2597 // figure out if this layerstack is mirrored
2598 // (more than one display) if so, pick the default display,
2599 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002600 hintDisplay = nullptr;
2601 for (const auto& [token, display] : mDisplays) {
2602 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2603 if (hintDisplay) {
2604 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002605 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002606 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002607 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002608 }
2609 }
2610 }
2611 }
Chet Haase91d25932013-04-11 15:24:55 -07002612
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002613 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002614 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2615 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002616
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002617 // could be null when this layer is using a layerStack
2618 // that is not visible on any display. Also can occur at
2619 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002620 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002621 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002622
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002623 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002624 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002625 if (hintDisplay) {
2626 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002627 }
Robert Carr2047fae2016-11-28 14:09:09 -08002628
2629 first = false;
2630 });
Mathias Agopian84300952012-11-21 16:02:13 -08002631 }
2632
2633
Mathias Agopian3559b072012-08-15 13:46:03 -07002634 /*
2635 * Perform our own transaction if needed
2636 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002637
2638 if (mLayersAdded) {
2639 mLayersAdded = false;
2640 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002641 mVisibleRegionsDirty = true;
2642 }
2643
2644 // some layers might have been removed, so
2645 // we need to update the regions they're exposing.
2646 if (mLayersRemoved) {
2647 mLayersRemoved = false;
2648 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002649 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002650 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002651 // this layer is not visible anymore
2652 // TODO: we could traverse the tree from front to back and
2653 // compute the actual visible region
2654 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002655 Region visibleReg;
2656 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002657 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002658 }
Robert Carr2047fae2016-11-28 14:09:09 -08002659 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002660 }
2661
2662 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002663
2664 updateCursorAsync();
2665}
2666
2667void SurfaceFlinger::updateCursorAsync()
2668{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002669 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002670 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002671 continue;
2672 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002673
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002674 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2675 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002676 }
2677 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002678}
2679
2680void SurfaceFlinger::commitTransaction()
2681{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002682 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002683 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002684 for (const auto& l : mLayersPendingRemoval) {
2685 recordBufferingStats(l->getName().string(),
2686 l->getOccupancyHistory(true));
2687 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002688 }
2689 mLayersPendingRemoval.clear();
2690 }
2691
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002692 // If this transaction is part of a window animation then the next frame
2693 // we composite should be considered an animation as well.
2694 mAnimCompositionPending = mAnimTransactionPending;
2695
Mathias Agopian4fec8732012-06-29 14:12:52 -07002696 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002697 // clear the "changed" flags in current state
2698 mCurrentState.colorMatrixChanged = false;
2699
Robert Carr1f0a16a2016-10-24 16:27:39 -07002700 mDrawingState.traverseInZOrder([](Layer* layer) {
2701 layer->commitChildList();
2702 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002703 mTransactionPending = false;
2704 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002705 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002706}
2707
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002708void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2709 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002710 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002711 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002712
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002713 Region aboveOpaqueLayers;
2714 Region aboveCoveredLayers;
2715 Region dirty;
2716
Mathias Agopian87baae12012-07-31 12:38:26 -07002717 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002718
Robert Carr2047fae2016-11-28 14:09:09 -08002719 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002720 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002721 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002722
Jesse Hall01e29052013-02-19 16:13:35 -08002723 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002724 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002725 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002726 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002727
Mathias Agopianab028732010-03-16 16:41:46 -07002728 /*
2729 * opaqueRegion: area of a surface that is fully opaque.
2730 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002731 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002732
2733 /*
2734 * visibleRegion: area of a surface that is visible on screen
2735 * and not fully transparent. This is essentially the layer's
2736 * footprint minus the opaque regions above it.
2737 * Areas covered by a translucent surface are considered visible.
2738 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002739 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002740
2741 /*
2742 * coveredRegion: area of a surface that is covered by all
2743 * visible regions above it (which includes the translucent areas).
2744 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002745 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002746
Jesse Halla8026d22012-09-25 13:25:04 -07002747 /*
2748 * transparentRegion: area of a surface that is hinted to be completely
2749 * transparent. This is only used to tell when the layer has no visible
2750 * non-transparent regions and can be removed from the layer list. It
2751 * does not affect the visibleRegion of this layer or any layers
2752 * beneath it. The hint may not be correct if apps don't respect the
2753 * SurfaceView restrictions (which, sadly, some don't).
2754 */
2755 Region transparentRegion;
2756
Mathias Agopianab028732010-03-16 16:41:46 -07002757
2758 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002759 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002760 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002761 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002762 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002763 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002764 if (!visibleRegion.isEmpty()) {
2765 // Remove the transparent area from the visible region
2766 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002767 if (tr.preserveRects()) {
2768 // transform the transparent region
2769 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002770 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002771 // transformation too complex, can't do the
2772 // transparent region optimization.
2773 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002774 }
Mathias Agopianab028732010-03-16 16:41:46 -07002775 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002776
Mathias Agopianab028732010-03-16 16:41:46 -07002777 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002778 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002779 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002780 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2781 // the opaque region is the layer's footprint
2782 opaqueRegion = visibleRegion;
2783 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002784 }
2785 }
2786
Robert Carre5f4f692018-01-12 13:12:28 -08002787 if (visibleRegion.isEmpty()) {
2788 layer->clearVisibilityRegions();
2789 return;
2790 }
2791
Mathias Agopianab028732010-03-16 16:41:46 -07002792 // Clip the covered region to the visible region
2793 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2794
2795 // Update aboveCoveredLayers for next (lower) layer
2796 aboveCoveredLayers.orSelf(visibleRegion);
2797
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002798 // subtract the opaque region covered by the layers above us
2799 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002800
2801 // compute this layer's dirty region
2802 if (layer->contentDirty) {
2803 // we need to invalidate the whole region
2804 dirty = visibleRegion;
2805 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002806 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002807 layer->contentDirty = false;
2808 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002809 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002810 * the exposed region consists of two components:
2811 * 1) what's VISIBLE now and was COVERED before
2812 * 2) what's EXPOSED now less what was EXPOSED before
2813 *
2814 * note that (1) is conservative, we start with the whole
2815 * visible region but only keep what used to be covered by
2816 * something -- which mean it may have been exposed.
2817 *
2818 * (2) handles areas that were not covered by anything but got
2819 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002820 */
Mathias Agopianab028732010-03-16 16:41:46 -07002821 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002822 const Region oldVisibleRegion = layer->visibleRegion;
2823 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002824 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2825 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002826 }
2827 dirty.subtractSelf(aboveOpaqueLayers);
2828
2829 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002830 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002831
Mathias Agopianab028732010-03-16 16:41:46 -07002832 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002833 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002834
Jesse Halla8026d22012-09-25 13:25:04 -07002835 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002836 layer->setVisibleRegion(visibleRegion);
2837 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002838 layer->setVisibleNonTransparentRegion(
2839 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002840 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002841
Mathias Agopian87baae12012-07-31 12:38:26 -07002842 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002843}
2844
Chia-I Wuab0c3192017-08-01 11:29:00 -07002845void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002846 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002847 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2848 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002849 }
2850 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002851}
2852
Dan Stoza6b9454d2014-11-07 16:00:59 -08002853bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002854{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002855 ALOGV("handlePageFlip");
2856
Brian Andersond6927fb2016-07-23 23:37:30 -07002857 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002858
Mathias Agopian4fec8732012-06-29 14:12:52 -07002859 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002860 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002861 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002862
2863 // Store the set of layers that need updates. This set must not change as
2864 // buffers are being latched, as this could result in a deadlock.
2865 // Example: Two producers share the same command stream and:
2866 // 1.) Layer 0 is latched
2867 // 2.) Layer 0 gets a new frame
2868 // 2.) Layer 1 gets a new frame
2869 // 3.) Layer 1 is latched.
2870 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2871 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002872 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002873 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002874 frameQueued = true;
2875 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002876 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002877 } else {
2878 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002879 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002880 } else {
2881 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002882 }
Robert Carr2047fae2016-11-28 14:09:09 -08002883 });
2884
Dan Stoza9e56aa02015-11-02 13:00:03 -08002885 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002886 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002887 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002888 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002889 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002890 newDataLatched = true;
2891 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002892 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002893
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002894 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002895
2896 // If we will need to wake up at some time in the future to deal with a
2897 // queued frame that shouldn't be displayed during this vsync period, wake
2898 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002899 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002900 signalLayerUpdate();
2901 }
2902
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002903 // enter boot animation on first buffer latch
2904 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2905 ALOGI("Enter boot animation");
2906 mBootStage = BootStage::BOOTANIMATION;
2907 }
2908
Dan Stoza6b9454d2014-11-07 16:00:59 -08002909 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002910 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002911}
2912
Mathias Agopianad456f92011-01-13 17:53:01 -08002913void SurfaceFlinger::invalidateHwcGeometry()
2914{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002915 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002916}
2917
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002918void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2919 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002920 // We only need to actually compose the display if:
2921 // 1) It is being handled by hardware composer, which may need this to
2922 // keep its virtual display state machine in sync, or
2923 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002924 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002925 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002926 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002927 return;
2928 }
2929
Dan Stoza9e56aa02015-11-02 13:00:03 -08002930 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002931 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002932
2933 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002934 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002935}
2936
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002937bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002938 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002939
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002940 const Region bounds(display->bounds());
2941 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002942 const auto displayId = display->getId();
2943 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002944 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002945
Chia-I Wu8e50e692018-05-04 10:12:37 -07002946 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002947 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002948
Dan Stoza9e56aa02015-11-02 13:00:03 -08002949 if (hasClientComposition) {
2950 ALOGV("hasClientComposition");
2951
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002952 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002953 if (display->hasWideColorGamut()) {
2954 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002955 }
2956 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002957 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002958 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002959
Dominik Laskowski7e045462018-05-30 13:02:02 -07002960 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002961 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2962 HWC2::Capability::SkipClientColorTransform);
2963
Chia-I Wud49d6692018-06-27 07:17:41 +08002964 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002965 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2966 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08002967 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002968 }
2969
Chia-I Wud49d6692018-06-27 07:17:41 +08002970 // The current enhanced saturation matrix is designed to enhance Display P3,
2971 // thus we only apply this matrix when the render intent is not colorimetric
2972 // and the output color space is Display P3.
2973 needsEnhancedColorMatrix =
2974 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2975 outputDataspace == Dataspace::DISPLAY_P3);
2976 if (needsEnhancedColorMatrix) {
2977 colorMatrix *= mEnhancedSaturationMatrix;
2978 }
2979
2980 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002981
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002982 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002983 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002984 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002985 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002986
2987 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002988 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
2989 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
2990 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07002991 }
2992 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002993 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002994
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002995 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002996 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002997 // when using overlays, we assume a fully transparent framebuffer
2998 // NOTE: we could reduce how much we need to clear, for instance
2999 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003000 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003001 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003002 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003003 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003004 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003005 // we're left with the letterbox region
3006 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003007 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003008
3009 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003010 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003011
Mathias Agopianb9494d52012-04-18 02:28:45 -07003012 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003013 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003014 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003015 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003016 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003017 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003018
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003019 if (!display->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07003020 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07003021 // scissor on the main display. It should never be needed
3022 // anyways (though in theory it could since the API allows it).
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003023 const Rect& bounds = display->getBounds();
3024 const Rect& scissor = display->getScissor();
Mathias Agopianf45c5102012-10-24 16:29:17 -07003025 if (scissor != bounds) {
3026 // scissor doesn't match the screen's dimensions, so we
3027 // need to clear everything outside of it and enable
3028 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003029
Mathias Agopianf45c5102012-10-24 16:29:17 -07003030 // enable scissor for this frame
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003031 const uint32_t height = display->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08003032 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07003033 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003034 }
3035 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003036 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003037
Mathias Agopian85d751c2012-08-29 16:59:24 -07003038 /*
3039 * and then, render the layers targeted at the framebuffer
3040 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003041
Dan Stoza9e56aa02015-11-02 13:00:03 -08003042 ALOGV("Rendering client layers");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003043 const Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003044 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003045 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003046 const Region clip(bounds.intersect(
3047 displayTransform.transform(layer->visibleRegion)));
3048 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07003049 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003050 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003051 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003052 case HWC2::Composition::Cursor:
3053 case HWC2::Composition::Device:
3054 case HWC2::Composition::Sideband:
3055 case HWC2::Composition::SolidColor: {
3056 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07003057 if (layer->getClearClientTarget(displayId) && !firstLayer &&
Rajavenu Kyatham2eae6d32018-04-10 12:34:05 +05303058 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3059 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003060 // never clear the very first layer since we're
3061 // guaranteed the FB is already cleared
3062 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003063 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003064 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003065 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003066 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003067 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003068 break;
3069 }
3070 default:
3071 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003072 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003073 } else {
3074 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003075 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003076 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003077 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003078
Chia-I Wud49d6692018-06-27 07:17:41 +08003079 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003080 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003081 }
3082
Mathias Agopianf45c5102012-10-24 16:29:17 -07003083 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003084 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003085 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003086}
3087
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003088void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
3089 const Region& region) const {
3090 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003091 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003092 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003093}
3094
Dan Stoza7d89d062015-04-30 13:29:25 -07003095status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003096 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003097 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003098 const sp<Layer>& lbc,
3099 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003100{
Dan Stoza7d89d062015-04-30 13:29:25 -07003101 // add this layer to the current state list
3102 {
3103 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003104 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003105 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3106 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003107 return NO_MEMORY;
3108 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003109 if (parent == nullptr) {
3110 mCurrentState.layersSortedByZ.add(lbc);
3111 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003112 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003113 ALOGE("addClientLayer called with a removed parent");
3114 return NAME_NOT_FOUND;
3115 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003116 parent->addChild(lbc);
3117 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003118
Yiwei Zhang243b3782018-05-15 17:40:04 -07003119 if (gbc != nullptr) {
3120 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3121 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3122 mMaxGraphicBufferProducerListSize,
3123 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3124 mGraphicBufferProducerList.size(),
3125 mMaxGraphicBufferProducerListSize, mNumLayers);
3126 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003127 mLayersAdded = true;
3128 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003129 }
3130
Mathias Agopian96f08192010-06-02 23:28:45 -07003131 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003132 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003133
Dan Stoza7d89d062015-04-30 13:29:25 -07003134 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003135}
3136
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003137status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003138 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003139 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3140}
Robert Carr7f9b8992017-03-10 11:08:39 -08003141
chaviwca27f252018-02-06 16:46:39 -08003142status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3143 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003144 if (layer->isPendingRemoval()) {
3145 return NO_ERROR;
3146 }
3147
Robert Carr1f0a16a2016-10-24 16:27:39 -07003148 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003149 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003150 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003151 if (topLevelOnly) {
3152 return NO_ERROR;
3153 }
3154
Chia-I Wu98f1c102017-05-30 14:54:08 -07003155 sp<Layer> ancestor = p;
3156 while (ancestor->getParent() != nullptr) {
3157 ancestor = ancestor->getParent();
3158 }
3159 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3160 ALOGE("removeLayer called with a layer whose parent has been removed");
3161 return NAME_NOT_FOUND;
3162 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003163
3164 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003165 } else {
3166 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003167 }
3168
Robert Carr136e2f62017-02-08 17:54:29 -08003169 // As a matter of normal operation, the LayerCleaner will produce a second
3170 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3171 // so we will succeed in promoting it, but it's already been removed
3172 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3173 // otherwise something has gone wrong and we are leaking the layer.
3174 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003175 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3176 layer->getName().string(),
3177 (p != nullptr) ? p->getName().string() : "no-parent");
3178 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003179 } else if (index < 0) {
3180 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003181 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003182
Chia-I Wuc6657022017-08-15 11:18:17 -07003183 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003184 mLayersPendingRemoval.add(layer);
3185 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003186 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003187 setTransactionFlags(eTransactionNeeded);
3188 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003189}
3190
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003191uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003192 return android_atomic_release_load(&mTransactionFlags);
3193}
3194
Mathias Agopian3f844832013-08-07 21:24:32 -07003195uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003196 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3197}
3198
Mathias Agopian3f844832013-08-07 21:24:32 -07003199uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003200 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3201}
3202
3203uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3204 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003205 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003206 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003207 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003208 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003209 }
3210 return old;
3211}
3212
chaviwca27f252018-02-06 16:46:39 -08003213bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3214 for (const ComposerState& state : states) {
3215 // Here we need to check that the interface we're given is indeed
3216 // one of our own. A malicious client could give us a nullptr
3217 // IInterface, or one of its own or even one of our own but a
3218 // different type. All these situations would cause us to crash.
3219 if (state.client == nullptr) {
3220 return true;
3221 }
3222
3223 sp<IBinder> binder = IInterface::asBinder(state.client);
3224 if (binder == nullptr) {
3225 return true;
3226 }
3227
3228 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3229 return true;
3230 }
3231 }
3232 return false;
3233}
3234
Mathias Agopian8b33f032012-07-24 20:43:54 -07003235void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003236 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003237 const Vector<DisplayState>& displays,
3238 uint32_t flags)
3239{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003240 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003241 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003242 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003243
chaviwca27f252018-02-06 16:46:39 -08003244 if (containsAnyInvalidClientState(states)) {
3245 return;
3246 }
3247
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003248 if (flags & eAnimation) {
3249 // For window updates that are part of an animation we must wait for
3250 // previous animation "frames" to be handled.
3251 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003252 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003253 if (CC_UNLIKELY(err != NO_ERROR)) {
3254 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003255 // caller after a few seconds.
3256 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3257 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003258 mAnimTransactionPending = false;
3259 break;
3260 }
3261 }
3262 }
3263
chaviwca27f252018-02-06 16:46:39 -08003264 for (const DisplayState& display : displays) {
3265 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003266 }
3267
chaviwca27f252018-02-06 16:46:39 -08003268 for (const ComposerState& state : states) {
3269 transactionFlags |= setClientStateLocked(state);
3270 }
3271
3272 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3273 // as destroyed should only occur after setting all other states. This is to allow for a
3274 // child re-parent to happen before marking its original parent as destroyed (which would
3275 // then mark the child as destroyed).
3276 for (const ComposerState& state : states) {
3277 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003278 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003279
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003280 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3281 // anyway. This can be used as a flush mechanism for previous async transactions.
3282 // Empty animation transaction can be used to simulate back-pressure, so also force a
3283 // transaction for empty animation transactions.
3284 if (transactionFlags == 0 &&
3285 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003286 transactionFlags = eTransactionNeeded;
3287 }
3288
Mathias Agopian386aa982011-11-07 21:58:03 -08003289 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003290 if (mInterceptor->isEnabled()) {
3291 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003292 }
Irvel468051e2016-06-13 16:44:44 -07003293
Mathias Agopian386aa982011-11-07 21:58:03 -08003294 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003295 const auto start = (flags & eEarlyWakeup)
3296 ? VSyncModulator::TransactionStart::EARLY
3297 : VSyncModulator::TransactionStart::NORMAL;
3298 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003299
3300 // if this is a synchronous transaction, wait for it to take effect
3301 // before returning.
3302 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003303 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003304 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003305 if (flags & eAnimation) {
3306 mAnimTransactionPending = true;
3307 }
3308 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003309 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3310 if (CC_UNLIKELY(err != NO_ERROR)) {
3311 // just in case something goes wrong in SF, return to the
3312 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003313 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3314 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003315 break;
3316 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003317 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003318 }
3319}
3320
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003321uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3322 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3323 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003324
Mathias Agopiane57f2922012-08-09 16:29:12 -07003325 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003326 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3327
3328 const uint32_t what = s.what;
3329 if (what & DisplayState::eSurfaceChanged) {
3330 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3331 state.surface = s.surface;
3332 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003333 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003334 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003335 if (what & DisplayState::eLayerStackChanged) {
3336 if (state.layerStack != s.layerStack) {
3337 state.layerStack = s.layerStack;
3338 flags |= eDisplayTransactionNeeded;
3339 }
3340 }
3341 if (what & DisplayState::eDisplayProjectionChanged) {
3342 if (state.orientation != s.orientation) {
3343 state.orientation = s.orientation;
3344 flags |= eDisplayTransactionNeeded;
3345 }
3346 if (state.frame != s.frame) {
3347 state.frame = s.frame;
3348 flags |= eDisplayTransactionNeeded;
3349 }
3350 if (state.viewport != s.viewport) {
3351 state.viewport = s.viewport;
3352 flags |= eDisplayTransactionNeeded;
3353 }
3354 }
3355 if (what & DisplayState::eDisplaySizeChanged) {
3356 if (state.width != s.width) {
3357 state.width = s.width;
3358 flags |= eDisplayTransactionNeeded;
3359 }
3360 if (state.height != s.height) {
3361 state.height = s.height;
3362 flags |= eDisplayTransactionNeeded;
3363 }
3364 }
3365
Mathias Agopiane57f2922012-08-09 16:29:12 -07003366 return flags;
3367}
3368
Robert Carrd4ae7f32018-06-07 16:10:57 -07003369bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3370 IPCThreadState* ipc = IPCThreadState::self();
3371 const int pid = ipc->getCallingPid();
3372 const int uid = ipc->getCallingUid();
3373
3374 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3375 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3376 return false;
3377 }
3378 return true;
3379}
3380
chaviwca27f252018-02-06 16:46:39 -08003381uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3382 const layer_state_t& s = composerState.state;
3383 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3384
Mathias Agopian13127d82013-03-05 17:47:11 -08003385 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003386 if (layer == nullptr) {
3387 return 0;
3388 }
3389
3390 if (layer->isPendingRemoval()) {
3391 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3392 return 0;
3393 }
3394
3395 uint32_t flags = 0;
3396
3397 const uint32_t what = s.what;
3398 bool geometryAppliesWithResize =
3399 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003400
3401 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3402 // pending state will also be deferred.
3403 if (what & layer_state_t::eDeferTransaction) {
3404 layer->pushPendingState();
3405 }
3406
chaviw8b3871a2017-11-01 17:41:01 -07003407 if (what & layer_state_t::ePositionChanged) {
3408 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3409 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003410 }
chaviw8b3871a2017-11-01 17:41:01 -07003411 }
3412 if (what & layer_state_t::eLayerChanged) {
3413 // NOTE: index needs to be calculated before we update the state
3414 const auto& p = layer->getParent();
3415 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003416 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003417 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003418 mCurrentState.layersSortedByZ.removeAt(idx);
3419 mCurrentState.layersSortedByZ.add(layer);
3420 // we need traversal (state changed)
3421 // AND transaction (list changed)
3422 flags |= eTransactionNeeded|eTraversalNeeded;
3423 }
chaviw8b3871a2017-11-01 17:41:01 -07003424 } else {
3425 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003426 flags |= eTransactionNeeded|eTraversalNeeded;
3427 }
3428 }
chaviw8b3871a2017-11-01 17:41:01 -07003429 }
3430 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003431 // NOTE: index needs to be calculated before we update the state
3432 const auto& p = layer->getParent();
3433 if (p == nullptr) {
3434 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3435 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3436 mCurrentState.layersSortedByZ.removeAt(idx);
3437 mCurrentState.layersSortedByZ.add(layer);
3438 // we need traversal (state changed)
3439 // AND transaction (list changed)
3440 flags |= eTransactionNeeded|eTraversalNeeded;
3441 }
3442 } else {
3443 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3444 flags |= eTransactionNeeded|eTraversalNeeded;
3445 }
chaviw8b3871a2017-11-01 17:41:01 -07003446 }
3447 }
3448 if (what & layer_state_t::eSizeChanged) {
3449 if (layer->setSize(s.w, s.h)) {
3450 flags |= eTraversalNeeded;
3451 }
3452 }
3453 if (what & layer_state_t::eAlphaChanged) {
3454 if (layer->setAlpha(s.alpha))
3455 flags |= eTraversalNeeded;
3456 }
3457 if (what & layer_state_t::eColorChanged) {
3458 if (layer->setColor(s.color))
3459 flags |= eTraversalNeeded;
3460 }
3461 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003462 // TODO: b/109894387
3463 //
3464 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3465 // rotation. To see the problem observe that if we have a square parent, and a child
3466 // of the same size, then we rotate the child 45 degrees around it's center, the child
3467 // must now be cropped to a non rectangular 8 sided region.
3468 //
3469 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3470 // private API, and the WindowManager only uses rotation in one case, which is on a top
3471 // level layer in which cropping is not an issue.
3472 //
3473 // However given that abuse of rotation matrices could lead to surfaces extending outside
3474 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3475 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3476 // transformations.
3477 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003478 flags |= eTraversalNeeded;
3479 }
3480 if (what & layer_state_t::eTransparentRegionChanged) {
3481 if (layer->setTransparentRegionHint(s.transparentRegion))
3482 flags |= eTraversalNeeded;
3483 }
3484 if (what & layer_state_t::eFlagsChanged) {
3485 if (layer->setFlags(s.flags, s.mask))
3486 flags |= eTraversalNeeded;
3487 }
3488 if (what & layer_state_t::eCropChanged) {
3489 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3490 flags |= eTraversalNeeded;
3491 }
3492 if (what & layer_state_t::eFinalCropChanged) {
3493 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3494 flags |= eTraversalNeeded;
3495 }
3496 if (what & layer_state_t::eLayerStackChanged) {
3497 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3498 // We only allow setting layer stacks for top level layers,
3499 // everything else inherits layer stack from its parent.
3500 if (layer->hasParent()) {
3501 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3502 layer->getName().string());
3503 } else if (idx < 0) {
3504 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3505 "that also does not appear in the top level layer list. Something"
3506 " has gone wrong.", layer->getName().string());
3507 } else if (layer->setLayerStack(s.layerStack)) {
3508 mCurrentState.layersSortedByZ.removeAt(idx);
3509 mCurrentState.layersSortedByZ.add(layer);
3510 // we need traversal (state changed)
3511 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003512 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003513 }
3514 }
3515 if (what & layer_state_t::eDeferTransaction) {
3516 if (s.barrierHandle != nullptr) {
3517 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3518 } else if (s.barrierGbp != nullptr) {
3519 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3520 if (authenticateSurfaceTextureLocked(gbp)) {
3521 const auto& otherLayer =
3522 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3523 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3524 } else {
3525 ALOGE("Attempt to defer transaction to to an"
3526 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003527 }
3528 }
chaviw8b3871a2017-11-01 17:41:01 -07003529 // We don't trigger a traversal here because if no other state is
3530 // changed, we don't want this to cause any more work
3531 }
3532 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003533 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003534 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003535 if (!hadParent) {
3536 mCurrentState.layersSortedByZ.remove(layer);
3537 }
chaviw8b3871a2017-11-01 17:41:01 -07003538 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003539 }
chaviw8b3871a2017-11-01 17:41:01 -07003540 }
3541 if (what & layer_state_t::eReparentChildren) {
3542 if (layer->reparentChildren(s.reparentHandle)) {
3543 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003544 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003545 }
chaviw8b3871a2017-11-01 17:41:01 -07003546 if (what & layer_state_t::eDetachChildren) {
3547 layer->detachChildren();
3548 }
3549 if (what & layer_state_t::eOverrideScalingModeChanged) {
3550 layer->setOverrideScalingMode(s.overrideScalingMode);
3551 // We don't trigger a traversal here because if no other state is
3552 // changed, we don't want this to cause any more work
3553 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003554 return flags;
3555}
3556
chaviwca27f252018-02-06 16:46:39 -08003557void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3558 const layer_state_t& state = composerState.state;
3559 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3560
3561 sp<Layer> layer(client->getLayerUser(state.surface));
3562 if (layer == nullptr) {
3563 return;
3564 }
3565
3566 if (layer->isPendingRemoval()) {
3567 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3568 return;
3569 }
3570
3571 if (state.what & layer_state_t::eDestroySurface) {
3572 removeLayerLocked(mStateLock, layer);
3573 }
3574}
3575
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003576status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003577 const String8& name,
3578 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003579 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003580 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003581 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003582{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003583 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003584 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003585 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003586 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003587 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003588
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003589 status_t result = NO_ERROR;
3590
3591 sp<Layer> layer;
3592
Cody Northropbc755282017-03-31 12:00:08 -06003593 String8 uniqueName = getUniqueLayerName(name);
3594
Mathias Agopian3165cc22012-08-08 19:42:09 -07003595 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3596 case ISurfaceComposerClient::eFXSurfaceNormal:
Marissa Wallfd668622018-05-10 10:21:13 -07003597 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3598 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003599
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003600 break;
chaviw13fdc492017-06-27 12:40:18 -07003601 case ISurfaceComposerClient::eFXSurfaceColor:
3602 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003603 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003604 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003605 break;
3606 default:
3607 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003608 break;
3609 }
3610
Dan Stoza7d89d062015-04-30 13:29:25 -07003611 if (result != NO_ERROR) {
3612 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003613 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003614
Chia-I Wuab0c3192017-08-01 11:29:00 -07003615 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3616 // TODO b/64227542
3617 if (windowType == 441731) {
3618 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3619 layer->setPrimaryDisplayOnly();
3620 }
3621
Albert Chaulk479c60c2017-01-27 14:21:34 -05003622 layer->setInfo(windowType, ownerUid);
3623
Robert Carr1f0a16a2016-10-24 16:27:39 -07003624 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003625 if (result != NO_ERROR) {
3626 return result;
3627 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003628 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003629
3630 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003631 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003632}
3633
Cody Northropbc755282017-03-31 12:00:08 -06003634String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3635{
3636 bool matchFound = true;
3637 uint32_t dupeCounter = 0;
3638
3639 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3640 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3641
Dan Stoza436ccf32018-06-21 12:10:12 -07003642 // Grab the state lock since we're accessing mCurrentState
3643 Mutex::Autolock lock(mStateLock);
3644
Cody Northropbc755282017-03-31 12:00:08 -06003645 // Loop over layers until we're sure there is no matching name
3646 while (matchFound) {
3647 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003648 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003649 if (layer->getName() == uniqueName) {
3650 matchFound = true;
3651 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3652 }
3653 });
3654 }
3655
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003656 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3657 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003658
3659 return uniqueName;
3660}
3661
Marissa Wallfd668622018-05-10 10:21:13 -07003662status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3663 uint32_t w, uint32_t h, uint32_t flags,
3664 PixelFormat& format, sp<IBinder>* handle,
3665 sp<IGraphicBufferProducer>* gbp,
3666 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003667 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003668 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003669 case PIXEL_FORMAT_TRANSPARENT:
3670 case PIXEL_FORMAT_TRANSLUCENT:
3671 format = PIXEL_FORMAT_RGBA_8888;
3672 break;
3673 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003674 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003675 break;
3676 }
3677
Marissa Wallfd668622018-05-10 10:21:13 -07003678 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3679 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003680 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003681 *handle = layer->getHandle();
3682 *gbp = layer->getProducer();
3683 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003684 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003685
Marissa Wallfd668622018-05-10 10:21:13 -07003686 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003687 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003688}
3689
chaviw13fdc492017-06-27 12:40:18 -07003690status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003691 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003692 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003693{
chaviw13fdc492017-06-27 12:40:18 -07003694 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003695 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003696 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003697}
3698
Mathias Agopianac9fa422013-02-11 16:40:36 -08003699status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003700{
Robert Carr9524cb32017-02-13 11:32:32 -08003701 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003702 status_t err = NO_ERROR;
3703 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003704 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003705 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003706 err = removeLayer(l);
3707 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3708 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003709 }
3710 return err;
3711}
3712
Mathias Agopian13127d82013-03-05 17:47:11 -08003713status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003714{
Mathias Agopian67106042013-03-14 19:18:13 -07003715 // called by ~LayerCleaner() when all references to the IBinder (handle)
3716 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003717 sp<Layer> l = layer.promote();
3718 if (l == nullptr) {
3719 // The layer has already been removed, carry on
3720 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003721 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003722 // If we have a parent, then we can continue to live as long as it does.
3723 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003724}
3725
Mathias Agopianb60314a2012-04-10 22:09:54 -07003726// ---------------------------------------------------------------------------
3727
Andy McFadden13a082e2012-08-24 10:16:42 -07003728void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003729 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3730 if (!displayToken) return;
3731
Jesse Hall01e29052013-02-19 16:13:35 -08003732 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003733 Vector<ComposerState> state;
3734 Vector<DisplayState> displays;
3735 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003736 d.what = DisplayState::eDisplayProjectionChanged |
3737 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003738 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003739 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003740 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003741 d.frame.makeInvalid();
3742 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003743 d.width = 0;
3744 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003745 displays.add(d);
3746 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003747
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003748 const auto display = getDisplayDevice(displayToken);
3749 if (!display) return;
3750
3751 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3752
3753 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003754 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003755 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003756
Brian Andersond0010582017-03-07 13:20:31 -08003757 // Use phase of 0 since phase is not known.
3758 // Use latency of 0, which will snap to the ideal latency.
3759 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003760}
3761
3762void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003763 // Async since we may be called from the main thread.
3764 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003765}
3766
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003767void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3768 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003769 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003770 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003771
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003772 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003773 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003774 return;
3775 }
3776
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003777 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003778 ALOGW("Trying to set power mode for virtual display");
3779 return;
3780 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003781
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003782 display->setPowerMode(mode);
3783
Lloyd Pique4dccc412018-01-22 17:21:36 -08003784 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003785 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003786 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003787 if (idx < 0) {
3788 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3789 return;
3790 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003791 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003792 }
3793
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003794 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003795 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003796 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003797 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003798 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003799 // FIXME: eventthread only knows about the main display right now
3800 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003801 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003802 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003803
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003804 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003805 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003806 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003807
3808 struct sched_param param = {0};
3809 param.sched_priority = 1;
3810 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3811 ALOGW("Couldn't set SCHED_FIFO on display on");
3812 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003813 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003814 // Turn off the display
3815 struct sched_param param = {0};
3816 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3817 ALOGW("Couldn't set SCHED_OTHER on display off");
3818 }
3819
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003820 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003821 disableHardwareVsync(true); // also cancels any in-progress resync
3822
Mathias Agopiancde87a32012-09-13 14:09:01 -07003823 // FIXME: eventthread only knows about the main display right now
3824 mEventThread->onScreenReleased();
3825 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003826
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003827 getHwComposer().setPowerMode(type, mode);
3828 mVisibleRegionsDirty = true;
3829 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003830 } else if (mode == HWC_POWER_MODE_DOZE ||
3831 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003832 // Update display while dozing
3833 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003834 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003835 // FIXME: eventthread only knows about the main display right now
3836 mEventThread->onScreenAcquired();
3837 resyncToHardwareVsync(true);
3838 }
3839 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3840 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003841 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003842 disableHardwareVsync(true); // also cancels any in-progress resync
3843 // FIXME: eventthread only knows about the main display right now
3844 mEventThread->onScreenReleased();
3845 }
3846 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003847 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003848 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003849 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003850 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003851
3852 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003853}
3854
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003855void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003856 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003857 const auto display = getDisplayDevice(displayToken);
3858 if (!display) {
3859 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3860 displayToken.get());
3861 } else if (display->isVirtual()) {
3862 ALOGW("Attempt to set power mode %d for virtual display", mode);
3863 } else {
3864 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003865 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003866 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003867}
3868
3869// ---------------------------------------------------------------------------
3870
Lloyd Pique755e3192018-01-31 16:46:15 -08003871status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3872 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003873 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003874
Mathias Agopianbd115332013-04-18 16:41:04 -07003875 IPCThreadState* ipc = IPCThreadState::self();
3876 const int pid = ipc->getCallingPid();
3877 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003878
Mathias Agopianbd115332013-04-18 16:41:04 -07003879 if ((uid != AID_SHELL) &&
3880 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003881 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003882 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003883 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003884 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003885 // (this would indicate SF is stuck, but we want to be able to
3886 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003887 status_t err = mStateLock.timedLock(s2ns(1));
3888 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003889 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003890 result.appendFormat(
3891 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3892 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003893 }
3894
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003895 bool dumpAll = true;
3896 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003897 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003898
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003899 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003900 if ((index < numArgs) &&
3901 (args[index] == String16("--list"))) {
3902 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003903 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003904 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003905 }
3906
3907 if ((index < numArgs) &&
3908 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003909 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003910 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003911 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003912 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003913
3914 if ((index < numArgs) &&
3915 (args[index] == String16("--latency-clear"))) {
3916 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003917 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003918 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003919 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003920
3921 if ((index < numArgs) &&
3922 (args[index] == String16("--dispsync"))) {
3923 index++;
3924 mPrimaryDispSync.dump(result);
3925 dumpAll = false;
3926 }
Dan Stozab90cf072015-03-05 11:05:59 -08003927
3928 if ((index < numArgs) &&
3929 (args[index] == String16("--static-screen"))) {
3930 index++;
3931 dumpStaticScreenStats(result);
3932 dumpAll = false;
3933 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003934
3935 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003936 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003937 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003938 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003939 dumpAll = false;
3940 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003941
3942 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3943 index++;
3944 dumpWideColorInfo(result);
3945 dumpAll = false;
3946 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003947
3948 if ((index < numArgs) &&
3949 (args[index] == String16("--enable-layer-stats"))) {
3950 index++;
3951 mLayerStats.enable();
3952 dumpAll = false;
3953 }
3954
3955 if ((index < numArgs) &&
3956 (args[index] == String16("--disable-layer-stats"))) {
3957 index++;
3958 mLayerStats.disable();
3959 dumpAll = false;
3960 }
3961
3962 if ((index < numArgs) &&
3963 (args[index] == String16("--clear-layer-stats"))) {
3964 index++;
3965 mLayerStats.clear();
3966 dumpAll = false;
3967 }
3968
3969 if ((index < numArgs) &&
3970 (args[index] == String16("--dump-layer-stats"))) {
3971 index++;
3972 mLayerStats.dump(result);
3973 dumpAll = false;
3974 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07003975
3976 if ((index < numArgs) &&
3977 (args[index] == String16("--display-identification"))) {
3978 index++;
3979 dumpDisplayIdentificationData(result);
3980 dumpAll = false;
3981 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003982
3983 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
3984 index++;
3985 mTimeStats.parseArgs(asProto, args, index, result);
3986 dumpAll = false;
3987 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003988 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003989
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003990 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07003991 if (asProto) {
3992 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
3993 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
3994 } else {
3995 dumpAllLocked(args, index, result);
3996 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08003997 }
3998
Mathias Agopian9795c422009-08-26 16:36:26 -07003999 if (locked) {
4000 mStateLock.unlock();
4001 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004002 }
4003 write(fd, result.string(), result.size());
4004 return NO_ERROR;
4005}
4006
Dan Stozac7014012014-02-14 15:03:43 -08004007void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4008 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004009{
Robert Carr2047fae2016-11-28 14:09:09 -08004010 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004011 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004012 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004013}
4014
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004015void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004016 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004017{
4018 String8 name;
4019 if (index < args.size()) {
4020 name = String8(args[index]);
4021 index++;
4022 }
4023
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004024 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4025 getHwComposer().isConnected(displayId)) {
4026 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4027 const nsecs_t period = activeConfig->getVsyncPeriod();
4028 result.appendFormat("%" PRId64 "\n", period);
4029 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004030
4031 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004032 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004033 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004034 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004035 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004036 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004037 }
Robert Carr2047fae2016-11-28 14:09:09 -08004038 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004039 }
4040}
4041
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004042void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004043 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004044{
4045 String8 name;
4046 if (index < args.size()) {
4047 name = String8(args[index]);
4048 index++;
4049 }
4050
Robert Carr2047fae2016-11-28 14:09:09 -08004051 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004052 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004053 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004054 }
Robert Carr2047fae2016-11-28 14:09:09 -08004055 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004056
Svetoslavd85084b2014-03-20 10:28:31 -07004057 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004058}
4059
Jamie Gennis6547ff42013-07-16 20:12:42 -07004060// This should only be called from the main thread. Otherwise it would need
4061// the lock and should use mCurrentState rather than mDrawingState.
4062void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004063 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004064 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004065 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004066
4067 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4068}
4069
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004070void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004071{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004072 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004073
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004074 if (isLayerTripleBufferingDisabled())
4075 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004076
4077 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004078 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004079 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004080 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004081 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4082 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004083 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004084}
4085
Dan Stozab90cf072015-03-05 11:05:59 -08004086void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4087{
4088 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004089 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4090 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004091 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004092 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004093 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4094 b + 1, bucketTimeSec, percent);
4095 }
David Sodman4a36e932017-11-07 14:29:47 -08004096 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004097 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004098 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004099 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004100 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004101}
4102
Dan Stozae77c7662016-05-13 11:37:28 -07004103void SurfaceFlinger::recordBufferingStats(const char* layerName,
4104 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004105 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4106 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004107 for (const auto& segment : history) {
4108 if (!segment.usedThirdBuffer) {
4109 stats.twoBufferTime += segment.totalTime;
4110 }
4111 if (segment.occupancyAverage < 1.0f) {
4112 stats.doubleBufferedTime += segment.totalTime;
4113 } else if (segment.occupancyAverage < 2.0f) {
4114 stats.tripleBufferedTime += segment.totalTime;
4115 }
4116 ++stats.numSegments;
4117 stats.totalTime += segment.totalTime;
4118 }
4119}
4120
Brian Andersond6927fb2016-07-23 23:37:30 -07004121void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4122 result.appendFormat("Layer frame timestamps:\n");
4123
4124 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4125 const size_t count = currentLayers.size();
4126 for (size_t i=0 ; i<count ; i++) {
4127 currentLayers[i]->dumpFrameEvents(result);
4128 }
4129}
4130
Dan Stozae77c7662016-05-13 11:37:28 -07004131void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4132 result.append("Buffering stats:\n");
4133 result.append(" [Layer name] <Active time> <Two buffer> "
4134 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004135 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004136 typedef std::tuple<std::string, float, float, float> BufferTuple;
4137 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004138 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004139 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004140 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004141 if (stats.numSegments == 0) {
4142 continue;
4143 }
4144 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4145 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4146 stats.totalTime;
4147 float doubleBufferRatio = static_cast<float>(
4148 stats.doubleBufferedTime) / stats.totalTime;
4149 float tripleBufferRatio = static_cast<float>(
4150 stats.tripleBufferedTime) / stats.totalTime;
4151 sorted.insert({activeTime, {name, twoBufferRatio,
4152 doubleBufferRatio, tripleBufferRatio}});
4153 }
4154 for (const auto& sortedPair : sorted) {
4155 float activeTime = sortedPair.first;
4156 const BufferTuple& values = sortedPair.second;
4157 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4158 std::get<0>(values).c_str(), activeTime,
4159 std::get<1>(values), std::get<2>(values),
4160 std::get<3>(values));
4161 }
4162 result.append("\n");
4163}
4164
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004165void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004166 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004167 const int32_t displayId = display->getId();
4168 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4169 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004170 continue;
4171 }
4172
Dominik Laskowski7e045462018-05-30 13:02:02 -07004173 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004174 uint8_t port;
4175 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004176 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004177 result.append("no identification data\n");
4178 continue;
4179 }
4180
4181 if (!isEdid(data)) {
4182 result.append("unknown identification data: ");
4183 for (uint8_t byte : data) {
4184 result.appendFormat("%x ", byte);
4185 }
4186 result.append("\n");
4187 continue;
4188 }
4189
4190 const auto edid = parseEdid(data);
4191 if (!edid) {
4192 result.append("invalid EDID: ");
4193 for (uint8_t byte : data) {
4194 result.appendFormat("%x ", byte);
4195 }
4196 result.append("\n");
4197 continue;
4198 }
4199
4200 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4201 result.append(edid->displayName.data(), edid->displayName.length());
4202 result.append("\"\n");
4203 }
4204 result.append("\n");
4205}
4206
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004207void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4208 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004209 result.appendFormat("DisplayColorSetting: %s\n",
4210 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004211
4212 // TODO: print out if wide-color mode is active or not
4213
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004214 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004215 const int32_t displayId = display->getId();
4216 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004217 continue;
4218 }
4219
Dominik Laskowski7e045462018-05-30 13:02:02 -07004220 result.appendFormat("Display %d color modes:\n", displayId);
4221 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004222 for (auto&& mode : modes) {
4223 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4224 }
4225
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004226 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004227 result.appendFormat(" Current color mode: %s (%d)\n",
4228 decodeColorMode(currentMode).c_str(), currentMode);
4229 }
4230 result.append("\n");
4231}
4232
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004233LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004234 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004235 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4236 const State& state = useDrawing ? mDrawingState : mCurrentState;
4237 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004238 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004239 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004240 });
4241
4242 return layersProto;
4243}
4244
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004245LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004246 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004247
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004248 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004249 resolution->set_w(display.getWidth());
4250 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004251
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004252 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4253 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4254 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004255
Dominik Laskowski7e045462018-05-30 13:02:02 -07004256 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004257 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004258 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004259 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004260 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004261 }
4262 });
4263
4264 return layersProto;
4265}
4266
Mathias Agopian74d211a2013-04-22 16:55:35 +02004267void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4268 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004269{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004270 bool colorize = false;
4271 if (index < args.size()
4272 && (args[index] == String16("--color"))) {
4273 colorize = true;
4274 index++;
4275 }
4276
4277 Colorizer colorizer(colorize);
4278
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004279 // figure out if we're stuck somewhere
4280 const nsecs_t now = systemTime();
4281 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4282 const nsecs_t inTransaction(mDebugInTransaction);
4283 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4284 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4285
4286 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004287 * Dump library configuration.
4288 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004289
4290 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004291 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004292 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004293 appendSfConfigString(result);
4294 appendUiConfigString(result);
4295 appendGuiConfigString(result);
4296 result.append("\n");
4297
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004298 result.append("\nDisplay identification data:\n");
4299 dumpDisplayIdentificationData(result);
4300
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004301 result.append("\nWide-Color information:\n");
4302 dumpWideColorInfo(result);
4303
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004304 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004305 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004306 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004307 result.append(SyncFeatures::getInstance().toString());
4308 result.append("\n");
4309
Andy McFadden41d67d72014-04-25 16:58:34 -07004310 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004311 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004312 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004313
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004314 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4315 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004316 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4317 getHwComposer().isConnected(displayId)) {
4318 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004319 result.appendFormat("Display %d: "
4320 "app phase %" PRId64 " ns, "
4321 "sf phase %" PRId64 " ns, "
4322 "early app phase %" PRId64 " ns, "
4323 "early sf phase %" PRId64 " ns, "
4324 "early app gl phase %" PRId64 " ns, "
4325 "early sf gl phase %" PRId64 " ns, "
4326 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4327 displayId,
4328 vsyncPhaseOffsetNs,
4329 sfVsyncPhaseOffsetNs,
4330 appEarlyOffset,
4331 sfEarlyOffset,
4332 appEarlyGlOffset,
4333 sfEarlyOffset,
4334 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004335 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004336 result.append("\n");
4337
Dan Stozab90cf072015-03-05 11:05:59 -08004338 // Dump static screen stats
4339 result.append("\n");
4340 dumpStaticScreenStats(result);
4341 result.append("\n");
4342
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004343 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4344
Dan Stozae77c7662016-05-13 11:37:28 -07004345 dumpBufferingStats(result);
4346
Andy McFadden4803b742012-09-24 19:07:20 -07004347 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004348 * Dump the visible layer list
4349 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004350 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004351 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004352 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4353 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004354 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004355
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004356 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004357 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004358 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004359 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004360
4361 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004362 * Dump Display state
4363 */
4364
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004365 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004366 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004367 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004368 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004369 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004370 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004371 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004372
4373 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004374 * Dump SurfaceFlinger global state
4375 */
4376
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004377 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004378 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004379 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004380
Mathias Agopian888c8222012-08-04 21:10:38 -07004381 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004382 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004383
David Sodmanbc815282017-11-05 18:57:52 -08004384 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004385
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004386 if (display) {
4387 display->undefinedRegion.dump(result, "undefinedRegion");
4388 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4389 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004390 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004391 result.appendFormat(" last eglSwapBuffers() time: %f us\n"
4392 " last transaction time : %f us\n"
4393 " transaction-flags : %08x\n"
4394 " gpu_to_cpu_unsupported : %d\n",
4395 mLastSwapBufferTime / 1000.0, mLastTransactionTime / 1000.0,
4396 mTransactionFlags, !mGpuToCpuSupported);
4397
4398 if (display) {
4399 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4400 result.appendFormat(" refresh-rate : %f fps\n"
4401 " x-dpi : %f\n"
4402 " y-dpi : %f\n",
4403 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4404 activeConfig->getDpiY());
4405 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004406
Mathias Agopian74d211a2013-04-22 16:55:35 +02004407 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004408 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004409
Mathias Agopian74d211a2013-04-22 16:55:35 +02004410 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004411 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004412
4413 /*
4414 * VSYNC state
4415 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004416 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004417 result.append("\n");
4418
4419 /*
4420 * HWC layer minidump
4421 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004422 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004423 const int32_t displayId = display->getId();
4424 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004425 continue;
4426 }
4427
Dominik Laskowski7e045462018-05-30 13:02:02 -07004428 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004429 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004430 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004431 result.append("\n");
4432 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004433
4434 /*
4435 * Dump HWComposer state
4436 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004437 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004438 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004439 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004440 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004441 result.appendFormat(" h/w composer %s\n",
4442 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004443 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004444
4445 /*
4446 * Dump gralloc state
4447 */
4448 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4449 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004450
4451 /*
4452 * Dump VrFlinger state if in use.
4453 */
4454 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4455 result.append("VrFlinger state:\n");
4456 result.append(mVrFlinger->Dump().c_str());
4457 result.append("\n");
4458 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004459}
4460
Dominik Laskowski7e045462018-05-30 13:02:02 -07004461const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004462 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004463 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004464 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004465 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004466 }
4467 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004468
4469 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4470 static const Vector<sp<Layer>> empty;
4471 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004472}
4473
Keun young Park63f165f2012-08-31 10:53:36 -07004474bool SurfaceFlinger::startDdmConnection()
4475{
4476 void* libddmconnection_dso =
4477 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4478 if (!libddmconnection_dso) {
4479 return false;
4480 }
4481 void (*DdmConnection_start)(const char* name);
4482 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004483 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004484 if (!DdmConnection_start) {
4485 dlclose(libddmconnection_dso);
4486 return false;
4487 }
4488 (*DdmConnection_start)(getServiceName());
4489 return true;
4490}
4491
Chia-I Wu28f320b2018-05-03 11:02:56 -07004492void SurfaceFlinger::updateColorMatrixLocked() {
4493 mat4 colorMatrix;
4494 if (mGlobalSaturationFactor != 1.0f) {
4495 // Rec.709 luma coefficients
4496 float3 luminance{0.213f, 0.715f, 0.072f};
4497 luminance *= 1.0f - mGlobalSaturationFactor;
4498 mat4 saturationMatrix = mat4(
4499 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4500 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4501 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4502 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4503 );
4504 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4505 } else {
4506 colorMatrix = mClientColorMatrix * mDaltonizer();
4507 }
4508
4509 if (mCurrentState.colorMatrix != colorMatrix) {
4510 mCurrentState.colorMatrix = colorMatrix;
4511 mCurrentState.colorMatrixChanged = true;
4512 setTransactionFlags(eTransactionNeeded);
4513 }
4514}
4515
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004516status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004517 switch (code) {
4518 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004519 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004520 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004521 case CLEAR_ANIMATION_FRAME_STATS:
4522 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004523 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004524 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004525 case ENABLE_VSYNC_INJECTIONS:
4526 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004527 {
4528 // codes that require permission check
Robert Carrd4ae7f32018-06-07 16:10:57 -07004529 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4530 IPCThreadState* ipc = IPCThreadState::self();
4531 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4532 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004533 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004534 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004535 break;
4536 }
Robert Carr1db73f62016-12-21 12:58:51 -08004537 /*
4538 * Calling setTransactionState is safe, because you need to have been
4539 * granted a reference to Client* and Handle* to do anything with it.
4540 *
4541 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4542 */
4543 case SET_TRANSACTION_STATE:
4544 case CREATE_SCOPED_CONNECTION:
4545 {
4546 return OK;
4547 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004548 case CAPTURE_SCREEN:
4549 {
4550 // codes that require permission check
4551 IPCThreadState* ipc = IPCThreadState::self();
4552 const int pid = ipc->getCallingPid();
4553 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004554 if ((uid != AID_GRAPHICS) &&
4555 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004556 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004557 return PERMISSION_DENIED;
4558 }
4559 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004560 }
chaviwa76b2712017-09-20 12:02:26 -07004561 case CAPTURE_LAYERS: {
4562 IPCThreadState* ipc = IPCThreadState::self();
4563 const int pid = ipc->getCallingPid();
4564 const int uid = ipc->getCallingUid();
4565 if ((uid != AID_GRAPHICS) &&
4566 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4567 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4568 return PERMISSION_DENIED;
4569 }
4570 break;
4571 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004572 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004573 return OK;
4574}
4575
4576status_t SurfaceFlinger::onTransact(
4577 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4578{
4579 status_t credentialCheck = CheckTransactCodeCredentials(code);
4580 if (credentialCheck != OK) {
4581 return credentialCheck;
4582 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004583
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004584 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4585 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004586 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004587 IPCThreadState* ipc = IPCThreadState::self();
4588 const int uid = ipc->getCallingUid();
4589 if (CC_UNLIKELY(uid != AID_SYSTEM
4590 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004591 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004592 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004593 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004594 return PERMISSION_DENIED;
4595 }
4596 int n;
4597 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004598 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004599 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004600 return NO_ERROR;
4601 case 1002: // SHOW_UPDATES
4602 n = data.readInt32();
4603 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004604 invalidateHwcGeometry();
4605 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004606 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004607 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004608 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004609 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004610 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004611 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004612 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004613 setTransactionFlags(
4614 eTransactionNeeded|
4615 eDisplayTransactionNeeded|
4616 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004617 return NO_ERROR;
4618 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004619 case 1006:{ // send empty update
4620 signalRefresh();
4621 return NO_ERROR;
4622 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004623 case 1008: // toggle use of hw composer
4624 n = data.readInt32();
4625 mDebugDisableHWC = n ? 1 : 0;
4626 invalidateHwcGeometry();
4627 repaintEverything();
4628 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004629 case 1009: // toggle use of transform hint
4630 n = data.readInt32();
4631 mDebugDisableTransformHint = n ? 1 : 0;
4632 invalidateHwcGeometry();
4633 repaintEverything();
4634 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004635 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004636 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004637 reply->writeInt32(0);
4638 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004639 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004640 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004641 return NO_ERROR;
4642 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004643 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004644 if (!display) {
4645 return NAME_NOT_FOUND;
4646 }
4647
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004648 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004649 return NO_ERROR;
4650 }
4651 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004652 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004653 // daltonize
4654 n = data.readInt32();
4655 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004656 case 1:
4657 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4658 break;
4659 case 2:
4660 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4661 break;
4662 case 3:
4663 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4664 break;
4665 default:
4666 mDaltonizer.setType(ColorBlindnessType::None);
4667 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004668 }
4669 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004670 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004671 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004672 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004673 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004674
4675 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004676 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004677 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004678 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004679 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004680 // apply a color matrix
4681 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004682 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004683 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004684 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004685 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004686 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004687 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004688 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004689 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004690 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004691 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004692
4693 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4694 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004695 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004696 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4697 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4698 }
4699
Chia-I Wu28f320b2018-05-03 11:02:56 -07004700 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004701 return NO_ERROR;
4702 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004703 // This is an experimental interface
4704 // Needs to be shifted to proper binder interface when we productize
4705 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004706 n = data.readInt32();
4707 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004708 return NO_ERROR;
4709 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004710 case 1017: {
4711 n = data.readInt32();
4712 mForceFullDamage = static_cast<bool>(n);
4713 return NO_ERROR;
4714 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004715 case 1018: { // Modify Choreographer's phase offset
4716 n = data.readInt32();
4717 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4718 return NO_ERROR;
4719 }
4720 case 1019: { // Modify SurfaceFlinger's phase offset
4721 n = data.readInt32();
4722 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4723 return NO_ERROR;
4724 }
Irvel468051e2016-06-13 16:44:44 -07004725 case 1020: { // Layer updates interceptor
4726 n = data.readInt32();
4727 if (n) {
4728 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004729 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004730 }
4731 else{
4732 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004733 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004734 }
4735 return NO_ERROR;
4736 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004737 case 1021: { // Disable HWC virtual displays
4738 n = data.readInt32();
4739 mUseHwcVirtualDisplays = !n;
4740 return NO_ERROR;
4741 }
Romain Guy0147a172017-06-01 13:53:56 -07004742 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004743 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004744 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004745
Chia-I Wu28f320b2018-05-03 11:02:56 -07004746 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004747 return NO_ERROR;
4748 }
Romain Guy54f154a2017-10-24 21:40:32 +01004749 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004750 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004751 invalidateHwcGeometry();
4752 repaintEverything();
4753 return NO_ERROR;
4754 }
4755 case 1024: { // Is wide color gamut rendering/color management supported?
4756 reply->writeBool(hasWideColorDisplay);
4757 return NO_ERROR;
4758 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004759 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004760 n = data.readInt32();
4761 if (n) {
4762 ALOGV("LayerTracing enabled");
4763 mTracing.enable();
4764 doTracing("tracing.enable");
4765 reply->writeInt32(NO_ERROR);
4766 } else {
4767 ALOGV("LayerTracing disabled");
4768 status_t err = mTracing.disable();
4769 reply->writeInt32(err);
4770 }
4771 return NO_ERROR;
4772 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004773 case 1026: { // Get layer tracing status
4774 reply->writeBool(mTracing.isEnabled());
4775 return NO_ERROR;
4776 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004777 // Is a DisplayColorSetting supported?
4778 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004779 const auto display = getDefaultDisplayDevice();
4780 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004781 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004782 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004783
4784 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4785 switch (setting) {
4786 case DisplayColorSetting::MANAGED:
4787 reply->writeBool(hasWideColorDisplay);
4788 break;
4789 case DisplayColorSetting::UNMANAGED:
4790 reply->writeBool(true);
4791 break;
4792 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004793 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004794 break;
4795 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004796 reply->writeBool(
4797 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004798 break;
4799 }
4800 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004801 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004802 // Is VrFlinger active?
4803 case 1028: {
4804 Mutex::Autolock _l(mStateLock);
4805 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4806 return NO_ERROR;
4807 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004808 }
4809 }
4810 return err;
4811}
4812
Steven Thomas6d8110b2017-08-31 18:24:21 -07004813void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004814 android_atomic_or(1, &mRepaintEverything);
4815 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004816}
4817
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004818// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4819class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004820public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004821 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4822 ~WindowDisconnector() {
4823 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004824 }
4825
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004826private:
4827 ANativeWindow* mWindow;
4828 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004829};
4830
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004831status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4832 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4833 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4834 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004835 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004836 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004837
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004838 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004839
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004840 const auto display = getDisplayDeviceLocked(displayToken);
4841 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004842
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004843 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004844
4845 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004846 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004847 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004848}
4849
4850status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004851 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004852 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004853 ATRACE_CALL();
4854
4855 class LayerRenderArea : public RenderArea {
4856 public:
Robert Carr578038f2018-03-09 12:25:24 -08004857 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4858 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004859 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004860 mLayer(layer),
4861 mCrop(crop),
4862 mFlinger(flinger),
4863 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004864 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004865 Rect getBounds() const override {
4866 const Layer::State& layerState(mLayer->getDrawingState());
4867 return Rect(layerState.active.w, layerState.active.h);
4868 }
4869 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4870 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4871 bool isSecure() const override { return false; }
4872 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004873 Rect getSourceCrop() const override {
4874 if (mCrop.isEmpty()) {
4875 return getBounds();
4876 } else {
4877 return mCrop;
4878 }
4879 }
Robert Carr578038f2018-03-09 12:25:24 -08004880 class ReparentForDrawing {
4881 public:
4882 const sp<Layer>& oldParent;
4883 const sp<Layer>& newParent;
4884
4885 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4886 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004887 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004888 }
Robert Carr15eae092018-03-23 13:43:53 -07004889 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004890 };
4891
4892 void render(std::function<void()> drawLayers) override {
4893 if (!mChildrenOnly) {
4894 mTransform = mLayer->getTransform().inverse();
4895 drawLayers();
4896 } else {
4897 Rect bounds = getBounds();
4898 screenshotParentLayer =
4899 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4900 bounds.getWidth(), bounds.getHeight(), 0);
4901
4902 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4903 drawLayers();
4904 }
4905 }
chaviwa76b2712017-09-20 12:02:26 -07004906
chaviwa76b2712017-09-20 12:02:26 -07004907 private:
chaviw7206d492017-11-10 16:16:12 -08004908 const sp<Layer> mLayer;
4909 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004910
4911 // In the "childrenOnly" case we reparent the children to a screenshot
4912 // layer which has no properties set and which does not draw.
4913 sp<ContainerLayer> screenshotParentLayer;
4914 Transform mTransform;
4915
4916 SurfaceFlinger* mFlinger;
4917 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004918 };
4919
4920 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4921 auto parent = layerHandle->owner.promote();
4922
chaviw7206d492017-11-10 16:16:12 -08004923 if (parent == nullptr || parent->isPendingRemoval()) {
4924 ALOGE("captureLayers called with a removed parent");
4925 return NAME_NOT_FOUND;
4926 }
4927
Robert Carr578038f2018-03-09 12:25:24 -08004928 const int uid = IPCThreadState::self()->getCallingUid();
4929 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4930 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4931 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4932 return PERMISSION_DENIED;
4933 }
4934
chaviw7206d492017-11-10 16:16:12 -08004935 Rect crop(sourceCrop);
4936 if (sourceCrop.width() <= 0) {
4937 crop.left = 0;
4938 crop.right = parent->getCurrentState().active.w;
4939 }
4940
4941 if (sourceCrop.height() <= 0) {
4942 crop.top = 0;
4943 crop.bottom = parent->getCurrentState().active.h;
4944 }
4945
4946 int32_t reqWidth = crop.width() * frameScale;
4947 int32_t reqHeight = crop.height() * frameScale;
4948
Robert Carr578038f2018-03-09 12:25:24 -08004949 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004950
Robert Carr578038f2018-03-09 12:25:24 -08004951 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004952 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4953 if (!layer->isVisible()) {
4954 return;
Robert Carr578038f2018-03-09 12:25:24 -08004955 } else if (childrenOnly && layer == parent.get()) {
4956 return;
chaviwa76b2712017-09-20 12:02:26 -07004957 }
4958 visitor(layer);
4959 });
4960 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004961 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004962}
4963
4964status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4965 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004966 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004967 bool useIdentityTransform) {
4968 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004969
Iris Chang7501ed62018-04-30 14:45:42 +08004970 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004971
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004972 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4973 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4974 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4975 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004976
4977 // This mutex protects syncFd and captureResult for communication of the return values from the
4978 // main thread back to this Binder thread
4979 std::mutex captureMutex;
4980 std::condition_variable captureCondition;
4981 std::unique_lock<std::mutex> captureLock(captureMutex);
4982 int syncFd = -1;
4983 std::optional<status_t> captureResult;
4984
Robert Carr03480e22018-01-04 16:02:06 -08004985 const int uid = IPCThreadState::self()->getCallingUid();
4986 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4987
Dominik Laskowski8c001672018-05-30 16:52:06 -07004988 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004989 // If there is a refresh pending, bug out early and tell the binder thread to try again
4990 // after the refresh.
4991 if (mRefreshPending) {
4992 ATRACE_NAME("Skipping screenshot for now");
4993 std::unique_lock<std::mutex> captureLock(captureMutex);
4994 captureResult = std::make_optional<status_t>(EAGAIN);
4995 captureCondition.notify_one();
4996 return;
4997 }
4998
4999 status_t result = NO_ERROR;
5000 int fd = -1;
5001 {
5002 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005003 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005004 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5005 useIdentityTransform, forSystem, &fd);
5006 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005007 }
5008
5009 {
5010 std::unique_lock<std::mutex> captureLock(captureMutex);
5011 syncFd = fd;
5012 captureResult = std::make_optional<status_t>(result);
5013 captureCondition.notify_one();
5014 }
5015 });
5016
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005017 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005018 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005019 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005020 while (*captureResult == EAGAIN) {
5021 captureResult.reset();
5022 result = postMessageAsync(message);
5023 if (result != NO_ERROR) {
5024 return result;
5025 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005026 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005027 }
5028 result = *captureResult;
5029 }
5030
5031 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005032 sync_wait(syncFd, -1);
5033 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005034 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005035
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005036 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005037}
5038
chaviwa76b2712017-09-20 12:02:26 -07005039void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5040 TraverseLayersFunction traverseLayers, bool yswap,
5041 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005042 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005043
Lloyd Pique144e1162017-12-20 16:44:52 -08005044 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005045
5046 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005047 const auto raWidth = renderArea.getWidth();
5048 const auto raHeight = renderArea.getHeight();
5049
5050 const auto reqWidth = renderArea.getReqWidth();
5051 const auto reqHeight = renderArea.getReqHeight();
5052 Rect sourceCrop = renderArea.getSourceCrop();
5053
Iris Chang7501ed62018-04-30 14:45:42 +08005054 bool filtering = false;
5055 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5056 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5057 static_cast<int32_t>(reqHeight) != raWidth;
5058 } else {
5059 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5060 static_cast<int32_t>(reqHeight) != raHeight;
5061 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005062
Dan Stozac1879002014-05-22 15:59:05 -07005063 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005064 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005065 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005066 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005067 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5068 Transform tr;
5069 uint32_t flags = 0x00;
5070 switch (mPrimaryDisplayOrientation) {
5071 case DisplayState::eOrientation90:
5072 flags = Transform::ROT_90;
5073 break;
5074 case DisplayState::eOrientation180:
5075 flags = Transform::ROT_180;
5076 break;
5077 case DisplayState::eOrientation270:
5078 flags = Transform::ROT_270;
5079 break;
5080 }
5081 tr.set(flags, raWidth, raHeight);
5082 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005083 }
5084
5085 // ensure that sourceCrop is inside screen
5086 if (sourceCrop.left < 0) {
5087 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5088 }
chaviwa76b2712017-09-20 12:02:26 -07005089 if (sourceCrop.right > raWidth) {
5090 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005091 }
5092 if (sourceCrop.top < 0) {
5093 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5094 }
chaviwa76b2712017-09-20 12:02:26 -07005095 if (sourceCrop.bottom > raHeight) {
5096 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005097 }
5098
Chia-I Wu36574d92018-05-16 10:54:36 -07005099 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5100 engine.setOutputDataSpace(Dataspace::SRGB);
5101 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005102
Mathias Agopian180f10d2013-04-10 22:55:41 -07005103 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005104 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005105
Iris Chang7501ed62018-04-30 14:45:42 +08005106 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5107 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5108 // convert hw orientation into flag presentation
5109 // here inverse transform needed
5110 uint8_t hw_rot_90 = 0x00;
5111 uint8_t hw_flip_hv = 0x00;
5112 switch (mPrimaryDisplayOrientation) {
5113 case DisplayState::eOrientation90:
5114 hw_rot_90 = Transform::ROT_90;
5115 hw_flip_hv = Transform::ROT_180;
5116 break;
5117 case DisplayState::eOrientation180:
5118 hw_flip_hv = Transform::ROT_180;
5119 break;
5120 case DisplayState::eOrientation270:
5121 hw_rot_90 = Transform::ROT_90;
5122 break;
5123 }
5124
5125 // transform flags operation
5126 // 1) flip H V if both have ROT_90 flag
5127 // 2) XOR these flags
5128 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5129 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5130 if (rotation_rot_90 & hw_rot_90) {
5131 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5132 }
5133 rotation = static_cast<Transform::orientation_flags>
5134 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5135 }
5136
Mathias Agopian180f10d2013-04-10 22:55:41 -07005137 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005138 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005139 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005140 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005141
chaviw50da5042018-04-09 13:49:37 -07005142 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005143 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005144 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005145
chaviwa76b2712017-09-20 12:02:26 -07005146 traverseLayers([&](Layer* layer) {
5147 if (filtering) layer->setFiltering(true);
David Sodmanca10ed22018-04-16 14:10:25 -07005148 layer->drawNow(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005149 if (filtering) layer->setFiltering(false);
5150 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005151}
5152
chaviwa76b2712017-09-20 12:02:26 -07005153status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5154 TraverseLayersFunction traverseLayers,
5155 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005156 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005157 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005158 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005159 ATRACE_CALL();
5160
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005161 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005162
5163 traverseLayers([&](Layer* layer) {
5164 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5165 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005166
Robert Carr03480e22018-01-04 16:02:06 -08005167 // We allow the system server to take screenshots of secure layers for
5168 // use in situations like the Screen-rotation animation and place
5169 // the impetus on WindowManager to not persist them.
5170 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005171 ALOGW("FB is protected: PERMISSION_DENIED");
5172 return PERMISSION_DENIED;
5173 }
5174
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005175 // this binds the given EGLImage as a framebuffer for the
5176 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005177 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005178 if (bufferBond.getStatus() != NO_ERROR) {
5179 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005180 return INVALID_OPERATION;
5181 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005182
Dan Stozaabcda352017-06-01 14:37:39 -07005183 // this will in fact render into our dequeued buffer
5184 // via an FBO, which means we didn't have to create
5185 // an EGLSurface and therefore we're not
5186 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005187 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005188
Dan Stozaabcda352017-06-01 14:37:39 -07005189 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005190 getRenderEngine().finish();
5191 *outSyncFd = -1;
5192
chaviwa76b2712017-09-20 12:02:26 -07005193 const auto reqWidth = renderArea.getReqWidth();
5194 const auto reqHeight = renderArea.getReqHeight();
5195
Dan Stozaabcda352017-06-01 14:37:39 -07005196 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5197 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005198 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005199 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005200 } else {
5201 base::unique_fd syncFd = getRenderEngine().flush();
5202 if (syncFd < 0) {
5203 getRenderEngine().finish();
5204 }
5205 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005206 }
5207
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005208 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005209}
5210
Mathias Agopiand5556842013-09-19 17:08:37 -07005211void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005212 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005213 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005214 for (size_t y = 0; y < h; y++) {
5215 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5216 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005217 if (p[x] != 0xFF000000) return;
5218 }
5219 }
chaviwa76b2712017-09-20 12:02:26 -07005220 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005221
Robert Carr2047fae2016-11-28 14:09:09 -08005222 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005223 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005224 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005225 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5226 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5227 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5228 static_cast<float>(state.color.a));
5229 i++;
5230 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005231 }
5232}
5233
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005234// ---------------------------------------------------------------------------
5235
Dan Stoza412903f2017-04-27 13:42:17 -07005236void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5237 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005238}
5239
Dan Stoza412903f2017-04-27 13:42:17 -07005240void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5241 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005242}
5243
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005244void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5245 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005246 const LayerVector::Visitor& visitor) {
5247 // We loop through the first level of layers without traversing,
5248 // as we need to interpret min/max layer Z in the top level Z space.
5249 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005250 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005251 continue;
5252 }
5253 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005254 // relative layers are traversed in Layer::traverseInZOrder
5255 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005256 continue;
5257 }
5258 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005259 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005260 return;
5261 }
chaviwa76b2712017-09-20 12:02:26 -07005262 if (!layer->isVisible()) {
5263 return;
5264 }
5265 visitor(layer);
5266 });
5267 }
5268}
5269
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005270}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005271
Lloyd Pique074e8122018-07-26 12:57:23 -07005272
Mathias Agopian3f844832013-08-07 21:24:32 -07005273#if defined(__gl_h_)
5274#error "don't include gl/gl.h in this file"
5275#endif
5276
5277#if defined(__gl2_h_)
5278#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005279#endif