blob: 897f7b4e643713a20df22a20f44e9e982f3915af [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
Alec Mourie7d1d4a2019-02-05 01:13:46 +000017//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070022#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080023
24#include <algorithm>
25#include <cinttypes>
26#include <cmath>
27#include <cstdint>
28#include <functional>
29#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070030#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080031#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Lloyd Pique70d91362018-10-18 16:02:55 -070040#include <compositionengine/CompositionEngine.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070041#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070042#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080043#include <compositionengine/Layer.h>
44#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070045#include <compositionengine/RenderSurface.h>
Lloyd Pique0b785d82018-12-04 17:25:27 -080046#include <compositionengine/impl/LayerCompositionState.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070047#include <compositionengine/impl/OutputCompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080048#include <compositionengine/impl/OutputLayerCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080049#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070052#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080053#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080054#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080055#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070056#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070057#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070058#include <ui/ColorSpace.h>
59#include <ui/DebugUtils.h>
60#include <ui/DisplayInfo.h>
61#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <ui/GraphicBufferAllocator.h>
63#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070064#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070066#include <utils/String16.h>
67#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070068#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080069#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071
Mathias Agopian921e6ac2012-07-23 23:11:29 -070072#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070073#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074
Robert Carr578038f2018-03-09 12:25:24 -080075#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070076#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070077#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020078#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080079#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020080#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080081#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080082#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070084#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080085#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070086#include "NativeWindowSurface.h"
Ady Abraham03b02dd2019-03-21 15:40:11 -070087#include "RefreshRateOverlay.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070088#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070090#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091
Steven Thomasb02664d2017-07-26 18:48:28 -070092#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070093#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070094#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070095#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070096#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070097#include "Effects/Daltonizer.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -070098#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070099#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700100#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700101#include "Scheduler/EventControlThread.h"
102#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700103#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700104#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700105#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700106#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800107#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700108
Mathias Agopianff2ed702013-09-01 21:36:12 -0700109#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700110
David Sodman7e4ae112018-02-09 15:02:28 -0800111#include "android-base/stringprintf.h"
112
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900113#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800114#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
115#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900116#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900117
chaviw1d044282017-09-27 12:19:28 -0700118#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900119#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700120
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800121namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700122
Jaesoo Lee43518572017-01-23 19:03:16 +0900123using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900124using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900125using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800126
Yiwei Zhang5434a782018-12-05 18:06:32 -0800127using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700128using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700129using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800130using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700131using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700132using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900133
Steven Thomasb02664d2017-07-26 18:48:28 -0700134namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700135
136#pragma clang diagnostic push
137#pragma clang diagnostic error "-Wswitch-enum"
138
139bool isWideColorMode(const ColorMode colorMode) {
140 switch (colorMode) {
141 case ColorMode::DISPLAY_P3:
142 case ColorMode::ADOBE_RGB:
143 case ColorMode::DCI_P3:
144 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700145 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700146 case ColorMode::BT2100_PQ:
147 case ColorMode::BT2100_HLG:
148 return true;
149 case ColorMode::NATIVE:
150 case ColorMode::STANDARD_BT601_625:
151 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
152 case ColorMode::STANDARD_BT601_525:
153 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
154 case ColorMode::STANDARD_BT709:
155 case ColorMode::SRGB:
156 return false;
157 }
158 return false;
159}
160
Peiyong Lin34ea5b92019-03-15 18:40:15 -0700161bool isHdrColorMode(const ColorMode colorMode) {
162 switch (colorMode) {
163 case ColorMode::BT2100_PQ:
164 case ColorMode::BT2100_HLG:
165 return true;
166 case ColorMode::DISPLAY_P3:
167 case ColorMode::ADOBE_RGB:
168 case ColorMode::DCI_P3:
169 case ColorMode::BT2020:
170 case ColorMode::DISPLAY_BT2020:
171 case ColorMode::NATIVE:
172 case ColorMode::STANDARD_BT601_625:
173 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
174 case ColorMode::STANDARD_BT601_525:
175 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
176 case ColorMode::STANDARD_BT709:
177 case ColorMode::SRGB:
178 return false;
179 }
180 return false;
181}
182
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700183ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
184 switch (rotation) {
185 case ISurfaceComposer::eRotateNone:
186 return ui::Transform::ROT_0;
187 case ISurfaceComposer::eRotate90:
188 return ui::Transform::ROT_90;
189 case ISurfaceComposer::eRotate180:
190 return ui::Transform::ROT_180;
191 case ISurfaceComposer::eRotate270:
192 return ui::Transform::ROT_270;
193 }
194 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
195 return ui::Transform::ROT_0;
196}
197
Peiyong Linfca547f2018-07-09 13:03:33 -0700198#pragma clang diagnostic pop
199
Steven Thomasb02664d2017-07-26 18:48:28 -0700200class ConditionalLock {
201public:
202 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
203 if (lock) {
204 mMutex.lock();
205 }
206 }
207 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
208private:
209 Mutex& mMutex;
210 bool mLocked;
211};
Peiyong Linfca547f2018-07-09 13:03:33 -0700212
Peiyong Lin9d846a52018-11-05 13:18:20 -0800213// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
214bool validateCompositionDataspace(Dataspace dataspace) {
215 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
216}
217
Steven Thomasb02664d2017-07-26 18:48:28 -0700218} // namespace anonymous
219
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800220// ---------------------------------------------------------------------------
221
Mathias Agopian99b49842011-06-27 16:05:52 -0700222const String16 sHardwareTest("android.permission.HARDWARE_TEST");
223const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
224const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
225const String16 sDump("android.permission.DUMP");
226
227// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700228int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700229bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800230uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800231bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800232bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800233int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600234bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700235int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700236bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700237bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700238Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
239ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
240Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
241ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700242
Kalle Raitaa099a242017-01-11 11:17:29 -0800243std::string getHwcServiceName() {
244 char value[PROPERTY_VALUE_MAX] = {};
245 property_get("debug.sf.hwc_service_name", value, "default");
246 ALOGI("Using HWComposer service: '%s'", value);
247 return std::string(value);
248}
249
250bool useTrebleTestingOverride() {
251 char value[PROPERTY_VALUE_MAX] = {};
252 property_get("debug.sf.treble_testing_override", value, "false");
253 ALOGI("Treble testing override: '%s'", value);
254 return std::string(value) == "true";
255}
256
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800257std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
258 switch(displayColorSetting) {
259 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700260 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800261 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700262 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800263 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700264 return std::string("Enhanced");
265 default:
266 return std::string("Unknown ") +
267 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800268 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800269}
270
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700271SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800272
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700273SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
274 : mFactory(factory),
275 mPhaseOffsets(mFactory.createPhaseOffsets()),
276 mInterceptor(mFactory.createSurfaceInterceptor(this)),
277 mTimeStats(mFactory.createTimeStats()),
278 mEventQueue(mFactory.createMessageQueue()),
279 mCompositionEngine(mFactory.createCompositionEngine()) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800280
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700281SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800282 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800283
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900284 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800285
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900286 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700287
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900288 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700289
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900290 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800291
Steven Thomas050b2c82017-03-06 11:45:16 -0800292 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900293 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800294
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900295 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800296
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900297 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700298
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900299 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600300
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900301 mDefaultCompositionDataspace =
302 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
303 mWideColorGamutCompositionDataspace =
304 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
305 defaultCompositionDataspace = mDefaultCompositionDataspace;
306 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
307 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
308 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
309 wideColorGamutCompositionPixelFormat =
310 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700311
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900312 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800313
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900314 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
315 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
316 switch (tmpPrimaryDisplayOrientation) {
317 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700318 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800319 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900320 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700321 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800322 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900323 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700324 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800325 break;
326 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700327 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800328 break;
329 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700330 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800331
Sundong Ahn85131bd2019-02-18 15:51:53 +0900332 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800333
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800334 // debugging stuff...
335 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700336
Mathias Agopianb4b17302013-03-20 18:36:41 -0700337 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700338 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700339
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800340 property_get("debug.sf.showupdates", value, "0");
341 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700342
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700343 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000344
345 // DDMS debugging deprecated (b/120782499)
346 property_get("debug.sf.ddms", value, "0");
347 int debugDdms = atoi(value);
348 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700349
350 property_get("debug.sf.disable_backpressure", value, "0");
351 mPropagateBackpressure = !atoi(value);
352 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700353
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800354 property_get("debug.sf.enable_hwc_vds", value, "0");
355 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800356 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800357
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800358 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800359 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800360 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700361
Yiwei Zhang243b3782018-05-15 17:40:04 -0700362 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700363 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
364 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
365
Ana Krulece5a06e02019-03-06 17:09:03 -0800366 mUseSmart90ForVideo = use_smart_90_for_video(false);
Ana Krulecba13ab32019-02-20 14:14:12 -0800367 property_get("debug.sf.use_smart_90_for_video", value, "0");
Ana Krulece5a06e02019-03-06 17:09:03 -0800368
369 int int_value = atoi(value);
370 if (int_value) {
371 mUseSmart90ForVideo = true;
372 }
Ana Krulecba13ab32019-02-20 14:14:12 -0800373
Dan Stozaec460082018-12-17 15:35:09 -0800374 property_get("debug.sf.luma_sampling", value, "1");
375 mLumaSampling = atoi(value);
376
Ana Krulec757f63a2019-01-25 10:46:18 -0800377 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
378 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700379
Romain Guy11d63f42017-07-20 12:47:14 -0700380 // We should be reading 'persist.sys.sf.color_saturation' here
381 // but since /data may be encrypted, we need to wait until after vold
382 // comes online to attempt to read the property. The property is
383 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800384
385 if (useTrebleTestingOverride()) {
386 // Without the override SurfaceFlinger cannot connect to HIDL
387 // services that are not listed in the manifests. Considered
388 // deriving the setting from the set service name, but it
389 // would be brittle if the name that's not 'default' is used
390 // for production purposes later on.
391 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
392 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800393}
394
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800395void SurfaceFlinger::onFirstRef()
396{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800397 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800398}
399
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700400SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800401
Dan Stozac7014012014-02-14 15:03:43 -0800402void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800403{
404 // the window manager died on us. prepare its eulogy.
405
Andy McFadden13a082e2012-08-24 10:16:42 -0700406 // restore initial conditions (default device unblank, etc)
407 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800408
409 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700410 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800411}
412
Robert Carr1db73f62016-12-21 12:58:51 -0800413static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700414 status_t err = client->initCheck();
415 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800416 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800417 }
Robert Carr1db73f62016-12-21 12:58:51 -0800418 return nullptr;
419}
420
421sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
422 return initClient(new Client(this));
423}
424
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700425sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
426 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700427{
428 class DisplayToken : public BBinder {
429 sp<SurfaceFlinger> flinger;
430 virtual ~DisplayToken() {
431 // no more references, this display must be terminated
432 Mutex::Autolock _l(flinger->mStateLock);
433 flinger->mCurrentState.displays.removeItem(this);
434 flinger->setTransactionFlags(eDisplayTransactionNeeded);
435 }
436 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700437 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700438 : flinger(flinger) {
439 }
440 };
441
442 sp<BBinder> token = new DisplayToken(this);
443
444 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700445 // Display ID is assigned when virtual display is allocated by HWC.
446 DisplayDeviceState state;
447 state.isSecure = secure;
448 state.displayName = displayName;
449 mCurrentState.displays.add(token, state);
450 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700451 return token;
452}
453
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700454void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700455 Mutex::Autolock _l(mStateLock);
456
Dominik Laskowski075d3172018-05-24 15:50:06 -0700457 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
458 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700459 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700460 return;
461 }
462
Dominik Laskowski075d3172018-05-24 15:50:06 -0700463 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
464 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700465 ALOGE("destroyDisplay called for non-virtual display");
466 return;
467 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700468 mInterceptor->saveDisplayDeletion(state.sequenceId);
469 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700470 setTransactionFlags(eDisplayTransactionNeeded);
471}
472
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800473std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
474 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700475
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800476 const auto internalDisplayId = getInternalDisplayIdLocked();
477 if (!internalDisplayId) {
478 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700479 }
480
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800481 std::vector<PhysicalDisplayId> displayIds;
482 displayIds.reserve(mPhysicalDisplayTokens.size());
483 displayIds.push_back(internalDisplayId->value);
484
485 for (const auto& [id, token] : mPhysicalDisplayTokens) {
486 if (id != *internalDisplayId) {
487 displayIds.push_back(id.value);
488 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700489 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700490
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800491 return displayIds;
492}
493
494sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
495 Mutex::Autolock lock(mStateLock);
496 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700497}
498
Ady Abraham37965d42018-11-01 13:43:32 -0700499status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
500 if (!outGetColorManagement) {
501 return BAD_VALUE;
502 }
503 *outGetColorManagement = useColorManagement;
504 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700505}
506
Lloyd Pique441d5042018-10-18 16:49:51 -0700507HWComposer& SurfaceFlinger::getHwComposer() const {
508 return mCompositionEngine->getHwComposer();
509}
510
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700511renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
512 return mCompositionEngine->getRenderEngine();
513}
514
Lloyd Pique70d91362018-10-18 16:02:55 -0700515compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
516 return *mCompositionEngine.get();
517}
518
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800519void SurfaceFlinger::bootFinished()
520{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700521 if (mStartPropertySetThread->join() != NO_ERROR) {
522 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800523 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800524 const nsecs_t now = systemTime();
525 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000526 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700527
528 // wait patiently for the window manager death
529 const String16 name("window");
530 sp<IBinder> window(defaultServiceManager()->getService(name));
531 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700532 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700533 }
Robert Carr720e5062018-07-30 17:45:14 -0700534 sp<IBinder> input(defaultServiceManager()->getService(
535 String16("inputflinger")));
536 if (input == nullptr) {
537 ALOGE("Failed to link to input service");
538 } else {
539 mInputFlinger = interface_cast<IInputFlinger>(input);
540 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700541
Steven Thomas050b2c82017-03-06 11:45:16 -0800542 if (mVrFlinger) {
543 mVrFlinger->OnBootFinished();
544 }
545
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700546 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700547 // formerly we would just kill the process, but we now ask it to exit so it
548 // can choose where to stop the animation.
549 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700550
551 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
552 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
553 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700554
Ana Krulecbd6654b2019-02-15 15:18:15 -0800555 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800556 readPersistentProperties();
557 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800558
Ady Abraham97d04232019-03-05 19:48:12 -0800559 // set the refresh rate according to the policy
Alec Mouri0a1cc962019-03-14 12:33:02 -0700560 const auto& performanceRefreshRate =
Dominik Laskowski22488f62019-03-28 09:53:04 -0700561 mRefreshRateConfigs.getRefreshRate(RefreshRateType::PERFORMANCE);
Ady Abraham97d04232019-03-05 19:48:12 -0800562
Dominik Laskowski22488f62019-03-28 09:53:04 -0700563 if (performanceRefreshRate && isDisplayConfigAllowed(performanceRefreshRate->configId)) {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800564 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800565 } else {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800566 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800567 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800568 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800569}
570
Dan Stoza436ccf32018-06-21 12:10:12 -0700571uint32_t SurfaceFlinger::getNewTexture() {
572 {
573 std::lock_guard lock(mTexturePoolMutex);
574 if (!mTexturePool.empty()) {
575 uint32_t name = mTexturePool.back();
576 mTexturePool.pop_back();
577 ATRACE_INT("TexturePoolSize", mTexturePool.size());
578 return name;
579 }
580
581 // The pool was too small, so increase it for the future
582 ++mTexturePoolSize;
583 }
584
585 // The pool was empty, so we need to get a new texture name directly using a
586 // blocking call to the main thread
587 uint32_t name = 0;
588 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
589 return name;
590}
591
Mathias Agopian3f844832013-08-07 21:24:32 -0700592void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700593 std::lock_guard lock(mTexturePoolMutex);
594 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
595 // to actually delete this or not based on mTexturePoolSize
596 mTexturePool.push_back(texture);
597 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700598}
599
Wei Wangf9b05ee2017-07-19 20:59:39 -0700600// Do not call property_set on main thread which will be blocked by init
601// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700602void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700603 ALOGI( "SurfaceFlinger's main thread ready to run. "
604 "Initializing graphics H/W...");
605
Ana Krulec757f63a2019-01-25 10:46:18 -0800606 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900607
Steven Thomasb02664d2017-07-26 18:48:28 -0700608 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700609 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800610 mScheduler =
Ady Abraham09bd3922019-04-08 10:44:56 -0700611 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
612 mRefreshRateConfigs);
Ana Krulecc2870422019-01-29 19:00:58 -0800613 auto resyncCallback =
614 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800615
Ana Krulecc2870422019-01-29 19:00:58 -0800616 mAppConnectionHandle =
617 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
618 resyncCallback,
619 impl::EventThread::InterceptVSyncsCallback());
620 mSfConnectionHandle = mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
621 resyncCallback, [this](nsecs_t timestamp) {
622 mInterceptor->saveVSyncEvent(timestamp);
623 });
624
625 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
626 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
627 mSfConnectionHandle.get());
628
Kevin DuBois413287f2019-02-25 08:46:47 -0800629 mRegionSamplingThread =
630 new RegionSamplingThread(*this, *mScheduler,
631 RegionSamplingThread::EnvironmentTimingTunables());
632
Steven Thomasb02664d2017-07-26 18:48:28 -0700633 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700634 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700635 renderEngineFeature |= (useColorManagement ?
636 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700637 renderEngineFeature |= (useContextPriority ?
638 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin6a043d52019-04-01 17:18:21 -0700639 renderEngineFeature |=
640 (enable_protected_contents(false) ? renderengine::RenderEngine::ENABLE_PROTECTED_CONTEXT
641 : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700642
643 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800644 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700645 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700646 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800647 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700648
649 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
650 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700651 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
652 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800653 // Process any initial hotplug and resulting display changes.
654 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700655 const auto display = getDefaultDisplayDeviceLocked();
656 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700657 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700658 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800659
Steven Thomas050b2c82017-03-06 11:45:16 -0800660 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700661 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700662 // This callback is called from the vr flinger dispatch thread. We
663 // need to call signalTransaction(), which requires holding
664 // mStateLock when we're not on the main thread. Acquiring
665 // mStateLock from the vr flinger dispatch thread might trigger a
666 // deadlock in surface flinger (see b/66916578), so post a message
667 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700668 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700669 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
670 mVrFlingerRequestsDisplay = requestDisplay;
671 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700672 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800673 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700674 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
675 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700676 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700677 .value_or(0),
678 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800679 if (!mVrFlinger) {
680 ALOGE("Failed to start vrflinger");
681 }
682 }
683
Mathias Agopian92a979a2012-08-02 18:32:23 -0700684 // initialize our drawing state
685 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700686
Andy McFadden13a082e2012-08-24 10:16:42 -0700687 // set initial conditions (e.g. unblank default device)
688 initializeDisplays();
689
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700690 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700691
Wei Wangf9b05ee2017-07-19 20:59:39 -0700692 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700693
694 const bool presentFenceReliable =
695 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
696 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700697
698 if (mStartPropertySetThread->Start() != NO_ERROR) {
699 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800700 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800701
Alec Mouri93bc83d2019-04-17 14:47:43 -0700702 mScheduler->setChangeRefreshRateCallback(
703 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
704 Mutex::Autolock lock(mStateLock);
705 setRefreshRateTo(type, event);
706 });
Alec Mouridc28b372019-04-18 21:17:13 -0700707 mScheduler->setGetVsyncPeriodCallback([this] {
708 Mutex::Autolock lock(mStateLock);
709 return getVsyncPeriod();
710 });
Ady Abraham09bd3922019-04-08 10:44:56 -0700711
Dominik Laskowski22488f62019-03-28 09:53:04 -0700712 mRefreshRateConfigs.populate(getHwComposer().getConfigs(*display->getId()));
713 mRefreshRateStats.setConfigMode(getHwComposer().getActiveConfigIndex(*display->getId()));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800714
Dan Stoza9e56aa02015-11-02 13:00:03 -0800715 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700716}
717
Romain Guy11d63f42017-07-20 12:47:14 -0700718void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700719 Mutex::Autolock _l(mStateLock);
720
Romain Guy11d63f42017-07-20 12:47:14 -0700721 char value[PROPERTY_VALUE_MAX];
722
723 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800724 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700725 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800726 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100727
728 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700729 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800730
731 property_get("persist.sys.sf.color_mode", value, "0");
732 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700733}
734
Mathias Agopiana67e4182012-06-19 17:26:12 -0700735void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800736 // Start boot animation service by setting a property mailbox
737 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700738 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800739 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700740 if (mStartPropertySetThread->join() != NO_ERROR) {
741 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800742 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700743}
744
Mathias Agopian875d8e12013-06-07 15:35:48 -0700745size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700746 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700747}
748
Mathias Agopian875d8e12013-06-07 15:35:48 -0700749size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700750 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700751}
752
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800753// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800754
Jamie Gennis582270d2011-08-17 18:19:00 -0700755bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800756 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800757 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800758 return authenticateSurfaceTextureLocked(bufferProducer);
759}
760
761bool SurfaceFlinger::authenticateSurfaceTextureLocked(
762 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800763 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800764 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800765}
766
Brian Anderson6b376712017-04-04 10:51:39 -0700767status_t SurfaceFlinger::getSupportedFrameTimestamps(
768 std::vector<FrameEvent>* outSupported) const {
769 *outSupported = {
770 FrameEvent::REQUESTED_PRESENT,
771 FrameEvent::ACQUIRE,
772 FrameEvent::LATCH,
773 FrameEvent::FIRST_REFRESH_START,
774 FrameEvent::LAST_REFRESH_START,
775 FrameEvent::GPU_COMPOSITION_DONE,
776 FrameEvent::DEQUEUE_READY,
777 FrameEvent::RELEASE,
778 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700779 ConditionalLock _l(mStateLock,
780 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700781 if (!getHwComposer().hasCapability(
782 HWC2::Capability::PresentFenceIsNotReliable)) {
783 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
784 }
785 return NO_ERROR;
786}
787
Dominik Laskowski22488f62019-03-28 09:53:04 -0700788status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
789 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700790 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700791 return BAD_VALUE;
792 }
793
Dominik Laskowski22488f62019-03-28 09:53:04 -0700794 Mutex::Autolock lock(mStateLock);
795
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800796 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700797 if (!displayId) {
798 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700799 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700800
Mathias Agopian8b736f12012-08-13 17:54:26 -0700801 // TODO: Not sure if display density should handled by SF any longer
802 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700803 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700804 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700805 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800806 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700807 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700808 }
809 return density;
810 }
811 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700812 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700813 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700814 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700815 return getDensityFromProperty("ro.sf.lcd_density"); }
816 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700817
Dan Stoza7f7da322014-05-02 15:26:25 -0700818 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700819
Dominik Laskowski075d3172018-05-24 15:50:06 -0700820 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700821 DisplayInfo info = DisplayInfo();
822
Dan Stoza9e56aa02015-11-02 13:00:03 -0800823 float xdpi = hwConfig->getDpiX();
824 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700825
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700826 info.w = hwConfig->getWidth();
827 info.h = hwConfig->getHeight();
828 // Default display viewport to display width and height
829 info.viewportW = info.w;
830 info.viewportH = info.h;
831
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800832 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700833 // The density of the device is provided by a build property
834 float density = Density::getBuildDensity() / 160.0f;
835 if (density == 0) {
836 // the build doesn't provide a density -- this is wrong!
837 // use xdpi instead
838 ALOGE("ro.sf.lcd_density must be defined as a build property");
839 density = xdpi / 160.0f;
840 }
841 if (Density::getEmuDensity()) {
842 // if "qemu.sf.lcd_density" is specified, it overrides everything
843 xdpi = ydpi = density = Density::getEmuDensity();
844 density /= 160.0f;
845 }
846 info.density = density;
847
848 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700849 const auto display = getDefaultDisplayDeviceLocked();
850 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700851
852 // This is for screenrecord
853 const Rect viewport = display->getViewport();
854 if (viewport.isValid()) {
855 info.viewportW = uint32_t(viewport.getWidth());
856 info.viewportH = uint32_t(viewport.getHeight());
857 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700858 } else {
859 // TODO: where should this value come from?
860 static const int TV_DENSITY = 213;
861 info.density = TV_DENSITY / 160.0f;
862 info.orientation = 0;
863 }
864
Dan Stoza7f7da322014-05-02 15:26:25 -0700865 info.xdpi = xdpi;
866 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800867 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ady Abraham796beb02019-04-11 15:23:07 -0700868 const auto refreshRateType = mRefreshRateConfigs.getRefreshRateType(hwConfig->getId());
869 const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
870 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800871
Andy McFadden91b2ca82014-06-13 14:04:23 -0700872 // This is how far in advance a buffer must be queued for
873 // presentation at a given time. If you want a buffer to appear
874 // on the screen at time N, you must submit the buffer before
875 // (N - presentationDeadline).
876 //
877 // Normally it's one full refresh period (to give SF a chance to
878 // latch the buffer), but this can be reduced by configuring a
879 // DispSync offset. Any additional delays introduced by the hardware
880 // composer or panel must be accounted for here.
881 //
882 // We add an additional 1ms to allow for processing time and
883 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700884 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700885
886 // All non-virtual displays are currently considered secure.
887 info.secure = true;
888
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800889 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700890 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800891 std::swap(info.w, info.h);
892 }
893
Michael Wright28f24d02016-07-12 13:30:53 -0700894 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700895 }
896
Dan Stoza7f7da322014-05-02 15:26:25 -0700897 return NO_ERROR;
898}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700899
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700900status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
901 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700902 return BAD_VALUE;
903 }
904
Ana Krulecc2870422019-01-29 19:00:58 -0800905 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700906 return NO_ERROR;
907}
908
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700909int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
910 const auto display = getDisplayDevice(displayToken);
911 if (!display) {
912 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800913 return BAD_VALUE;
914 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700915
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700916 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700917}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700918
Ady Abraham03b02dd2019-03-21 15:40:11 -0700919void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800920 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800921
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800922 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800923 // config twice. However event generation config might have changed so we need to update it
924 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800925 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700926 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
927 mDesiredActiveConfig = info;
928 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800929
930 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800931 // This will trigger HWC refresh without resetting the idle timer.
932 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700933 // Start receiving vsync samples now, so that we can detect a period
934 // switch.
935 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
936 mPhaseOffsets->setRefreshRateType(info.type);
937 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
938 mVsyncModulator.onRefreshRateChangeInitiated();
939 mVsyncModulator.setPhaseOffsets(early, gl, late);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800940 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800941 mDesiredActiveConfigChanged = true;
942 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700943
944 if (mRefreshRateOverlay) {
945 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
946 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800947}
948
949status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
950 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800951
952 std::vector<int32_t> allowedConfig;
953 allowedConfig.push_back(mode);
954
955 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800956}
957
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800958void SurfaceFlinger::setActiveConfigInternal() {
959 ATRACE_CALL();
960
Dominik Laskowski22488f62019-03-28 09:53:04 -0700961 const auto display = getDefaultDisplayDeviceLocked();
962 if (!display) {
963 return;
964 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800965
Dominik Laskowski22488f62019-03-28 09:53:04 -0700966 std::lock_guard<std::mutex> lock(mActiveConfigLock);
967 mRefreshRateStats.setConfigMode(mUpcomingActiveConfig.configId);
968
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800969 display->setActiveConfig(mUpcomingActiveConfig.configId);
970
Ana Krulecc2870422019-01-29 19:00:58 -0800971 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Alec Mouri754c98a2019-03-18 18:53:42 -0700972 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Alec Mouri1c9e82b2019-03-07 12:24:05 -0800973 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
974 mVsyncModulator.setPhaseOffsets(early, gl, late);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800975 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700976
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800977 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -0800978 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
979 mUpcomingActiveConfig.configId);
980 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800981}
982
Dominik Laskowski22488f62019-03-28 09:53:04 -0700983bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -0800984 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800985 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -0700986 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800987 // fence has not signaled yet. wait for the next invalidate
Ady Abrahame1a5bcb2019-04-17 20:09:26 -0700988 mEventQueue->invalidateForHWC();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800989 return true;
990 }
991
992 // We received the present fence from the HWC, so we assume it successfully updated
993 // the config, hence we update SF.
994 mCheckPendingFence = false;
995 setActiveConfigInternal();
996 }
997
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800998 // Store the local variable to release the lock.
999 ActiveConfigInfo desiredActiveConfig;
1000 {
1001 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001002 if (!mDesiredActiveConfigChanged) {
1003 return false;
1004 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001005 desiredActiveConfig = mDesiredActiveConfig;
1006 }
1007
Dominik Laskowski22488f62019-03-28 09:53:04 -07001008 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001009 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1010 // display is not valid or we are already in the requested mode
1011 // on both cases there is nothing left to do
1012 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham6398a0a2019-04-18 19:30:44 -07001013 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001014 mDesiredActiveConfigChanged = false;
1015 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
1016 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001017 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001018
Ady Abraham838de062019-02-04 10:24:03 -08001019 // Desired active config was set, it is different than the config currently in use, however
1020 // allowed configs might have change by the time we process the refresh.
1021 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001022 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham838de062019-02-04 10:24:03 -08001023 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Alec Mouriecf2e0f2019-03-26 13:26:17 -07001024 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
Ady Abraham838de062019-02-04 10:24:03 -08001025 mDesiredActiveConfig.configId = display->getActiveConfig();
Ady Abraham6398a0a2019-04-18 19:30:44 -07001026 mDesiredActiveConfigChanged = false;
1027 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ady Abraham838de062019-02-04 10:24:03 -08001028 return false;
1029 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001030 mUpcomingActiveConfig = desiredActiveConfig;
1031 const auto displayId = display->getId();
1032 LOG_ALWAYS_FATAL_IF(!displayId);
1033
1034 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1035 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1036
1037 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -08001038 mCheckPendingFence = true;
Ady Abrahame1a5bcb2019-04-17 20:09:26 -07001039 mEventQueue->invalidateForHWC();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001040 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001041}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001042
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001043status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1044 Vector<ColorMode>* outColorModes) {
1045 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001046 return BAD_VALUE;
1047 }
1048
Peiyong Lina52f0292018-03-14 17:26:31 -07001049 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001050 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001051 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1052
1053 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1054 if (!displayId) {
1055 return NAME_NOT_FOUND;
1056 }
1057
Dominik Laskowski075d3172018-05-24 15:50:06 -07001058 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001059 }
Michael Wright28f24d02016-07-12 13:30:53 -07001060 outColorModes->clear();
1061 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1062
1063 return NO_ERROR;
1064}
1065
Daniel Solomon42d04562019-01-20 21:03:19 -08001066status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1067 ui::DisplayPrimaries &primaries) {
1068 if (!displayToken) {
1069 return BAD_VALUE;
1070 }
1071
1072 // Currently we only support this API for a single internal display.
1073 if (getInternalDisplayToken() != displayToken) {
1074 return BAD_VALUE;
1075 }
1076
1077 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1078 return NO_ERROR;
1079}
1080
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001081ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1082 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001083 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001084 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001085 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001086}
1087
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001088status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001089 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001090 Vector<ColorMode> modes;
1091 getDisplayColorModes(displayToken, &modes);
1092 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1093 if (mode < ColorMode::NATIVE || !exists) {
1094 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1095 decodeColorMode(mode).c_str(), mode, displayToken.get());
1096 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001097 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001098 const auto display = getDisplayDevice(displayToken);
1099 if (!display) {
1100 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1101 decodeColorMode(mode).c_str(), mode, displayToken.get());
1102 } else if (display->isVirtual()) {
1103 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1104 decodeColorMode(mode).c_str(), mode);
1105 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001106 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1107 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001108 }
1109 }));
1110
Michael Wright28f24d02016-07-12 13:30:53 -07001111 return NO_ERROR;
1112}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001113
Svetoslavd85084b2014-03-20 10:28:31 -07001114status_t SurfaceFlinger::clearAnimationFrameStats() {
1115 Mutex::Autolock _l(mStateLock);
1116 mAnimFrameTracker.clearStats();
1117 return NO_ERROR;
1118}
1119
1120status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1121 Mutex::Autolock _l(mStateLock);
1122 mAnimFrameTracker.getStats(outStats);
1123 return NO_ERROR;
1124}
1125
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001126status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1127 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001128 Mutex::Autolock _l(mStateLock);
1129
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001130 const auto display = getDisplayDeviceLocked(displayToken);
1131 if (!display) {
1132 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001133 return BAD_VALUE;
1134 }
1135
Peiyong Linfb069302018-04-25 14:34:31 -07001136 // At this point the DisplayDeivce should already be set up,
1137 // meaning the luminance information is already queried from
1138 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001139 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001140 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1141 capabilities.getDesiredMaxLuminance(),
1142 capabilities.getDesiredMaxAverageLuminance(),
1143 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001144
1145 return NO_ERROR;
1146}
1147
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001148status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1149 ui::PixelFormat* outFormat,
1150 ui::Dataspace* outDataspace,
1151 uint8_t* outComponentMask) const {
1152 if (!outFormat || !outDataspace || !outComponentMask) {
1153 return BAD_VALUE;
1154 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001155 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001156 if (!display || !display->getId()) {
1157 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1158 return BAD_VALUE;
1159 }
1160 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1161 outDataspace, outComponentMask);
1162}
1163
Kevin DuBois74e53772018-11-19 10:52:38 -08001164status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1165 bool enable, uint8_t componentMask,
1166 uint64_t maxFrames) const {
1167 const auto display = getDisplayDevice(displayToken);
1168 if (!display || !display->getId()) {
1169 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1170 return BAD_VALUE;
1171 }
1172
1173 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1174 componentMask, maxFrames);
1175}
1176
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001177status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1178 uint64_t maxFrames, uint64_t timestamp,
1179 DisplayedFrameStats* outStats) const {
1180 const auto display = getDisplayDevice(displayToken);
1181 if (!display || !display->getId()) {
1182 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1183 return BAD_VALUE;
1184 }
1185
1186 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1187 outStats);
1188}
1189
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001190status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1191 if (!outSupported) {
1192 return BAD_VALUE;
1193 }
1194 *outSupported = getRenderEngine().supportsProtectedContent();
1195 return NO_ERROR;
1196}
1197
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001198status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1199 bool* outIsWideColorDisplay) const {
1200 if (!displayToken || !outIsWideColorDisplay) {
1201 return BAD_VALUE;
1202 }
1203 Mutex::Autolock _l(mStateLock);
1204 const auto display = getDisplayDeviceLocked(displayToken);
1205 if (!display) {
1206 return BAD_VALUE;
1207 }
1208 *outIsWideColorDisplay = display->hasWideColorGamut();
1209 return NO_ERROR;
1210}
1211
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001212status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001213 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001214 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001215
Chia-I Wu90f669f2017-10-05 14:24:41 -07001216 if (mInjectVSyncs == enable) {
1217 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001218 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001219
Ana Krulecc2870422019-01-29 19:00:58 -08001220 auto resyncCallback =
1221 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001222
Ady Abraham46e2f3e2019-03-18 16:40:15 -07001223 // TODO(b/128863962): Part of the Injector should be refactored, so that it
Ana Krulec98b5b242018-08-10 15:03:23 -07001224 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001225 if (enable) {
1226 ALOGV("VSync Injections enabled");
1227 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001228 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001229 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001230 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001231 impl::EventThread::InterceptVSyncsCallback(),
1232 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001233 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001234 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001235 } else {
1236 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001237 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1238 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001239 }
1240
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001241 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001242 }));
1243
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001244 return NO_ERROR;
1245}
1246
1247status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001248 Mutex::Autolock _l(mStateLock);
1249
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001250 if (!mInjectVSyncs) {
1251 ALOGE("VSync Injections not enabled");
1252 return BAD_VALUE;
1253 }
1254 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1255 ALOGV("Injecting VSync inside SurfaceFlinger");
1256 mVSyncInjector->onInjectSyncEvent(when);
1257 }
1258 return NO_ERROR;
1259}
1260
Lloyd Pique755e3192018-01-31 16:46:15 -08001261status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1262 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001263 // Try to acquire a lock for 1s, fail gracefully
1264 const status_t err = mStateLock.timedLock(s2ns(1));
1265 const bool locked = (err == NO_ERROR);
1266 if (!locked) {
1267 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1268 return TIMED_OUT;
1269 }
1270
1271 outLayers->clear();
1272 mCurrentState.traverseInZOrder([&](Layer* layer) {
1273 outLayers->push_back(layer->getLayerDebugInfo());
1274 });
1275
1276 mStateLock.unlock();
1277 return NO_ERROR;
1278}
1279
Peiyong Linc6780972018-10-28 15:24:08 -07001280status_t SurfaceFlinger::getCompositionPreference(
1281 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1282 Dataspace* outWideColorGamutDataspace,
1283 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001284 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001285 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001286 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001287 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001288 return NO_ERROR;
1289}
1290
Dan Stozaec460082018-12-17 15:35:09 -08001291status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1292 const sp<IBinder>& stopLayerHandle,
1293 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001294 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001295 return BAD_VALUE;
1296 }
1297 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001298 return NO_ERROR;
1299}
1300
Dan Stozaec460082018-12-17 15:35:09 -08001301status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001302 if (!listener) {
1303 return BAD_VALUE;
1304 }
Dan Stozaec460082018-12-17 15:35:09 -08001305 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001306 return NO_ERROR;
1307}
Dan Gittik57e63c52019-01-18 16:37:54 +00001308
1309status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1310 bool* outSupport) const {
1311 if (!displayToken || !outSupport) {
1312 return BAD_VALUE;
1313 }
1314 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1315 if (!displayId) {
1316 return NAME_NOT_FOUND;
1317 }
1318 *outSupport =
1319 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1320 return NO_ERROR;
1321}
1322
1323status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1324 float brightness) const {
1325 if (!displayToken) {
1326 return BAD_VALUE;
1327 }
1328 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1329 if (!displayId) {
1330 return NAME_NOT_FOUND;
1331 }
1332 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1333}
1334
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001335// ----------------------------------------------------------------------------
1336
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001337sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1338 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulecc2870422019-01-29 19:00:58 -08001339 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001340 Mutex::Autolock lock(mStateLock);
1341 return getVsyncPeriod();
1342 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001343
Ana Krulecc2870422019-01-29 19:00:58 -08001344 const auto& handle =
1345 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001346
Ana Krulecc2870422019-01-29 19:00:58 -08001347 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Mathias Agopianbb641242010-05-18 17:06:55 -07001348}
1349
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001350// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001351
1352void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001353 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001354}
1355
1356void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001357 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001358}
1359
1360void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001361 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001362}
1363
1364void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001365 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001366 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001367}
1368
1369status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001370 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001371 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001372}
1373
1374status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001375 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001376 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001377 if (res == NO_ERROR) {
1378 msg->wait();
1379 }
1380 return res;
1381}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001382
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001383void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001384 do {
1385 waitForEvent();
1386 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001387}
1388
Dominik Laskowski83b88212018-12-11 13:34:06 -08001389nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001390 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001391 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1392 return 0;
1393 }
1394
1395 const auto config = getHwComposer().getActiveConfig(*displayId);
1396 return config ? config->getVsyncPeriod() : 0;
1397}
1398
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001399void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1400 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001401 ATRACE_NAME("SF onVsync");
1402
Steven Thomas3cfac282017-02-06 12:29:30 -08001403 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001404 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001405 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001406 return;
1407 }
1408
Dominik Laskowski075d3172018-05-24 15:50:06 -07001409 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001410 return;
1411 }
1412
Dominik Laskowski075d3172018-05-24 15:50:06 -07001413 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001414 // For now, we don't do anything with external display vsyncs.
1415 return;
1416 }
1417
Alec Mouri754c98a2019-03-18 18:53:42 -07001418 bool periodChanged = false;
1419 mScheduler->addResyncSample(timestamp, &periodChanged);
1420 if (periodChanged) {
1421 mVsyncModulator.onRefreshRateChangeDetected();
1422 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001423}
1424
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001425void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001426 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1427 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001428}
1429
Dominik Laskowski22488f62019-03-28 09:53:04 -07001430bool SurfaceFlinger::isDisplayConfigAllowed(int32_t configId) {
1431 return mAllowedDisplayConfigs.empty() || mAllowedDisplayConfigs.count(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001432}
1433
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001434void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001435 const auto display = getDefaultDisplayDeviceLocked();
1436 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001437 return;
1438 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001439 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001440
Ana Krulec7d1d6832018-12-27 11:10:09 -08001441 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowski22488f62019-03-28 09:53:04 -07001442 const auto& refreshRateConfig = mRefreshRateConfigs.getRefreshRate(refreshRate);
Alec Mouri0a1cc962019-03-14 12:33:02 -07001443 if (!refreshRateConfig) {
1444 ALOGV("Skipping refresh rate change request for unsupported rate.");
Ady Abraham1902d072019-03-01 17:18:59 -08001445 return;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001446 }
Ady Abraham1902d072019-03-01 17:18:59 -08001447
Alec Mouri0a1cc962019-03-14 12:33:02 -07001448 const int desiredConfigId = refreshRateConfig->configId;
1449
Dominik Laskowski22488f62019-03-28 09:53:04 -07001450 if (!isDisplayConfigAllowed(desiredConfigId)) {
Ady Abraham1902d072019-03-01 17:18:59 -08001451 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1452 return;
1453 }
1454
Dominik Laskowski22488f62019-03-28 09:53:04 -07001455 setDesiredActiveConfig({refreshRate, desiredConfigId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001456}
1457
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001458void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001459 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001460 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001461 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001462
Lloyd Piqueba04e622017-12-14 17:11:26 -08001463 // Ignore events that do not have the right sequenceId.
1464 if (sequenceId != getBE().mComposerSequenceId) {
1465 return;
1466 }
1467
Steven Thomasb02664d2017-07-26 18:48:28 -07001468 // Only lock if we're not on the main thread. This function is normally
1469 // called on a hwbinder thread, but for the primary display it's called on
1470 // the main thread with the state lock already held, so don't attempt to
1471 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001472 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001473
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001474 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001475
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001476 if (std::this_thread::get_id() == mMainThreadId) {
1477 // Process all pending hot plug events immediately if we are on the main thread.
1478 processDisplayHotplugEventsLocked();
1479 }
1480
Lloyd Piqueba04e622017-12-14 17:11:26 -08001481 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001482}
1483
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001484void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001485 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001486 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001487 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001488 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001489 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001490}
1491
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001492void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001493 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001494 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001495 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001496 getHwComposer().setVsyncEnabled(*displayId,
1497 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1498 }
Mathias Agopian86303202012-07-24 22:46:10 -07001499}
1500
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001501// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001502void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001503 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001504 // Clear the drawing state so that the logic inside of
1505 // handleTransactionLocked will fire. It will determine the delta between
1506 // mCurrentState and mDrawingState and re-apply all changes when we make the
1507 // transition.
1508 mDrawingState.displays.clear();
1509 mDisplays.clear();
1510}
1511
Steven Thomas050b2c82017-03-06 11:45:16 -08001512void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001513 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001514 if (!mVrFlinger)
1515 return;
1516 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001517 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001518 return;
1519 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001520
Lloyd Pique441d5042018-10-18 16:49:51 -07001521 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001522 ALOGE("Vr flinger is only supported for remote hardware composer"
1523 " service connections. Ignoring request to transition to vr"
1524 " flinger.");
1525 mVrFlingerRequestsDisplay = false;
1526 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001527 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001528
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001529 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001530
Steven Thomas0123ac62018-07-12 11:32:34 -07001531 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001532 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001533
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001534 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001535
1536 // Clear out all the output layers from the composition engine for all
1537 // displays before destroying the hardware composer interface. This ensures
1538 // any HWC layers are destroyed through that interface before it becomes
1539 // invalid.
1540 for (const auto& [token, displayDevice] : mDisplays) {
1541 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1542 compositionengine::Output::OutputLayers());
1543 }
1544
Steven Thomas0123ac62018-07-12 11:32:34 -07001545 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1546 // called below. Clear the reference now so we don't accidentally use it
1547 // later.
1548 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001549
Steven Thomasb02664d2017-07-26 18:48:28 -07001550 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001551 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001552 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001553
Steven Thomasb02664d2017-07-26 18:48:28 -07001554 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001555 // Delete the current instance before creating the new one
1556 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1557 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1558 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1559 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001560
Lloyd Pique441d5042018-10-18 16:49:51 -07001561 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001562 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001563
1564 if (vrFlingerRequestsDisplay) {
1565 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001566 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001567
1568 mVisibleRegionsDirty = true;
1569 invalidateHwcGeometry();
1570
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001571 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001572 display = getDefaultDisplayDeviceLocked();
1573 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001574 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001575
Steven Thomasb02664d2017-07-26 18:48:28 -07001576 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001577 const nsecs_t vsyncPeriod = getVsyncPeriod();
1578 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001579
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001580 // The present fences returned from vr_hwc are not an accurate
1581 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001582 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001583
Steven Thomasb02664d2017-07-26 18:48:28 -07001584 // Use phase of 0 since phase is not known.
1585 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001586 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001587 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001588
Ana Krulecc2870422019-01-29 19:00:58 -08001589 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001590
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001591 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001592 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001593}
1594
Ady Abrahambe0f9482019-04-24 15:41:53 -07001595bool SurfaceFlinger::previousFrameMissed() NO_THREAD_SAFETY_ANALYSIS {
1596 // We are storing the last 2 present fences. If sf's phase offset is to be
1597 // woken up before the actual vsync but targeting the next vsync, we need to check
1598 // fence N-2
1599 const sp<Fence>& fence =
1600 mVsyncModulator.getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
1601 ? mPreviousPresentFences[0]
1602 : mPreviousPresentFences[1];
1603
1604 return fence != Fence::NO_FENCE && (fence->getStatus() == Fence::Status::Unsignaled);
1605}
1606
Dominik Laskowski22488f62019-03-28 09:53:04 -07001607void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001608 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001609 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001610 case MessageQueue::INVALIDATE: {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001611 bool frameMissed = previousFrameMissed();
Alec Mouricc0fc602019-02-26 21:45:19 -08001612 bool hwcFrameMissed = mHadDeviceComposition && frameMissed;
1613 bool gpuFrameMissed = mHadClientComposition && frameMissed;
1614 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
1615 ATRACE_INT("HwcFrameMissed", static_cast<int>(hwcFrameMissed));
1616 ATRACE_INT("GpuFrameMissed", static_cast<int>(gpuFrameMissed));
1617 if (frameMissed) {
1618 mFrameMissedCount++;
1619 mTimeStats->incrementMissedFrames();
1620 }
1621
Alec Mouri40189b02019-03-05 15:07:54 -08001622 if (hwcFrameMissed) {
1623 mHwcFrameMissedCount++;
1624 }
1625
1626 if (gpuFrameMissed) {
1627 mGpuFrameMissedCount++;
1628 }
1629
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001630 if (mUseSmart90ForVideo) {
1631 // This call is made each time SF wakes up and creates a new frame. It is part
1632 // of video detection feature.
Ady Abraham09bd3922019-04-08 10:44:56 -07001633 mScheduler->updateFpsBasedOnContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001634 }
1635
Ady Abrahamb838aed2019-02-12 15:30:16 -08001636 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001637 break;
1638 }
1639
Alec Mourife3dc942019-02-12 14:19:18 -08001640 // For now, only propagate backpressure when missing a hwc frame.
Alec Mourib0f45822019-05-06 11:01:35 -07001641 if (hwcFrameMissed && !gpuFrameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001642 if (mPropagateBackpressure) {
1643 signalLayerUpdate();
1644 break;
1645 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001646 }
Dan Stoza50182882016-07-08 12:02:20 -07001647
Steven Thomas050b2c82017-03-06 11:45:16 -08001648 // Now that we're going to make it to the handleMessageTransaction()
1649 // call below it's safe to call updateVrFlinger(), which will
1650 // potentially trigger a display handoff.
1651 updateVrFlinger();
1652
Dan Stoza6b9454d2014-11-07 16:00:59 -08001653 bool refreshNeeded = handleMessageTransaction();
1654 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001655
1656 updateCursorAsync();
1657 updateInputFlinger();
1658
Dan Stoza58784442014-12-02 16:58:17 -08001659 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001660 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001661 // Signal a refresh if a transaction modified the window state,
1662 // a new buffer was latched, or if HWC has requested a full
1663 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001664 signalRefresh();
1665 }
1666 break;
1667 }
1668 case MessageQueue::REFRESH: {
1669 handleMessageRefresh();
1670 break;
1671 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001672 }
1673}
1674
Dan Stoza6b9454d2014-11-07 16:00:59 -08001675bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001676 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001677 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001678
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001679 bool flushedATransaction = flushTransactionQueues();
1680
1681 bool runHandleTransaction = transactionFlags &&
1682 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1683
1684 if (runHandleTransaction) {
1685 handleTransaction(eTransactionMask);
1686 } else {
1687 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001688 }
1689
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001690 if (transactionFlushNeeded()) {
1691 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001692 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001693
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001694 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001695}
1696
Mathias Agopian4fec8732012-06-29 14:12:52 -07001697void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001698 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001699
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001700 mRefreshPending = false;
1701
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001702 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001703 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001704 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001705 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001706 for (const auto& [token, display] : mDisplays) {
1707 beginFrame(display);
1708 prepareFrame(display);
1709 doDebugFlashRegions(display, repaintEverything);
1710 doComposition(display, repaintEverything);
1711 }
1712
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001713 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001714
1715 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001716 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001717
Dan Stozabfbffeb2016-07-21 14:49:33 -07001718 mHadClientComposition = false;
Alec Mouricc0fc602019-02-26 21:45:19 -08001719 mHadDeviceComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001720 for (const auto& [token, displayDevice] : mDisplays) {
1721 auto display = displayDevice->getCompositionDisplay();
1722 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001723 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001724 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Alec Mouricc0fc602019-02-26 21:45:19 -08001725 mHadDeviceComposition =
1726 mHadDeviceComposition || getHwComposer().hasDeviceComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001727 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001728
Jorim Jaggi90535212018-05-23 23:44:06 +02001729 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001730
David Sodman7e4ae112018-02-09 15:02:28 -08001731 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001732}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001733
David Sodmanfa9b2af2017-12-24 13:28:59 -08001734
1735bool SurfaceFlinger::handleMessageInvalidate() {
1736 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001737 bool refreshNeeded = handlePageFlip();
1738
Vishnu Nair4351ad52019-02-11 14:13:02 -08001739 if (mVisibleRegionsDirty) {
1740 computeLayerBounds();
Nataniel Borges2b796da2019-02-15 13:32:18 -08001741 if (mTracingEnabled) {
1742 mTracing.notify("visibleRegionsDirty");
1743 }
Vishnu Nair4351ad52019-02-11 14:13:02 -08001744 }
1745
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001746 for (auto& layer : mLayersPendingRefresh) {
1747 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001748 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001749 invalidateLayerStack(layer, visibleReg);
1750 }
1751 mLayersPendingRefresh.clear();
1752 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001753}
1754
David Sodman79bba0e2018-08-05 18:07:49 -07001755void SurfaceFlinger::calculateWorkingSet() {
1756 ATRACE_CALL();
1757 ALOGV(__FUNCTION__);
1758
David Sodman79bba0e2018-08-05 18:07:49 -07001759 // build the h/w work list
1760 if (CC_UNLIKELY(mGeometryInvalid)) {
1761 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001762 for (const auto& [token, displayDevice] : mDisplays) {
1763 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001764
Lloyd Piquea83776c2019-01-29 18:42:32 -08001765 uint32_t zOrder = 0;
David Sodman79bba0e2018-08-05 18:07:49 -07001766
Lloyd Piquea83776c2019-01-29 18:42:32 -08001767 for (auto& layer : display->getOutputLayersOrderedByZ()) {
1768 auto& compositionState = layer->editState();
1769 compositionState.forceClientComposition = false;
1770 if (!compositionState.hwc || mDebugDisableHWC || mDebugRegion) {
1771 compositionState.forceClientComposition = true;
David Sodman79bba0e2018-08-05 18:07:49 -07001772 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001773
Lloyd Piquea83776c2019-01-29 18:42:32 -08001774 // The output Z order is set here based on a simple counter.
1775 compositionState.z = zOrder++;
1776
1777 // Update the display independent composition state. This goes
1778 // to the general composition layer state structure.
1779 // TODO: Do this once per compositionengine::CompositionLayer.
1780 layer->getLayerFE().latchCompositionState(layer->getLayer().editState().frontEnd,
1781 true);
1782
1783 // Recalculate the geometry state of the output layer.
1784 layer->updateCompositionState(true);
1785
1786 // Write the updated geometry state to the HWC
1787 layer->writeStateToHWC(true);
David Sodman79bba0e2018-08-05 18:07:49 -07001788 }
1789 }
1790 }
1791
1792 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001793 for (const auto& [token, displayDevice] : mDisplays) {
1794 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001795 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001796 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001797 continue;
1798 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001799 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001800
1801 if (mDrawingState.colorMatrixChanged) {
1802 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001803 }
Peiyong Linc502cb72019-03-01 15:00:23 -08001804 Dataspace targetDataspace = Dataspace::UNKNOWN;
1805 if (useColorManagement) {
1806 ColorMode colorMode;
1807 RenderIntent renderIntent;
1808 pickColorMode(displayDevice, &colorMode, &targetDataspace, &renderIntent);
1809 display->setColorMode(colorMode, targetDataspace, renderIntent);
1810 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001811 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001812 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001813 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001814 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1815 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001816 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001817 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001818 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1819 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001820 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001821 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001822 }
1823
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001824 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001825 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001826 }
1827
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001828 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001829 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001830 layer->setCompositionType(displayDevice,
1831 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001832 continue;
1833 }
1834
Lloyd Pique32cbe282018-10-19 13:09:22 -07001835 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001836 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Peiyong Lin34ea5b92019-03-15 18:40:15 -07001837 displayDevice->getSupportedPerFrameMetadata(),
1838 isHdrColorMode(displayState.colorMode) ? Dataspace::UNKNOWN
1839 : targetDataspace);
David Sodman79bba0e2018-08-05 18:07:49 -07001840 }
1841 }
1842
1843 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001844
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001845 for (const auto& [token, displayDevice] : mDisplays) {
1846 auto display = displayDevice->getCompositionDisplay();
1847 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Lloyd Pique0b785d82018-12-04 17:25:27 -08001848 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1849 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1850 layer->getCompositionType(displayDevice));
David Sodmanba340492018-08-05 21:51:33 -07001851 }
1852 }
David Sodman79bba0e2018-08-05 18:07:49 -07001853}
1854
Lloyd Pique32cbe282018-10-19 13:09:22 -07001855void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1856 bool repaintEverything) {
1857 auto display = displayDevice->getCompositionDisplay();
1858 const auto& displayState = display->getState();
1859
Mathias Agopiancd60f992012-08-16 16:28:27 -07001860 // is debugging enabled
1861 if (CC_LIKELY(!mDebugRegion))
1862 return;
1863
Lloyd Pique32cbe282018-10-19 13:09:22 -07001864 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001865 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001866 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001867 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001868 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001869 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001870 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001871
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001872 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001873 }
1874 }
1875
Lloyd Pique32cbe282018-10-19 13:09:22 -07001876 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001877
1878 if (mDebugRegion > 1) {
1879 usleep(mDebugRegion * 1000);
1880 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001881
Lloyd Pique32cbe282018-10-19 13:09:22 -07001882 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001883}
1884
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001885void SurfaceFlinger::logLayerStats() {
1886 ATRACE_CALL();
1887 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001888 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001889 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001890 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001891 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001892 }
1893 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001894
1895 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001896 }
1897}
1898
David Sodman2b406362017-12-15 13:33:47 -08001899void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001900{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001901 ATRACE_CALL();
1902 ALOGV("preComposition");
1903
David Sodman2b406362017-12-15 13:33:47 -08001904 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1905
Mathias Agopiancd60f992012-08-16 16:28:27 -07001906 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001907 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001908 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001909 needExtraInvalidate = true;
1910 }
Robert Carr2047fae2016-11-28 14:09:09 -08001911 });
1912
Mathias Agopiancd60f992012-08-16 16:28:27 -07001913 if (needExtraInvalidate) {
1914 signalLayerUpdate();
1915 }
1916}
1917
Ana Krulece588e312018-09-18 12:32:24 -07001918void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1919 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001920 // Update queue of past composite+present times and determine the
1921 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001922 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001923 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001924 while (!getBE().mCompositePresentTimes.empty()) {
1925 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001926 // Cached values should have been updated before calling this method,
1927 // which helps avoid duplicate syscalls.
1928 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1929 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1930 break;
1931 }
1932 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001933 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001934 }
1935
1936 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001937 while (getBE().mCompositePresentTimes.size() > 16) {
1938 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001939 }
1940
Ana Krulece588e312018-09-18 12:32:24 -07001941 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001942}
1943
Ana Krulece588e312018-09-18 12:32:24 -07001944void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1945 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001946 // Integer division and modulo round toward 0 not -inf, so we need to
1947 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001948 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1949 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1950 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001951
Ana Krulec757f63a2019-01-25 10:46:18 -08001952 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001953 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001954 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001955 }
1956
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001957 // Snap the latency to a value that removes scheduling jitter from the
1958 // composition and present times, which often have >1ms of jitter.
1959 // Reducing jitter is important if an app attempts to extrapolate
1960 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001961 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001962 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001963 nsecs_t bias = stats.vsyncPeriod / 2;
1964 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1965 nsecs_t snappedCompositeToPresentLatency =
1966 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001967
David Sodman99974d22017-11-28 12:04:33 -08001968 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001969 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1970 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001971 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001972}
1973
David Sodman2b406362017-12-15 13:33:47 -08001974void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001975{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001976 ATRACE_CALL();
1977 ALOGV("postComposition");
1978
Brian Anderson3546a3f2016-07-14 11:51:14 -07001979 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001980 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001981 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001982 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001983 }
1984
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001985 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07001986 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001987
David Sodman73beded2017-11-15 11:56:06 -08001988 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001989 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001990 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001991 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07001992 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
1993 ->getRenderSurface()
1994 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001995 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001996 } else {
1997 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1998 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001999
David Sodman73beded2017-11-15 11:56:06 -08002000 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002001 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2002 mPreviousPresentFences[0] = displayDevice
2003 ? getHwComposer().getPresentFence(*displayDevice->getId())
2004 : Fence::NO_FENCE;
2005 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002006 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002007
Ana Krulece588e312018-09-18 12:32:24 -07002008 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002009 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002010
David Sodman2b406362017-12-15 13:33:47 -08002011 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002012 // when we started doing work for this frame, but that should be okay
2013 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002014 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002015 CompositorTiming compositorTiming;
2016 {
David Sodman99974d22017-11-28 12:04:33 -08002017 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2018 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002019 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002020
Robert Carr2047fae2016-11-28 14:09:09 -08002021 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002022 bool frameLatched =
2023 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2024 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002025 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002026 recordBufferingStats(layer->getName().string(),
2027 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002028 }
Robert Carr2047fae2016-11-28 14:09:09 -08002029 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002030
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002031 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002032 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002033 }
2034
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002035 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002036 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2037 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002038 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002039 }
2040 }
2041
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002042 if (mAnimCompositionPending) {
2043 mAnimCompositionPending = false;
2044
Brian Anderson4e606e32017-03-16 15:34:57 -07002045 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002046 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002047 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002048 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002049 // The HWC doesn't support present fences, so use the refresh
2050 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002051 const nsecs_t presentTime =
2052 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002053 mAnimFrameTracker.setActualPresentTime(presentTime);
2054 }
2055 mAnimFrameTracker.advanceFrame();
2056 }
Dan Stozab90cf072015-03-05 11:05:59 -08002057
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002058 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002059 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002060 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002061 }
2062
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002063 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002064
Lloyd Pique32cbe282018-10-19 13:09:22 -07002065 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2066 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002067 return;
2068 }
2069
2070 nsecs_t currentTime = systemTime();
2071 if (mHasPoweredOff) {
2072 mHasPoweredOff = false;
2073 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002074 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002075 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002076 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2077 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002078 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002079 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002080 }
David Sodman4a36e932017-11-07 14:29:47 -08002081 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002082 }
David Sodman4a36e932017-11-07 14:29:47 -08002083 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002084
2085 {
2086 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002087 if (mTexturePool.size() < mTexturePoolSize) {
2088 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002089 const size_t offset = mTexturePool.size();
2090 mTexturePool.resize(mTexturePoolSize);
2091 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2092 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002093 } else if (mTexturePool.size() > mTexturePoolSize) {
2094 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2095 const size_t offset = mTexturePoolSize;
2096 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2097 mTexturePool.resize(mTexturePoolSize);
2098 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002099 }
2100 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002101
Ady Abrahambe0f9482019-04-24 15:41:53 -07002102 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Walle2ffb422018-10-12 11:33:52 -07002103 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002104
Kevin DuBois413287f2019-02-25 08:46:47 -08002105 if (mLumaSampling && mRegionSamplingThread) {
2106 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002107 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002108
2109 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2110 // side-effect of getTotalSize(), so we check that again here
2111 if (ATRACE_ENABLED()) {
2112 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2113 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002114}
2115
Vishnu Nair4351ad52019-02-11 14:13:02 -08002116void SurfaceFlinger::computeLayerBounds() {
2117 for (const auto& pair : mDisplays) {
2118 const auto& displayDevice = pair.second;
2119 const auto display = displayDevice->getCompositionDisplay();
2120 for (const auto& layer : mDrawingState.layersSortedByZ) {
2121 // only consider the layers on the given layer stack
2122 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002123 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002124 }
2125
2126 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2127 }
2128 }
2129}
2130
Mathias Agopiancd60f992012-08-16 16:28:27 -07002131void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002132 ATRACE_CALL();
2133 ALOGV("rebuildLayerStacks");
2134
Mathias Agopiancd60f992012-08-16 16:28:27 -07002135 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002136 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002137 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002138 mVisibleRegionsDirty = false;
2139 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002140
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002141 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002142 const auto& displayDevice = pair.second;
2143 auto display = displayDevice->getCompositionDisplay();
2144 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002145 Region opaqueRegion;
2146 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002147 compositionengine::Output::OutputLayers layersSortedByZ;
2148 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002149 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002150 const ui::Transform& tr = displayState.transform;
2151 const Rect bounds = displayState.bounds;
2152 if (displayState.isEnabled) {
2153 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002154
Jeff Sharkey76488112017-02-27 14:15:18 -07002155 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002156 auto compositionLayer = layer->getCompositionLayer();
2157 if (compositionLayer == nullptr) {
2158 return;
2159 }
2160
Lloyd Pique32cbe282018-10-19 13:09:22 -07002161 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002162 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2163 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2164
Lloyd Pique07e33212018-12-18 16:33:37 -08002165 bool needsOutputLayer = false;
2166
Lloyd Piqueef36b002019-01-23 17:52:04 -08002167 if (display->belongsInOutput(layer->getLayerStack(),
2168 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002169 Region drawRegion(tr.transform(
2170 layer->visibleNonTransparentRegion));
2171 drawRegion.andSelf(bounds);
2172 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002173 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002174 }
Chia-I Wu83806892017-11-16 10:50:20 -08002175 }
2176
Lloyd Pique07e33212018-12-18 16:33:37 -08002177 if (needsOutputLayer) {
2178 layersSortedByZ.emplace_back(
2179 display->getOrCreateOutputLayer(displayId, compositionLayer,
2180 layerFE));
2181 deprecated_layersSortedByZ.add(layer);
2182
2183 auto& outputLayerState = layersSortedByZ.back()->editState();
2184 outputLayerState.visibleRegion =
2185 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2186 } else if (displayId) {
2187 // For layers that are being removed from a HWC display,
2188 // and that have queued frames, add them to a a list of
2189 // released layers so we can properly set a fence.
2190 bool hasExistingOutputLayer =
2191 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2192 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2193 mLayersWithQueuedFrames.cend(),
2194 layer) != mLayersWithQueuedFrames.cend();
2195
2196 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002197 layersNeedingFences.add(layer);
2198 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002199 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002200 });
2201 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002202
2203 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2204
2205 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002206 displayDevice->setLayersNeedingFences(layersNeedingFences);
2207
2208 Region undefinedRegion{bounds};
2209 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2210
2211 display->editState().undefinedRegion = undefinedRegion;
2212 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002213 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002214 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002215}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002216
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002217// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002218// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002219// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002220// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002221// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002222// The returned HDR data space is one of
2223// - Dataspace::UNKNOWN
2224// - Dataspace::BT2020_HLG
2225// - Dataspace::BT2020_PQ
Peiyong Lin03912882019-04-16 15:34:46 -07002226Dataspace SurfaceFlinger::getBestDataspace(const sp<DisplayDevice>& display,
2227 Dataspace* outHdrDataSpace,
2228 bool* outIsHdrClientComposition) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002229 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002230 *outHdrDataSpace = Dataspace::UNKNOWN;
2231
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002232 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002233 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002234 case Dataspace::V0_SCRGB:
2235 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002236 case Dataspace::BT2020:
2237 case Dataspace::BT2020_ITU:
2238 case Dataspace::BT2020_LINEAR:
2239 case Dataspace::DISPLAY_BT2020:
2240 bestDataSpace = Dataspace::DISPLAY_BT2020;
2241 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002242 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002243 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002244 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002245 case Dataspace::BT2020_PQ:
2246 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002247 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002248 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lin03912882019-04-16 15:34:46 -07002249 *outIsHdrClientComposition = layer->getForceClientComposition(display);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002250 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002251 case Dataspace::BT2020_HLG:
2252 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002253 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002254 // When there's mixed PQ content and HLG content, we set the HDR
2255 // data space to be BT2020_PQ and convert HLG to PQ.
2256 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2257 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002258 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002259 break;
2260 default:
2261 break;
2262 }
Romain Guy54f154a2017-10-24 21:40:32 +01002263 }
2264
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002265 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002266}
2267
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002268// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002269void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2270 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002271 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2272 *outMode = ColorMode::NATIVE;
2273 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002274 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002275 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002276 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002277
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002278 Dataspace hdrDataSpace;
Peiyong Lin03912882019-04-16 15:34:46 -07002279 bool isHdrClientComposition = false;
2280 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace, &isHdrClientComposition);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002281
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002282 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2283
Peiyong Lina3ea5592019-02-10 14:45:00 -08002284 switch (mForceColorMode) {
2285 case ColorMode::SRGB:
2286 bestDataSpace = Dataspace::V0_SRGB;
2287 break;
2288 case ColorMode::DISPLAY_P3:
2289 bestDataSpace = Dataspace::DISPLAY_P3;
2290 break;
2291 default:
2292 break;
2293 }
2294
Peiyong Lindfde5112018-06-05 10:58:41 -07002295 // respect hdrDataSpace only when there is no legacy HDR support
Peiyong Lin03912882019-04-16 15:34:46 -07002296 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
2297 !profile->hasLegacyHdrSupport(hdrDataSpace) && !isHdrClientComposition;
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002298 if (isHdr) {
2299 bestDataSpace = hdrDataSpace;
2300 }
2301
Chia-I Wu0d711262018-05-21 15:19:35 -07002302 RenderIntent intent;
2303 switch (mDisplayColorSetting) {
2304 case DisplayColorSetting::MANAGED:
2305 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002306 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002307 break;
2308 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002309 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002310 break;
2311 default: // vendor display color setting
2312 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2313 break;
2314 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002315
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002316 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002317}
2318
Lloyd Pique32cbe282018-10-19 13:09:22 -07002319void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2320 auto display = displayDevice->getCompositionDisplay();
2321 const auto& displayState = display->getState();
2322
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002323 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002324 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2325 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002326
David Sodmanfa9b2af2017-12-24 13:28:59 -08002327 // If nothing has changed (!dirty), don't recompose.
2328 // If something changed, but we don't currently have any visible layers,
2329 // and didn't when we last did a composition, then skip it this time.
2330 // The second rule does two things:
2331 // - When all layers are removed from a display, we'll emit one black
2332 // frame, then nothing more until we get new layers.
2333 // - When a display is created with a private layer stack, we won't
2334 // emit any black frames until a layer is added to the layer stack.
2335 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002336
Dominik Laskowski075d3172018-05-24 15:50:06 -07002337 const char flagPrefix[] = {'-', '+'};
2338 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002339 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2340 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2341 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2342 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002343
Lloyd Pique31cb2942018-10-19 17:23:03 -07002344 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002345
David Sodmanfa9b2af2017-12-24 13:28:59 -08002346 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002347 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002348 }
2349}
2350
Lloyd Pique32cbe282018-10-19 13:09:22 -07002351void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2352 auto display = displayDevice->getCompositionDisplay();
2353 const auto& displayState = display->getState();
2354
2355 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002356 return;
David Sodman2b406362017-12-15 13:33:47 -08002357 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002358
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002359 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002360 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002361 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002362}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002363
Lloyd Pique32cbe282018-10-19 13:09:22 -07002364void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002365 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002366 ALOGV("doComposition");
2367
Lloyd Pique32cbe282018-10-19 13:09:22 -07002368 auto display = displayDevice->getCompositionDisplay();
2369 const auto& displayState = display->getState();
2370
2371 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002372 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002373 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002374
David Sodmanfa9b2af2017-12-24 13:28:59 -08002375 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002376 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002377
Lloyd Pique32cbe282018-10-19 13:09:22 -07002378 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002379 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002380 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002381 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002382}
2383
David Sodmanfa9b2af2017-12-24 13:28:59 -08002384void SurfaceFlinger::postFrame()
2385{
2386 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002387 const auto display = getDefaultDisplayDeviceLocked();
2388 if (display && getHwComposer().isConnected(*display->getId())) {
2389 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002390 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2391 logFrameStats();
2392 }
2393 }
2394}
2395
Lloyd Pique32cbe282018-10-19 13:09:22 -07002396void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002397 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002398 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002399
Lloyd Pique32cbe282018-10-19 13:09:22 -07002400 auto display = displayDevice->getCompositionDisplay();
2401 const auto& displayState = display->getState();
2402 const auto displayId = display->getId();
2403
Lloyd Pique32cbe282018-10-19 13:09:22 -07002404 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002405 if (displayId) {
2406 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002407 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002408 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002409 for (auto& layer : display->getOutputLayersOrderedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002410 sp<Fence> releaseFence = Fence::NO_FENCE;
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002411 bool usedClientComposition = true;
David Sodman15094112018-10-11 09:39:37 -07002412
Chia-I Wu7b549592017-11-15 09:14:57 -08002413 // The layer buffer from the previous frame (if any) is released
2414 // by HWC only when the release fence from this frame (if any) is
2415 // signaled. Always get the release fence from HWC first.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002416 if (layer->getState().hwc) {
2417 const auto& hwcState = *layer->getState().hwc;
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002418 releaseFence =
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002419 getHwComposer().getLayerReleaseFence(*displayId, hwcState.hwcLayer.get());
2420 usedClientComposition =
2421 hwcState.hwcCompositionType == Hwc2::IComposerClient::Composition::CLIENT;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002422 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002423
2424 // If the layer was client composited in the previous frame, we
2425 // need to merge with the previous client target acquire fence.
2426 // Since we do not track that, always merge with the current
2427 // client target acquire fence when it is available, even though
2428 // this is suboptimal.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002429 if (usedClientComposition) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002430 releaseFence =
2431 Fence::merge("LayerRelease", releaseFence,
2432 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002433 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002434
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002435 layer->getLayerFE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002436 }
Chia-I Wu83806892017-11-16 10:50:20 -08002437
2438 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002439 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002440 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002441 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002442 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002443 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002444 for (auto& layer : displayDevice->getLayersNeedingFences()) {
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002445 layer->getCompositionLayer()->getLayerFE()->onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002446 }
2447 }
2448
Dominik Laskowski075d3172018-05-24 15:50:06 -07002449 if (displayId) {
2450 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002451 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002452 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002453}
2454
Mathias Agopian87baae12012-07-31 12:38:26 -07002455void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002456{
Mathias Agopian841cde52012-03-01 15:44:37 -08002457 ATRACE_CALL();
2458
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002459 // here we keep a copy of the drawing state (that is the state that's
2460 // going to be overwritten by handleTransactionLocked()) outside of
2461 // mStateLock so that the side-effects of the State assignment
2462 // don't happen with mStateLock held (which can cause deadlocks).
2463 State drawingState(mDrawingState);
2464
Mathias Agopianca4d3602011-05-19 15:38:14 -07002465 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002466 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002467
Mathias Agopianca4d3602011-05-19 15:38:14 -07002468 // Here we're guaranteed that some transaction flags are set
2469 // so we can call handleTransactionLocked() unconditionally.
2470 // We call getTransactionFlags(), which will also clear the flags,
2471 // with mStateLock held to guarantee that mCurrentState won't change
2472 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002473
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002474 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002475 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002476 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002477
Mathias Agopianca4d3602011-05-19 15:38:14 -07002478 mDebugInTransaction = 0;
2479 invalidateHwcGeometry();
2480 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002481}
2482
Lloyd Piqueba04e622017-12-14 17:11:26 -08002483void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2484 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002485 const std::optional<DisplayIdentificationInfo> info =
2486 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002487
Dominik Laskowski075d3172018-05-24 15:50:06 -07002488 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002489 continue;
2490 }
2491
Lloyd Piqueba04e622017-12-14 17:11:26 -08002492 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002493 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002494 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002495 mPhysicalDisplayTokens[info->id] = new BBinder();
2496 DisplayDeviceState state;
2497 state.displayId = info->id;
2498 state.isSecure = true; // All physical displays are currently considered secure.
2499 state.displayName = info->name;
2500 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2501 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002502 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002503 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002504 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002505
Dominik Laskowski075d3172018-05-24 15:50:06 -07002506 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2507 if (index >= 0) {
2508 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2509 mInterceptor->saveDisplayDeletion(state.sequenceId);
2510 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002511 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002512 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002513 }
2514
2515 processDisplayChangesLocked();
2516 }
2517
2518 mPendingHotplugEvents.clear();
2519}
2520
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002521void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002522 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2523 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002524}
2525
Lloyd Pique99d3da52018-01-22 17:48:03 -08002526sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002527 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002528 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002529 const sp<IGraphicBufferProducer>& producer) {
2530 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002531 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002532 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002533 creationArgs.isSecure = state.isSecure;
2534 creationArgs.displaySurface = dispSurface;
2535 creationArgs.hasWideColorGamut = false;
2536 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002537
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002538 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002539 creationArgs.isPrimary = isInternalDisplay;
2540
2541 if (useColorManagement && displayId) {
2542 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002543 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002544 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002545 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002546 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002547
Dominik Laskowski7e045462018-05-30 13:02:02 -07002548 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002549 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002550 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002551 }
tangrobin6753a022018-08-10 10:58:54 +08002552 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002553
Dominik Laskowski075d3172018-05-24 15:50:06 -07002554 if (displayId) {
2555 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002556 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002557 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002558 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002559
Lloyd Pique90c115d2018-09-18 21:39:42 -07002560 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002561 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002562 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002563
Lloyd Pique99d3da52018-01-22 17:48:03 -08002564 // Make sure that composition can never be stalled by a virtual display
2565 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002566 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002567 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002568 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2569 }
2570
Dominik Laskowski075d3172018-05-24 15:50:06 -07002571 creationArgs.displayInstallOrientation =
2572 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002573
Lloyd Pique99d3da52018-01-22 17:48:03 -08002574 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002575 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002576
Lloyd Pique90c115d2018-09-18 21:39:42 -07002577 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002578
2579 if (maxFrameBufferAcquiredBuffers >= 3) {
2580 nativeWindowSurface->preallocateBuffers();
2581 }
2582
2583 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002584 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002585 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002586 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002587 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002588 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002589 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2590 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002591 if (!state.isVirtual()) {
2592 LOG_ALWAYS_FATAL_IF(!displayId);
2593 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002594 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002595
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002596 display->setLayerStack(state.layerStack);
2597 display->setProjection(state.orientation, state.viewport, state.frame);
2598 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002599
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002600 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002601}
2602
Lloyd Pique347200f2017-12-14 17:00:15 -08002603void SurfaceFlinger::processDisplayChangesLocked() {
2604 // here we take advantage of Vector's copy-on-write semantics to
2605 // improve performance by skipping the transaction entirely when
2606 // know that the lists are identical
2607 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2608 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2609 if (!curr.isIdenticalTo(draw)) {
2610 mVisibleRegionsDirty = true;
2611 const size_t cc = curr.size();
2612 size_t dc = draw.size();
2613
2614 // find the displays that were removed
2615 // (ie: in drawing state but not in current state)
2616 // also handle displays that changed
2617 // (ie: displays that are in both lists)
2618 for (size_t i = 0; i < dc;) {
2619 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2620 if (j < 0) {
2621 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002622 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002623 // Save display ID before disconnecting.
2624 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002625 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002626
2627 if (!display->isVirtual()) {
2628 LOG_ALWAYS_FATAL_IF(!displayId);
2629 dispatchDisplayHotplugEvent(displayId->value, false);
2630 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002631 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002632
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002633 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002634 } else {
2635 // this display is in both lists. see if something changed.
2636 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002637 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002638 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2639 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2640 if (state_binder != draw_binder) {
2641 // changing the surface is like destroying and
2642 // recreating the DisplayDevice, so we just remove it
2643 // from the drawing state, so that it get re-added
2644 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002645 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002646 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002647 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002648 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002649 mDrawingState.displays.removeItemsAt(i);
2650 dc--;
2651 // at this point we must loop to the next item
2652 continue;
2653 }
2654
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002655 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002656 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002657 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002658 }
2659 if ((state.orientation != draw[i].orientation) ||
2660 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002661 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002662 }
2663 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002664 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002665 }
2666 }
2667 }
2668 ++i;
2669 }
2670
2671 // find displays that were added
2672 // (ie: in current state but not in drawing state)
2673 for (size_t i = 0; i < cc; i++) {
2674 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2675 const DisplayDeviceState& state(curr[i]);
2676
Lloyd Pique542307f2018-10-19 13:24:08 -07002677 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002678 sp<IGraphicBufferProducer> producer;
2679 sp<IGraphicBufferProducer> bqProducer;
2680 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002681 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002682
Dominik Laskowski075d3172018-05-24 15:50:06 -07002683 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002684 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002685 // Virtual displays without a surface are dormant:
2686 // they have external state (layer stack, projection,
2687 // etc.) but no internal state (i.e. a DisplayDevice).
2688 if (state.surface != nullptr) {
2689 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002690 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002691 int width = 0;
2692 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2693 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2694 int height = 0;
2695 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2696 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2697 int intFormat = 0;
2698 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2699 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002700 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002701
Dominik Laskowski075d3172018-05-24 15:50:06 -07002702 displayId =
2703 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002704 }
2705
2706 // TODO: Plumb requested format back up to consumer
2707
2708 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002709 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002710 bqProducer, bqConsumer,
2711 state.displayName);
2712
2713 dispSurface = vds;
2714 producer = vds;
2715 }
2716 } else {
2717 ALOGE_IF(state.surface != nullptr,
2718 "adding a supported display, but rendering "
2719 "surface is provided (%p), ignoring it",
2720 state.surface.get());
2721
Dominik Laskowski075d3172018-05-24 15:50:06 -07002722 displayId = state.displayId;
2723 LOG_ALWAYS_FATAL_IF(!displayId);
2724 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002725 producer = bqProducer;
2726 }
2727
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002728 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002729 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002730 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002731 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002732 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002733 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002734 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002735 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002736 }
2737 }
2738 }
2739 }
2740 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002741
2742 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002743}
2744
Mathias Agopian87baae12012-07-31 12:38:26 -07002745void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002746{
Dan Stoza7dde5992015-05-22 09:51:44 -07002747 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002748 mCurrentState.traverseInZOrder([](Layer* layer) {
2749 layer->notifyAvailableFrames();
2750 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002751
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002752 /*
2753 * Traversal of the children
2754 * (perform the transaction for each of them if needed)
2755 */
2756
Marissa Wall06255332019-03-27 13:48:27 -07002757 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002758 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002759 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002760 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002761
2762 const uint32_t flags = layer->doTransaction(0);
2763 if (flags & Layer::eVisibleRegion)
2764 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002765
2766 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002767 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002768 }
Robert Carr2047fae2016-11-28 14:09:09 -08002769 });
Marissa Wall06255332019-03-27 13:48:27 -07002770 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002771 }
2772
2773 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002774 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002775 */
2776
Mathias Agopiane57f2922012-08-09 16:29:12 -07002777 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002778 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002779 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002780 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002781
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002782 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002783 // The transform hint might have changed for some layers
2784 // (either because a display has changed, or because a layer
2785 // as changed).
2786 //
2787 // Walk through all the layers in currentLayers,
2788 // and update their transform hint.
2789 //
2790 // If a layer is visible only on a single display, then that
2791 // display is used to calculate the hint, otherwise we use the
2792 // default display.
2793 //
2794 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2795 // the hint is set before we acquire a buffer from the surface texture.
2796 //
2797 // NOTE: layer transactions have taken place already, so we use their
2798 // drawing state. However, SurfaceFlinger's own transaction has not
2799 // happened yet, so we must use the current state layer list
2800 // (soon to become the drawing state list).
2801 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002802 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002803 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002804 bool first = true;
2805 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002806 // NOTE: we rely on the fact that layers are sorted by
2807 // layerStack first (so we don't have to traverse the list
2808 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002809 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002810 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002811 currentlayerStack = layerStack;
2812 // figure out if this layerstack is mirrored
2813 // (more than one display) if so, pick the default display,
2814 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002815 hintDisplay = nullptr;
2816 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002817 if (display->getCompositionDisplay()
2818 ->belongsInOutput(layer->getLayerStack(),
2819 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002820 if (hintDisplay) {
2821 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002822 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002823 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002824 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002825 }
2826 }
2827 }
2828 }
Chet Haase91d25932013-04-11 15:24:55 -07002829
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002830 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002831 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2832 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002833
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002834 // could be null when this layer is using a layerStack
2835 // that is not visible on any display. Also can occur at
2836 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002837 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002838 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002839
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002840 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002841 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002842 if (hintDisplay) {
2843 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002844 }
Robert Carr2047fae2016-11-28 14:09:09 -08002845
2846 first = false;
2847 });
Mathias Agopian84300952012-11-21 16:02:13 -08002848 }
2849
2850
Mathias Agopian3559b072012-08-15 13:46:03 -07002851 /*
2852 * Perform our own transaction if needed
2853 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002854
2855 if (mLayersAdded) {
2856 mLayersAdded = false;
2857 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002858 mVisibleRegionsDirty = true;
2859 }
2860
2861 // some layers might have been removed, so
2862 // we need to update the regions they're exposing.
2863 if (mLayersRemoved) {
2864 mLayersRemoved = false;
2865 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002866 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002867 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002868 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002869 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002870 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002871 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002872 }
Robert Carr2047fae2016-11-28 14:09:09 -08002873 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002874 }
2875
Vishnu Nairec0ab382019-02-13 15:32:56 -08002876 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002877 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002878}
2879
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002880void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002881 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002882 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002883 return;
2884 }
2885
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002886 if (mVisibleRegionsDirty || mInputInfoChanged) {
2887 mInputInfoChanged = false;
2888 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002889 } else if (mInputWindowCommands.syncInputWindows) {
2890 // If the caller requested to sync input windows, but there are no
2891 // changes to input windows, notify immediately.
2892 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002893 }
2894
2895 executeInputWindowCommands();
2896}
2897
2898void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002899 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002900
2901 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2902 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002903 // When calculating the screen bounds we ignore the transparent region since it may
2904 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002905 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002906 }
2907 });
chaviw291d88a2019-02-14 10:33:58 -08002908
2909 mInputFlinger->setInputWindows(inputHandles,
2910 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2911 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002912}
2913
Vishnu Nairec0ab382019-02-13 15:32:56 -08002914void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002915 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002916 mPendingInputWindowCommands.clear();
2917}
2918
chaviwfbe5d9c2018-12-26 12:23:37 -08002919void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08002920 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2921 if (transferTouchFocusCommand.fromToken != nullptr &&
2922 transferTouchFocusCommand.toToken != nullptr &&
2923 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2924 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2925 transferTouchFocusCommand.toToken);
2926 }
2927 }
2928
2929 mInputWindowCommands.clear();
2930}
2931
Riley Andrews03414a12014-07-01 14:22:59 -07002932void SurfaceFlinger::updateCursorAsync()
2933{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002934 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002935 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002936 continue;
2937 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002938
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002939 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2940 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002941 }
2942 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002943}
2944
chaviw61626f22018-11-15 16:26:27 -08002945void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2946 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08002947 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08002948 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08002949 }
2950 layer->releasePendingBuffer(systemTime());
2951}
2952
Mathias Agopian4fec8732012-06-29 14:12:52 -07002953void SurfaceFlinger::commitTransaction()
2954{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002955 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002956 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002957 for (const auto& l : mLayersPendingRemoval) {
2958 recordBufferingStats(l->getName().string(),
2959 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002960
Lloyd Pique07e33212018-12-18 16:33:37 -08002961 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07002962 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08002963 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07002964 }
chaviw74d90ad2019-04-26 14:45:26 -07002965
2966 // If the layer has been removed and has no parent, then it will not be reachable
2967 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2968 // ensure we can copy its current to drawing state.
2969 if (!l->getParent()) {
2970 mOffscreenLayers.emplace(l.get());
2971 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002972 }
2973 mLayersPendingRemoval.clear();
2974 }
2975
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002976 // If this transaction is part of a window animation then the next frame
2977 // we composite should be considered an animation as well.
2978 mAnimCompositionPending = mAnimTransactionPending;
2979
Nataniel Borges2b796da2019-02-15 13:32:18 -08002980 withTracingLock([&]() {
2981 mDrawingState = mCurrentState;
2982 // clear the "changed" flags in current state
2983 mCurrentState.colorMatrixChanged = false;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002984
chaviw74d90ad2019-04-26 14:45:26 -07002985 mDrawingState.traverseInZOrder([&](Layer* layer) {
2986 layer->commitChildList();
2987
2988 // If the layer can be reached when traversing mDrawingState, then the layer is no
2989 // longer offscreen. Remove the layer from the offscreenLayer set.
2990 if (mOffscreenLayers.count(layer)) {
2991 mOffscreenLayers.erase(layer);
2992 }
2993 });
2994
2995 commitOffscreenLayers();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002996 });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002997
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002998 mTransactionPending = false;
2999 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003000 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003001}
3002
Nataniel Borges2b796da2019-02-15 13:32:18 -08003003void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
3004 if (mTracingEnabledChanged) {
3005 mTracingEnabled = mTracing.isEnabled();
3006 mTracingEnabledChanged = false;
3007 }
3008
3009 // Synchronize with Tracing thread
3010 std::unique_lock<std::mutex> lock;
3011 if (mTracingEnabled) {
3012 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
3013 }
3014
3015 lockedOperation();
3016
3017 // Synchronize with Tracing thread
3018 if (mTracingEnabled) {
3019 lock.unlock();
3020 }
3021}
3022
chaviw74d90ad2019-04-26 14:45:26 -07003023void SurfaceFlinger::commitOffscreenLayers() {
3024 for (Layer* offscreenLayer : mOffscreenLayers) {
3025 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
3026 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3027 if (!trFlags) return;
3028
3029 layer->doTransaction(0);
3030 layer->commitChildList();
3031 });
3032 }
3033}
3034
Lloyd Pique32cbe282018-10-19 13:09:22 -07003035void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003036 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003037 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003038 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003039
Lloyd Pique32cbe282018-10-19 13:09:22 -07003040 auto display = displayDevice->getCompositionDisplay();
3041
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003042 Region aboveOpaqueLayers;
3043 Region aboveCoveredLayers;
3044 Region dirty;
3045
Mathias Agopian87baae12012-07-31 12:38:26 -07003046 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003047
Robert Carr2047fae2016-11-28 14:09:09 -08003048 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003049 // start with the whole surface at its current location
3050 const Layer::State& s(layer->getDrawingState());
3051
Jesse Hall01e29052013-02-19 16:13:35 -08003052 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003053 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003054 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003055 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003056
Mathias Agopianab028732010-03-16 16:41:46 -07003057 /*
3058 * opaqueRegion: area of a surface that is fully opaque.
3059 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003060 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003061
3062 /*
3063 * visibleRegion: area of a surface that is visible on screen
3064 * and not fully transparent. This is essentially the layer's
3065 * footprint minus the opaque regions above it.
3066 * Areas covered by a translucent surface are considered visible.
3067 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003068 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003069
3070 /*
3071 * coveredRegion: area of a surface that is covered by all
3072 * visible regions above it (which includes the translucent areas).
3073 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003074 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003075
Jesse Halla8026d22012-09-25 13:25:04 -07003076 /*
3077 * transparentRegion: area of a surface that is hinted to be completely
3078 * transparent. This is only used to tell when the layer has no visible
3079 * non-transparent regions and can be removed from the layer list. It
3080 * does not affect the visibleRegion of this layer or any layers
3081 * beneath it. The hint may not be correct if apps don't respect the
3082 * SurfaceView restrictions (which, sadly, some don't).
3083 */
3084 Region transparentRegion;
3085
Mathias Agopianab028732010-03-16 16:41:46 -07003086
3087 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003088 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003089 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003090 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003091
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003092 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003093 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003094 if (!visibleRegion.isEmpty()) {
3095 // Remove the transparent area from the visible region
3096 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003097 if (tr.preserveRects()) {
3098 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003099 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003100 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003101 // transformation too complex, can't do the
3102 // transparent region optimization.
3103 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003104 }
Mathias Agopianab028732010-03-16 16:41:46 -07003105 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003106
Mathias Agopianab028732010-03-16 16:41:46 -07003107 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003108 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003109 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003110 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003111 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003112 // the opaque region is the layer's footprint
3113 opaqueRegion = visibleRegion;
3114 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003115 }
3116 }
3117
Robert Carre5f4f692018-01-12 13:12:28 -08003118 if (visibleRegion.isEmpty()) {
3119 layer->clearVisibilityRegions();
3120 return;
3121 }
3122
Mathias Agopianab028732010-03-16 16:41:46 -07003123 // Clip the covered region to the visible region
3124 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3125
3126 // Update aboveCoveredLayers for next (lower) layer
3127 aboveCoveredLayers.orSelf(visibleRegion);
3128
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003129 // subtract the opaque region covered by the layers above us
3130 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003131
3132 // compute this layer's dirty region
3133 if (layer->contentDirty) {
3134 // we need to invalidate the whole region
3135 dirty = visibleRegion;
3136 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003137 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003138 layer->contentDirty = false;
3139 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003140 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003141 * the exposed region consists of two components:
3142 * 1) what's VISIBLE now and was COVERED before
3143 * 2) what's EXPOSED now less what was EXPOSED before
3144 *
3145 * note that (1) is conservative, we start with the whole
3146 * visible region but only keep what used to be covered by
3147 * something -- which mean it may have been exposed.
3148 *
3149 * (2) handles areas that were not covered by anything but got
3150 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003151 */
Mathias Agopianab028732010-03-16 16:41:46 -07003152 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003153 const Region oldVisibleRegion = layer->visibleRegion;
3154 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003155 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3156 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003157 }
3158 dirty.subtractSelf(aboveOpaqueLayers);
3159
3160 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003161 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003162
Mathias Agopianab028732010-03-16 16:41:46 -07003163 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003164 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003165
Jesse Halla8026d22012-09-25 13:25:04 -07003166 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003167 layer->setVisibleRegion(visibleRegion);
3168 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003169 layer->setVisibleNonTransparentRegion(
3170 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003171 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003172
Mathias Agopian87baae12012-07-31 12:38:26 -07003173 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003174}
3175
Chia-I Wuab0c3192017-08-01 11:29:00 -07003176void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003177 for (const auto& [token, displayDevice] : mDisplays) {
3178 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003179 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003180 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003181 }
3182 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003183}
3184
Dan Stoza6b9454d2014-11-07 16:00:59 -08003185bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003186{
Ady Abraham09bd3922019-04-08 10:44:56 -07003187 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003188 ALOGV("handlePageFlip");
3189
Brian Andersond6927fb2016-07-23 23:37:30 -07003190 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003191
Mathias Agopian4fec8732012-06-29 14:12:52 -07003192 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003193 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003194 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003195
3196 // Store the set of layers that need updates. This set must not change as
3197 // buffers are being latched, as this could result in a deadlock.
3198 // Example: Two producers share the same command stream and:
3199 // 1.) Layer 0 is latched
3200 // 2.) Layer 0 gets a new frame
3201 // 2.) Layer 1 gets a new frame
3202 // 3.) Layer 1 is latched.
3203 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3204 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003205 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003206 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003207 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003208 nsecs_t expectedPresentTime;
Ana Krulecc2870422019-01-29 19:00:58 -08003209 expectedPresentTime = mScheduler->expectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003210 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003211 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003212 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003213 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003214 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003215 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003216 } else {
3217 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003218 }
Robert Carr2047fae2016-11-28 14:09:09 -08003219 });
3220
Lloyd Piquef2c79392018-12-20 16:23:33 -08003221 if (!mLayersWithQueuedFrames.empty()) {
3222 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3223 // writes to Layer current state. See also b/119481871
3224 Mutex::Autolock lock(mStateLock);
3225
3226 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003227 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003228 mLayersPendingRefresh.push_back(layer);
3229 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003230 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003231 if (layer->isBufferLatched()) {
3232 newDataLatched = true;
3233 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003234 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003235 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003236
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003237 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003238
3239 // If we will need to wake up at some time in the future to deal with a
3240 // queued frame that shouldn't be displayed during this vsync period, wake
3241 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003242 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003243 signalLayerUpdate();
3244 }
3245
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003246 // enter boot animation on first buffer latch
3247 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3248 ALOGI("Enter boot animation");
3249 mBootStage = BootStage::BOOTANIMATION;
3250 }
3251
Dan Stoza6b9454d2014-11-07 16:00:59 -08003252 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003253 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003254}
3255
Mathias Agopianad456f92011-01-13 17:53:01 -08003256void SurfaceFlinger::invalidateHwcGeometry()
3257{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003258 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003259}
3260
Lloyd Pique32cbe282018-10-19 13:09:22 -07003261void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003262 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003263 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003264 // We only need to actually compose the display if:
3265 // 1) It is being handled by hardware composer, which may need this to
3266 // keep its virtual display state machine in sync, or
3267 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003268 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003269 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003270 return;
3271 }
3272
Dan Stoza9e56aa02015-11-02 13:00:03 -08003273 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003274 base::unique_fd readyFence;
3275 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003276
3277 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003278 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003279}
3280
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003281bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3282 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003283 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003284 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003285
Lloyd Pique32cbe282018-10-19 13:09:22 -07003286 auto display = displayDevice->getCompositionDisplay();
3287 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003288 const auto displayId = display->getId();
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003289 auto& renderEngine = getRenderEngine();
Peiyong Lin548d4fa2019-04-02 18:14:44 -07003290 const bool supportProtectedContent = renderEngine.supportsProtectedContent();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003291
3292 const Region bounds(displayState.bounds);
3293 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003294 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003295 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003296
Chia-I Wu8e50e692018-05-04 10:12:37 -07003297 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003298
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003299 renderengine::DisplaySettings clientCompositionDisplay;
3300 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3301 sp<GraphicBuffer> buf;
Alec Mouri6338c9d2019-02-07 16:57:51 -08003302 base::unique_fd fd;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003303
Dan Stoza9e56aa02015-11-02 13:00:03 -08003304 if (hasClientComposition) {
3305 ALOGV("hasClientComposition");
3306
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003307 if (displayDevice->isPrimary() && supportProtectedContent) {
3308 bool needsProtected = false;
3309 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3310 // If the layer is a protected layer, mark protected context is needed.
3311 if (layer->isProtected()) {
3312 needsProtected = true;
3313 break;
3314 }
3315 }
Peiyong Lin52010312019-05-02 14:22:16 -07003316 if (needsProtected != renderEngine.isProtected()) {
3317 renderEngine.useProtectedContext(needsProtected);
3318 }
3319 if (needsProtected != display->getRenderSurface()->isProtected() &&
3320 needsProtected == renderEngine.isProtected()) {
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003321 display->getRenderSurface()->setProtected(needsProtected);
3322 }
3323 }
3324
Alec Mouri6338c9d2019-02-07 16:57:51 -08003325 buf = display->getRenderSurface()->dequeueBuffer(&fd);
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003326
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003327 if (buf == nullptr) {
3328 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3329 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003330 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003331 return false;
3332 }
3333
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003334 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3335 clientCompositionDisplay.clip = displayState.scissor;
3336 const ui::Transform& displayTransform = displayState.transform;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07003337 clientCompositionDisplay.globalTransform = displayTransform.asMatrix4();
Peiyong Linb1925962019-04-01 16:37:10 -07003338 clientCompositionDisplay.orientation = displayState.orientation;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003339
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003340 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003341 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003342 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003343 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003344 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003345 clientCompositionDisplay.outputDataspace = outputDataspace;
3346 clientCompositionDisplay.maxLuminance =
3347 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003348
Lloyd Pique441d5042018-10-18 16:49:51 -07003349 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003350 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003351 getHwComposer()
3352 .hasDisplayCapability(displayId,
3353 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003354
Peiyong Lind3788632018-09-18 16:01:31 -07003355 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003356 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3357 if (applyColorMatrix) {
Alec Mouric7e8ce82019-04-02 12:28:05 -07003358 clientCompositionDisplay.colorTransform = displayState.colorTransformMat;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003359 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003360 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003361
Mathias Agopian85d751c2012-08-29 16:59:24 -07003362 /*
3363 * and then, render the layers targeted at the framebuffer
3364 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003365
Dan Stoza9e56aa02015-11-02 13:00:03 -08003366 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003367 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003368 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003369 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003370 const Region viewportRegion(displayState.viewport);
3371 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003372 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003373 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003374 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003375 switch (layer->getCompositionType(displayDevice)) {
3376 case Hwc2::IComposerClient::Composition::CURSOR:
3377 case Hwc2::IComposerClient::Composition::DEVICE:
3378 case Hwc2::IComposerClient::Composition::SIDEBAND:
3379 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003380 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003381 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003382 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003383 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003384 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003385 // never clear the very first layer since we're
3386 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003387 renderengine::LayerSettings layerSettings;
3388 Region dummyRegion;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003389 bool prepared =
3390 layer->prepareClientLayer(renderArea, clip, dummyRegion,
3391 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003392
3393 if (prepared) {
3394 layerSettings.source.buffer.buffer = nullptr;
3395 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3396 layerSettings.alpha = half(0.0);
3397 layerSettings.disableBlending = true;
3398 clientCompositionLayers.push_back(layerSettings);
3399 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003400 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003401 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003402 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003403 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003404 renderengine::LayerSettings layerSettings;
3405 bool prepared =
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003406 layer->prepareClientLayer(renderArea, clip, clearRegion,
3407 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003408 if (prepared) {
3409 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003410 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003411 break;
3412 }
3413 default:
3414 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003415 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003416 } else {
3417 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003418 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003419 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003420 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003421
Alec Mouri820c7402019-01-23 13:02:39 -08003422 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003423 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003424 clientCompositionDisplay.clearRegion = clearRegion;
Peiyong Lin74ca2f42019-01-14 19:36:57 -08003425
3426 // We boost GPU frequency here because there will be color spaces conversion
3427 // and it's expensive. We boost the GPU frequency so that GPU composition can
3428 // finish in time. We must reset GPU frequency afterwards, because high frequency
3429 // consumes extra battery.
3430 const bool expensiveRenderingExpected =
3431 clientCompositionDisplay.outputDataspace == Dataspace::DISPLAY_P3;
3432 if (expensiveRenderingExpected && displayId) {
3433 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, true);
3434 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003435 if (!debugRegion.isEmpty()) {
3436 Region::const_iterator it = debugRegion.begin();
3437 Region::const_iterator end = debugRegion.end();
3438 while (it != end) {
3439 const Rect& rect = *it++;
3440 renderengine::LayerSettings layerSettings;
3441 layerSettings.source.buffer.buffer = nullptr;
3442 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3443 layerSettings.geometry.boundaries = rect.toFloatRect();
3444 layerSettings.alpha = half(1.0);
3445 clientCompositionLayers.push_back(layerSettings);
3446 }
3447 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003448 renderEngine.drawLayers(clientCompositionDisplay, clientCompositionLayers,
Alec Mourife0d72b2019-03-21 14:05:56 -07003449 buf->getNativeBuffer(), /*useFramebufferCache=*/true, std::move(fd),
3450 readyFence);
Peiyong Lin8ec87f82019-04-05 11:30:51 -07003451 } else if (displayId) {
3452 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, false);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003453 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003454 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003455}
3456
Chia-I Wu28e3a252018-09-07 12:05:02 -07003457void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003458 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003459 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003460}
3461
Robert Carrc0df3122019-04-11 13:18:21 -07003462status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3463 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3464 const sp<IBinder>& parentHandle,
3465 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003466 // add this layer to the current state list
3467 {
3468 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003469 sp<Layer> parent;
3470 if (parentHandle != nullptr) {
3471 parent = fromHandle(parentHandle);
3472 if (parent == nullptr) {
3473 return NAME_NOT_FOUND;
3474 }
3475 } else {
3476 parent = parentLayer;
3477 }
3478
Robert Carr1f0a16a2016-10-24 16:27:39 -07003479 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003480 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3481 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003482 return NO_MEMORY;
3483 }
Robert Carrc0df3122019-04-11 13:18:21 -07003484
3485 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3486
Robert Carrb89ea9d2018-12-10 13:01:14 -08003487 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003488 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003489 } else if (parent == nullptr) {
3490 lbc->onRemovedFromCurrentState();
3491 } else if (parent->isRemovedFromCurrentState()) {
3492 parent->addChild(lbc);
3493 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003494 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003495 parent->addChild(lbc);
3496 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003497
Yiwei Zhang243b3782018-05-15 17:40:04 -07003498 if (gbc != nullptr) {
3499 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3500 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3501 mMaxGraphicBufferProducerListSize,
3502 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3503 mGraphicBufferProducerList.size(),
3504 mMaxGraphicBufferProducerListSize, mNumLayers);
3505 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003506 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003507 }
3508
Mathias Agopian96f08192010-06-02 23:28:45 -07003509 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003510 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003511
Dan Stoza7d89d062015-04-30 13:29:25 -07003512 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003513}
3514
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003515uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003516 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003517}
3518
Mathias Agopian3f844832013-08-07 21:24:32 -07003519uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003520 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003521}
3522
Mathias Agopian3f844832013-08-07 21:24:32 -07003523uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003524 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003525}
3526
3527uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003528 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003529 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003530 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003531 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003532 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003533 }
3534 return old;
3535}
3536
Marissa Wall713b63f2018-10-17 15:42:43 -07003537bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003538 // to prevent onHandleDestroyed from being called while the lock is held,
3539 // we must keep a copy of the transactions (specifically the composer
3540 // states) around outside the scope of the lock
3541 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003542 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003543 {
3544 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003545
Valerie Haufce31b82019-04-30 16:41:14 -07003546 auto it = mTransactionQueues.begin();
3547 while (it != mTransactionQueues.end()) {
3548 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003549
Valerie Haufce31b82019-04-30 16:41:14 -07003550 while (!transactionQueue.empty()) {
3551 const auto& transaction = transactionQueue.front();
3552 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
3553 transaction.states)) {
3554 setTransactionFlags(eTransactionFlushNeeded);
3555 break;
3556 }
3557 transactions.push_back(transaction);
3558 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3559 mPendingInputWindowCommands, transaction.desiredPresentTime,
3560 transaction.buffer, transaction.callback,
3561 transaction.postTime, transaction.privileged,
3562 /*isMainThread*/ true);
3563 transactionQueue.pop();
3564 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003565 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003566
Valerie Haufce31b82019-04-30 16:41:14 -07003567 if (transactionQueue.empty()) {
3568 it = mTransactionQueues.erase(it);
3569 mTransactionCV.broadcast();
3570 } else {
3571 std::next(it, 1);
3572 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003573 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003574 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003575 return flushedATransaction;
3576}
3577
3578bool SurfaceFlinger::transactionFlushNeeded() {
3579 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003580}
3581
chaviwca27f252018-02-06 16:46:39 -08003582bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3583 for (const ComposerState& state : states) {
3584 // Here we need to check that the interface we're given is indeed
3585 // one of our own. A malicious client could give us a nullptr
3586 // IInterface, or one of its own or even one of our own but a
3587 // different type. All these situations would cause us to crash.
3588 if (state.client == nullptr) {
3589 return true;
3590 }
3591
3592 sp<IBinder> binder = IInterface::asBinder(state.client);
3593 if (binder == nullptr) {
3594 return true;
3595 }
3596
3597 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3598 return true;
3599 }
3600 }
3601 return false;
3602}
3603
Marissa Wall17b4e452018-12-26 16:32:34 -08003604bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3605 const Vector<ComposerState>& states) {
Ana Krulecc2870422019-01-29 19:00:58 -08003606 nsecs_t expectedPresentTime = mScheduler->expectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003607 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3608 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3609 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3610 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3611 return false;
3612 }
3613
Marissa Wall713b63f2018-10-17 15:42:43 -07003614 for (const ComposerState& state : states) {
3615 const layer_state_t& s = state.state;
3616 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3617 continue;
3618 }
3619 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003620 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003621 }
3622 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003623 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003624}
3625
3626void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3627 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003628 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003629 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003630 int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003631 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003632 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003633 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003634
Valerie Haubc6ddb12019-03-08 11:10:15 -08003635 const int64_t postTime = systemTime();
3636
Robert Carr14167e02019-02-13 13:50:55 -08003637 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3638
Mathias Agopian698c0872011-06-28 19:09:31 -07003639 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003640
chaviwca27f252018-02-06 16:46:39 -08003641 if (containsAnyInvalidClientState(states)) {
3642 return;
3643 }
3644
Marissa Wall713b63f2018-10-17 15:42:43 -07003645 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003646 auto itr = mTransactionQueues.find(applyToken);
3647 // if this is an animation frame, wait until prior animation frame has
3648 // been applied by SF
3649 if (flags & eAnimation) {
3650 while (itr != mTransactionQueues.end()) {
3651 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3652 if (CC_UNLIKELY(err != NO_ERROR)) {
3653 ALOGW_IF(err == TIMED_OUT,
3654 "setTransactionState timed out "
3655 "waiting for animation frame to apply");
3656 break;
3657 }
3658 itr = mTransactionQueues.find(applyToken);
3659 }
3660 }
3661 if (itr != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003662 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003663 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003664 uncacheBuffer, listenerCallbacks, postTime,
3665 privileged);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003666 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003667 return;
3668 }
3669
Valerie Haubc6ddb12019-03-08 11:10:15 -08003670 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003671 uncacheBuffer, listenerCallbacks, postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003672}
3673
3674void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003675 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003676 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003677 const int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003678 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003679 const std::vector<ListenerCallbacks>& listenerCallbacks,
Marissa Wall78b72202019-03-15 14:58:34 -07003680 const int64_t postTime, bool privileged,
3681 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003682 uint32_t transactionFlags = 0;
3683
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003684 if (flags & eAnimation) {
3685 // For window updates that are part of an animation we must wait for
3686 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003687 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003688 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003689 if (CC_UNLIKELY(err != NO_ERROR)) {
3690 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003691 // caller after a few seconds.
3692 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3693 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003694 mAnimTransactionPending = false;
3695 break;
3696 }
3697 }
3698 }
3699
chaviwca27f252018-02-06 16:46:39 -08003700 for (const DisplayState& display : displays) {
3701 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003702 }
3703
Marissa Walld600d572019-03-26 15:38:50 -07003704 // In case the client has sent a Transaction that should receive callbacks but without any
3705 // SurfaceControls that should be included in the callback, send the listener and callbackIds
3706 // to the callback thread so it can send an empty callback
3707 if (!listenerCallbacks.empty()) {
3708 mTransactionCompletedThread.run();
3709 }
3710 for (const auto& [listener, callbackIds] : listenerCallbacks) {
3711 mTransactionCompletedThread.addCallback(listener, callbackIds);
3712 }
3713
Marissa Walle2ffb422018-10-12 11:33:52 -07003714 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003715 for (const ComposerState& state : states) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07003716 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, listenerCallbacks,
3717 postTime, privileged);
3718 }
3719
Marissa Walle2ffb422018-10-12 11:33:52 -07003720 // If the state doesn't require a traversal and there are callbacks, send them now
Marissa Wallb0022cc2019-04-16 14:19:55 -07003721 if (!(clientStateFlags & eTraversalNeeded) && !listenerCallbacks.empty()) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003722 mTransactionCompletedThread.sendCallbacks();
3723 }
3724 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003725
chaviw273171b2018-12-26 11:46:30 -08003726 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3727
Marissa Wall947d34e2019-03-29 14:03:53 -07003728 if (uncacheBuffer.isValid()) {
3729 ClientCache::getInstance().erase(uncacheBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003730 }
3731
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003732 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3733 // anyway. This can be used as a flush mechanism for previous async transactions.
3734 // Empty animation transaction can be used to simulate back-pressure, so also force a
3735 // transaction for empty animation transactions.
3736 if (transactionFlags == 0 &&
3737 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003738 transactionFlags = eTransactionNeeded;
3739 }
3740
Marissa Wall06255332019-03-27 13:48:27 -07003741 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3742 // so we don't have to wake up again next frame to preform an uneeded traversal.
3743 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3744 transactionFlags = transactionFlags & (~eTraversalNeeded);
3745 mTraversalNeededMainThread = true;
3746 }
3747
Mathias Agopian386aa982011-11-07 21:58:03 -08003748 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003749 if (mInterceptor->isEnabled()) {
3750 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003751 }
Irvel468051e2016-06-13 16:44:44 -07003752
Mathias Agopian386aa982011-11-07 21:58:03 -08003753 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003754 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3755 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003756 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003757
3758 // if this is a synchronous transaction, wait for it to take effect
3759 // before returning.
3760 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003761 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003762 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003763 if (flags & eAnimation) {
3764 mAnimTransactionPending = true;
3765 }
chaviw4fe36852019-04-15 16:25:49 -07003766 if (mPendingInputWindowCommands.syncInputWindows) {
3767 mPendingSyncInputWindows = true;
3768 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003769
3770 // applyTransactionState can be called by either the main SF thread or by
3771 // another process through setTransactionState. While a given process may wish
3772 // to wait on synchronous transactions, the main SF thread should never
3773 // be blocked. Therefore, we only wait if isMainThread is false.
3774 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003775 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3776 if (CC_UNLIKELY(err != NO_ERROR)) {
3777 // just in case something goes wrong in SF, return to the
3778 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003779 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3780 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003781 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003782 break;
3783 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003784 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003785 }
3786}
3787
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003788uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3789 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3790 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003791
Mathias Agopiane57f2922012-08-09 16:29:12 -07003792 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003793 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3794
3795 const uint32_t what = s.what;
3796 if (what & DisplayState::eSurfaceChanged) {
3797 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3798 state.surface = s.surface;
3799 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003800 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003801 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003802 if (what & DisplayState::eLayerStackChanged) {
3803 if (state.layerStack != s.layerStack) {
3804 state.layerStack = s.layerStack;
3805 flags |= eDisplayTransactionNeeded;
3806 }
3807 }
3808 if (what & DisplayState::eDisplayProjectionChanged) {
3809 if (state.orientation != s.orientation) {
3810 state.orientation = s.orientation;
3811 flags |= eDisplayTransactionNeeded;
3812 }
3813 if (state.frame != s.frame) {
3814 state.frame = s.frame;
3815 flags |= eDisplayTransactionNeeded;
3816 }
3817 if (state.viewport != s.viewport) {
3818 state.viewport = s.viewport;
3819 flags |= eDisplayTransactionNeeded;
3820 }
3821 }
3822 if (what & DisplayState::eDisplaySizeChanged) {
3823 if (state.width != s.width) {
3824 state.width = s.width;
3825 flags |= eDisplayTransactionNeeded;
3826 }
3827 if (state.height != s.height) {
3828 state.height = s.height;
3829 flags |= eDisplayTransactionNeeded;
3830 }
3831 }
3832
Mathias Agopiane57f2922012-08-09 16:29:12 -07003833 return flags;
3834}
3835
Robert Carr14167e02019-02-13 13:50:55 -08003836bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003837 IPCThreadState* ipc = IPCThreadState::self();
3838 const int pid = ipc->getCallingPid();
3839 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003840 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003841 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003842 return false;
3843 }
3844 return true;
3845}
3846
Marissa Wall3dad52d2019-03-22 14:03:19 -07003847uint32_t SurfaceFlinger::setClientStateLocked(
3848 const ComposerState& composerState, int64_t desiredPresentTime,
3849 const std::vector<ListenerCallbacks>& listenerCallbacks, int64_t postTime,
3850 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003851 const layer_state_t& s = composerState.state;
3852 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3853
Mathias Agopian13127d82013-03-05 17:47:11 -08003854 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003855 if (layer == nullptr) {
3856 return 0;
3857 }
3858
chaviw8b3871a2017-11-01 17:41:01 -07003859 uint32_t flags = 0;
3860
Garfield Tan8a3083e2018-12-03 13:21:07 -08003861 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003862 bool geometryAppliesWithResize =
3863 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003864
3865 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3866 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003867 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003868 layer->pushPendingState();
3869 }
3870
chaviw8b3871a2017-11-01 17:41:01 -07003871 if (what & layer_state_t::ePositionChanged) {
3872 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3873 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003874 }
chaviw8b3871a2017-11-01 17:41:01 -07003875 }
3876 if (what & layer_state_t::eLayerChanged) {
3877 // NOTE: index needs to be calculated before we update the state
3878 const auto& p = layer->getParent();
3879 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003880 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003881 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003882 mCurrentState.layersSortedByZ.removeAt(idx);
3883 mCurrentState.layersSortedByZ.add(layer);
3884 // we need traversal (state changed)
3885 // AND transaction (list changed)
3886 flags |= eTransactionNeeded|eTraversalNeeded;
3887 }
chaviw8b3871a2017-11-01 17:41:01 -07003888 } else {
3889 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003890 flags |= eTransactionNeeded|eTraversalNeeded;
3891 }
3892 }
chaviw8b3871a2017-11-01 17:41:01 -07003893 }
3894 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003895 // NOTE: index needs to be calculated before we update the state
3896 const auto& p = layer->getParent();
3897 if (p == nullptr) {
3898 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3899 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3900 mCurrentState.layersSortedByZ.removeAt(idx);
3901 mCurrentState.layersSortedByZ.add(layer);
3902 // we need traversal (state changed)
3903 // AND transaction (list changed)
3904 flags |= eTransactionNeeded|eTraversalNeeded;
3905 }
3906 } else {
3907 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3908 flags |= eTransactionNeeded|eTraversalNeeded;
3909 }
chaviw8b3871a2017-11-01 17:41:01 -07003910 }
3911 }
3912 if (what & layer_state_t::eSizeChanged) {
3913 if (layer->setSize(s.w, s.h)) {
3914 flags |= eTraversalNeeded;
3915 }
3916 }
3917 if (what & layer_state_t::eAlphaChanged) {
3918 if (layer->setAlpha(s.alpha))
3919 flags |= eTraversalNeeded;
3920 }
3921 if (what & layer_state_t::eColorChanged) {
3922 if (layer->setColor(s.color))
3923 flags |= eTraversalNeeded;
3924 }
Peiyong Lind3788632018-09-18 16:01:31 -07003925 if (what & layer_state_t::eColorTransformChanged) {
3926 if (layer->setColorTransform(s.colorTransform)) {
3927 flags |= eTraversalNeeded;
3928 }
3929 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003930 if (what & layer_state_t::eBackgroundColorChanged) {
3931 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3932 flags |= eTraversalNeeded;
3933 }
3934 }
chaviw8b3871a2017-11-01 17:41:01 -07003935 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003936 // TODO: b/109894387
3937 //
3938 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3939 // rotation. To see the problem observe that if we have a square parent, and a child
3940 // of the same size, then we rotate the child 45 degrees around it's center, the child
3941 // must now be cropped to a non rectangular 8 sided region.
3942 //
3943 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3944 // private API, and the WindowManager only uses rotation in one case, which is on a top
3945 // level layer in which cropping is not an issue.
3946 //
3947 // However given that abuse of rotation matrices could lead to surfaces extending outside
3948 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3949 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3950 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003951 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003952 flags |= eTraversalNeeded;
3953 }
3954 if (what & layer_state_t::eTransparentRegionChanged) {
3955 if (layer->setTransparentRegionHint(s.transparentRegion))
3956 flags |= eTraversalNeeded;
3957 }
3958 if (what & layer_state_t::eFlagsChanged) {
3959 if (layer->setFlags(s.flags, s.mask))
3960 flags |= eTraversalNeeded;
3961 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003962 if (what & layer_state_t::eCropChanged_legacy) {
3963 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003964 flags |= eTraversalNeeded;
3965 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003966 if (what & layer_state_t::eCornerRadiusChanged) {
3967 if (layer->setCornerRadius(s.cornerRadius))
3968 flags |= eTraversalNeeded;
3969 }
chaviw8b3871a2017-11-01 17:41:01 -07003970 if (what & layer_state_t::eLayerStackChanged) {
3971 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3972 // We only allow setting layer stacks for top level layers,
3973 // everything else inherits layer stack from its parent.
3974 if (layer->hasParent()) {
3975 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3976 layer->getName().string());
3977 } else if (idx < 0) {
3978 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3979 "that also does not appear in the top level layer list. Something"
3980 " has gone wrong.", layer->getName().string());
3981 } else if (layer->setLayerStack(s.layerStack)) {
3982 mCurrentState.layersSortedByZ.removeAt(idx);
3983 mCurrentState.layersSortedByZ.add(layer);
3984 // we need traversal (state changed)
3985 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003986 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003987 }
3988 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003989 if (what & layer_state_t::eDeferTransaction_legacy) {
3990 if (s.barrierHandle_legacy != nullptr) {
3991 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3992 } else if (s.barrierGbp_legacy != nullptr) {
3993 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003994 if (authenticateSurfaceTextureLocked(gbp)) {
3995 const auto& otherLayer =
3996 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003997 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003998 } else {
3999 ALOGE("Attempt to defer transaction to to an"
4000 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08004001 }
4002 }
chaviw8b3871a2017-11-01 17:41:01 -07004003 // We don't trigger a traversal here because if no other state is
4004 // changed, we don't want this to cause any more work
4005 }
4006 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08004007 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07004008 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08004009 if (!hadParent) {
4010 mCurrentState.layersSortedByZ.remove(layer);
4011 }
chaviw8b3871a2017-11-01 17:41:01 -07004012 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08004013 }
chaviw8b3871a2017-11-01 17:41:01 -07004014 }
4015 if (what & layer_state_t::eReparentChildren) {
4016 if (layer->reparentChildren(s.reparentHandle)) {
4017 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07004018 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004019 }
chaviw8b3871a2017-11-01 17:41:01 -07004020 if (what & layer_state_t::eDetachChildren) {
4021 layer->detachChildren();
4022 }
4023 if (what & layer_state_t::eOverrideScalingModeChanged) {
4024 layer->setOverrideScalingMode(s.overrideScalingMode);
4025 // We don't trigger a traversal here because if no other state is
4026 // changed, we don't want this to cause any more work
4027 }
Marissa Wall61c58622018-07-18 10:12:20 -07004028 if (what & layer_state_t::eTransformChanged) {
4029 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4030 }
4031 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4032 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4033 flags |= eTraversalNeeded;
4034 }
4035 if (what & layer_state_t::eCropChanged) {
4036 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4037 }
Marissa Wall861616d2018-10-22 12:52:23 -07004038 if (what & layer_state_t::eFrameChanged) {
4039 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
4040 }
Marissa Wall61c58622018-07-18 10:12:20 -07004041 if (what & layer_state_t::eAcquireFenceChanged) {
4042 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4043 }
4044 if (what & layer_state_t::eDataspaceChanged) {
4045 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4046 }
4047 if (what & layer_state_t::eHdrMetadataChanged) {
4048 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4049 }
4050 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4051 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4052 }
4053 if (what & layer_state_t::eApiChanged) {
4054 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4055 }
4056 if (what & layer_state_t::eSidebandStreamChanged) {
4057 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4058 }
Robert Carr720e5062018-07-30 17:45:14 -07004059 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08004060 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004061 layer->setInputInfo(s.inputInfo);
4062 flags |= eTraversalNeeded;
4063 } else {
4064 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4065 }
Robert Carr720e5062018-07-30 17:45:14 -07004066 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004067 if (what & layer_state_t::eMetadataChanged) {
4068 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4069 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004070 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4071 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4072 flags |= eTraversalNeeded;
4073 }
4074 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004075 std::vector<sp<CallbackHandle>> callbackHandles;
Marissa Wall3dad52d2019-03-22 14:03:19 -07004076 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!listenerCallbacks.empty())) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07004077 for (const auto& [listener, callbackIds] : listenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07004078 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4079 }
4080 }
Marissa Wall78b72202019-03-15 14:58:34 -07004081 bool bufferChanged = what & layer_state_t::eBufferChanged;
4082 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
4083 sp<GraphicBuffer> buffer;
4084 if (bufferChanged && cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004085 ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004086 buffer = s.buffer;
4087 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004088 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004089 } else if (bufferChanged) {
4090 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08004091 }
Marissa Wall78b72202019-03-15 14:58:34 -07004092 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004093 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08004094 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08004095 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004096 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004097 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4098 // Do not put anything that updates layer state or modifies flags after
4099 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004100 return flags;
4101}
4102
chaviw273171b2018-12-26 11:46:30 -08004103uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4104 uint32_t flags = 0;
4105 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4106 flags |= eTraversalNeeded;
4107 }
4108
chaviwa911b102019-02-14 10:18:33 -08004109 if (inputWindowCommands.syncInputWindows) {
4110 flags |= eTraversalNeeded;
4111 }
4112
Vishnu Nairec0ab382019-02-13 15:32:56 -08004113 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004114 return flags;
4115}
4116
Marissa Wall2d814fb2019-04-09 18:52:57 +00004117status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4118 uint32_t h, PixelFormat format, uint32_t flags,
4119 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07004120 sp<IGraphicBufferProducer>* gbp,
4121 const sp<IBinder>& parentHandle,
4122 const sp<Layer>& parentLayer) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004123 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004124 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004125 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004126 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004127 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004128
Robert Carrc0df3122019-04-11 13:18:21 -07004129 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4130 "Expected only one of parentLayer or parentHandle to be non-null. "
4131 "Programmer error?");
4132
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004133 status_t result = NO_ERROR;
4134
4135 sp<Layer> layer;
4136
Cody Northropbc755282017-03-31 12:00:08 -06004137 String8 uniqueName = getUniqueLayerName(name);
4138
Evan Roskya1f1e152019-01-24 16:17:46 -08004139 bool primaryDisplayOnly = false;
4140
4141 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4142 // TODO b/64227542
4143 if (metadata.has(METADATA_WINDOW_TYPE)) {
4144 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4145 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07004146 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08004147 primaryDisplayOnly = true;
4148 }
4149 }
4150
Mathias Agopian3165cc22012-08-08 19:42:09 -07004151 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004152 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Evan Roskya1f1e152019-01-24 16:17:46 -08004153 result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata),
4154 format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004155
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004156 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004157 case ISurfaceComposerClient::eFXSurfaceBufferState:
Evan Roskya1f1e152019-01-24 16:17:46 -08004158 result = createBufferStateLayer(client, uniqueName, w, h, flags, std::move(metadata),
4159 handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07004160 break;
chaviw13fdc492017-06-27 12:40:18 -07004161 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004162 // check if buffer size is set for color layer.
4163 if (w > 0 || h > 0) {
4164 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4165 int(w), int(h));
4166 return BAD_VALUE;
4167 }
4168
Evan Roskya1f1e152019-01-24 16:17:46 -08004169 result = createColorLayer(client, uniqueName, w, h, flags, std::move(metadata), handle,
4170 &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004171 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004172 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004173 // check if buffer size is set for container layer.
4174 if (w > 0 || h > 0) {
4175 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4176 int(w), int(h));
4177 return BAD_VALUE;
4178 }
Evan Roskya1f1e152019-01-24 16:17:46 -08004179 result = createContainerLayer(client, uniqueName, w, h, flags, std::move(metadata),
4180 handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004181 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004182 default:
4183 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004184 break;
4185 }
4186
Dan Stoza7d89d062015-04-30 13:29:25 -07004187 if (result != NO_ERROR) {
4188 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004189 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004190
Evan Roskya1f1e152019-01-24 16:17:46 -08004191 if (primaryDisplayOnly) {
4192 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07004193 }
4194
Robert Carrb89ea9d2018-12-10 13:01:14 -08004195 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07004196 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
4197 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004198 if (result != NO_ERROR) {
4199 return result;
4200 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004201 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004202
4203 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004204 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004205}
4206
Cody Northropbc755282017-03-31 12:00:08 -06004207String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4208{
4209 bool matchFound = true;
4210 uint32_t dupeCounter = 0;
4211
4212 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4213 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4214
Dan Stoza436ccf32018-06-21 12:10:12 -07004215 // Grab the state lock since we're accessing mCurrentState
4216 Mutex::Autolock lock(mStateLock);
4217
Cody Northropbc755282017-03-31 12:00:08 -06004218 // Loop over layers until we're sure there is no matching name
4219 while (matchFound) {
4220 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004221 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004222 if (layer->getName() == uniqueName) {
4223 matchFound = true;
4224 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4225 }
4226 });
4227 }
4228
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004229 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4230 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004231
4232 return uniqueName;
4233}
4234
Marissa Wallfd668622018-05-10 10:21:13 -07004235status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4236 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004237 LayerMetadata metadata, PixelFormat& format,
4238 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004239 sp<IGraphicBufferProducer>* gbp,
4240 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004241 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004242 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004243 case PIXEL_FORMAT_TRANSPARENT:
4244 case PIXEL_FORMAT_TRANSLUCENT:
4245 format = PIXEL_FORMAT_RGBA_8888;
4246 break;
4247 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004248 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004249 break;
4250 }
4251
Evan Roskya1f1e152019-01-24 16:17:46 -08004252 sp<BufferQueueLayer> layer = getFactory().createBufferQueueLayer(
4253 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wallfd668622018-05-10 10:21:13 -07004254 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004255 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004256 *handle = layer->getHandle();
4257 *gbp = layer->getProducer();
4258 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004259 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004260
Marissa Wallfd668622018-05-10 10:21:13 -07004261 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004262 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004263}
4264
Marissa Wall61c58622018-07-18 10:12:20 -07004265status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4266 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004267 LayerMetadata metadata, sp<IBinder>* handle,
4268 sp<Layer>* outLayer) {
4269 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(
4270 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wall61c58622018-07-18 10:12:20 -07004271 *handle = layer->getHandle();
4272 *outLayer = layer;
4273
4274 return NO_ERROR;
4275}
4276
Evan Roskya1f1e152019-01-24 16:17:46 -08004277status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, uint32_t w,
4278 uint32_t h, uint32_t flags, LayerMetadata metadata,
4279 sp<IBinder>* handle, sp<Layer>* outLayer) {
4280 *outLayer = getFactory().createColorLayer(
4281 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004282 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004283 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004284}
4285
Evan Roskya1f1e152019-01-24 16:17:46 -08004286status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name,
4287 uint32_t w, uint32_t h, uint32_t flags,
4288 LayerMetadata metadata, sp<IBinder>* handle,
4289 sp<Layer>* outLayer) {
4290 *outLayer = getFactory().createContainerLayer(
4291 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004292 *handle = (*outLayer)->getHandle();
4293 return NO_ERROR;
4294}
4295
4296
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004297void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004298 mLayersPendingRemoval.add(layer);
4299 mLayersRemoved = true;
4300 setTransactionFlags(eTransactionNeeded);
4301}
4302
Robert Carr695d5282018-12-18 15:27:58 -08004303void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004304{
Robert Carr2e102c92018-10-23 12:11:15 -07004305 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004306 // If a layer has a parent, we allow it to out-live it's handle
4307 // with the idea that the parent holds a reference and will eventually
4308 // be cleaned up. However no one cleans up the top-level so we do so
4309 // here.
4310 if (layer->getParent() == nullptr) {
4311 mCurrentState.layersSortedByZ.remove(layer);
4312 }
4313 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004314
4315 auto it = mLayersByLocalBinderToken.begin();
4316 while (it != mLayersByLocalBinderToken.end()) {
4317 if (it->second == layer) {
4318 it = mLayersByLocalBinderToken.erase(it);
4319 } else {
4320 it++;
4321 }
4322 }
4323
Robert Carr695d5282018-12-18 15:27:58 -08004324 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004325}
4326
Mathias Agopianb60314a2012-04-10 22:09:54 -07004327// ---------------------------------------------------------------------------
4328
Andy McFadden13a082e2012-08-24 10:16:42 -07004329void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004330 const auto display = getDefaultDisplayDeviceLocked();
4331 if (!display) return;
4332
4333 const sp<IBinder> token = display->getDisplayToken().promote();
4334 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004335
Jesse Hall01e29052013-02-19 16:13:35 -08004336 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004337 Vector<ComposerState> state;
4338 Vector<DisplayState> displays;
4339 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004340 d.what = DisplayState::eDisplayProjectionChanged |
4341 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004342 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004343 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004344 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004345 d.frame.makeInvalid();
4346 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004347 d.width = 0;
4348 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004349 displays.add(d);
Marissa Wall3dad52d2019-03-22 14:03:19 -07004350 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004351
Dominik Laskowskie9774092018-12-11 10:04:24 -08004352 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004353
Dominik Laskowski83b88212018-12-11 13:34:06 -08004354 const nsecs_t vsyncPeriod = getVsyncPeriod();
4355 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004356
Brian Andersond0010582017-03-07 13:20:31 -08004357 // Use phase of 0 since phase is not known.
4358 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004359 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004360 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004361}
4362
4363void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004364 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004365 postMessageAsync(
4366 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004367}
4368
Dominik Laskowskie9774092018-12-11 10:04:24 -08004369void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004370 if (display->isVirtual()) {
4371 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004372 return;
4373 }
4374
Dominik Laskowski075d3172018-05-24 15:50:06 -07004375 const auto displayId = display->getId();
4376 LOG_ALWAYS_FATAL_IF(!displayId);
4377
Dominik Laskowski34157762018-10-31 13:07:19 -07004378 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004379
4380 int currentMode = display->getPowerMode();
4381 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004382 return;
4383 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004384
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004385 display->setPowerMode(mode);
4386
Lloyd Pique4dccc412018-01-22 17:21:36 -08004387 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004388 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004389 }
4390
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004391 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004392 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004393 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004394 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004395 mScheduler->onScreenAcquired(mAppConnectionHandle);
4396 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004397 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004398
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004399 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004400 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004401 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004402
4403 struct sched_param param = {0};
4404 param.sched_priority = 1;
4405 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4406 ALOGW("Couldn't set SCHED_FIFO on display on");
4407 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004408 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004409 // Turn off the display
4410 struct sched_param param = {0};
4411 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4412 ALOGW("Couldn't set SCHED_OTHER on display off");
4413 }
4414
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004415 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004416 mScheduler->disableHardwareVsync(true);
4417 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004418 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004419
Dominik Laskowski075d3172018-05-24 15:50:06 -07004420 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004421 mVisibleRegionsDirty = true;
4422 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004423 } else if (mode == HWC_POWER_MODE_DOZE ||
4424 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004425 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004426 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004427 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004428 mScheduler->onScreenAcquired(mAppConnectionHandle);
4429 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004430 }
4431 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4432 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004433 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004434 mScheduler->disableHardwareVsync(true);
4435 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004436 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004437 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004438 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004439 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004440 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004441 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004442
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004443 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004444 mTimeStats->setPowerMode(mode);
Dominik Laskowski22488f62019-03-28 09:53:04 -07004445 mRefreshRateStats.setPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004446 }
4447
Dominik Laskowski34157762018-10-31 13:07:19 -07004448 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004449}
4450
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004451void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004452 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004453 const auto display = getDisplayDevice(displayToken);
4454 if (!display) {
4455 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4456 displayToken.get());
4457 } else if (display->isVirtual()) {
4458 ALOGW("Attempt to set power mode %d for virtual display", mode);
4459 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004460 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004461 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004462 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004463}
4464
4465// ---------------------------------------------------------------------------
4466
Dominik Laskowskic2867142019-01-21 11:33:38 -08004467status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4468 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004469 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004470
Mathias Agopianbd115332013-04-18 16:41:04 -07004471 IPCThreadState* ipc = IPCThreadState::self();
4472 const int pid = ipc->getCallingPid();
4473 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004474
Mathias Agopianbd115332013-04-18 16:41:04 -07004475 if ((uid != AID_SHELL) &&
4476 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004477 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4478 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004479 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004480 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004481 // (this would indicate SF is stuck, but we want to be able to
4482 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004483 status_t err = mStateLock.timedLock(s2ns(1));
4484 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004485 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004486 StringAppendF(&result,
4487 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4488 "(no locks held)\n",
4489 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004490 }
4491
Dominik Laskowskic2867142019-01-21 11:33:38 -08004492 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004493
Dominik Laskowskic2867142019-01-21 11:33:38 -08004494 static const std::unordered_map<std::string, Dumper> dumpers = {
4495 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4496 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4497 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004498 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004499 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004500 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004501 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4502 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004503 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4504 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4505 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4506 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4507 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4508 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004509 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004510 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4511 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004512
Dominik Laskowskic2867142019-01-21 11:33:38 -08004513 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004514
Dominik Laskowskic2867142019-01-21 11:33:38 -08004515 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4516 (it->second)(args, asProto, result);
4517 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004518 if (asProto) {
4519 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4520 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4521 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004522 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004523 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004524 }
4525
Mathias Agopian9795c422009-08-26 16:36:26 -07004526 if (locked) {
4527 mStateLock.unlock();
4528 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004529 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004530 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004531 return NO_ERROR;
4532}
4533
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004534status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4535 if (asProto && mTracing.isEnabled()) {
4536 mTracing.writeToFileAsync();
4537 }
4538
4539 return doDump(fd, DumpArgs(), asProto);
4540}
4541
Dominik Laskowskic2867142019-01-21 11:33:38 -08004542void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004543 mCurrentState.traverseInZOrder(
4544 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004545}
4546
Dominik Laskowskic2867142019-01-21 11:33:38 -08004547void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004548 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004549
Dominik Laskowskic2867142019-01-21 11:33:38 -08004550 if (args.size() > 1) {
4551 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004552 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004553 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004554 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004555 }
Robert Carr2047fae2016-11-28 14:09:09 -08004556 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004557 } else {
4558 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004559 }
4560}
4561
Dominik Laskowskic2867142019-01-21 11:33:38 -08004562void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004563 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004564 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004565 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004566 }
Robert Carr2047fae2016-11-28 14:09:09 -08004567 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004568
Svetoslavd85084b2014-03-20 10:28:31 -07004569 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004570}
4571
Dominik Laskowskic2867142019-01-21 11:33:38 -08004572void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4573 mTimeStats->parseArgs(asProto, args, result);
4574}
4575
Jamie Gennis6547ff42013-07-16 20:12:42 -07004576// This should only be called from the main thread. Otherwise it would need
4577// the lock and should use mCurrentState rather than mDrawingState.
4578void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004579 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004580 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004581 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004582
4583 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4584}
4585
Yiwei Zhang5434a782018-12-05 18:06:32 -08004586void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004587 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004588
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004589 if (isLayerTripleBufferingDisabled())
4590 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004591
Yiwei Zhang5434a782018-12-05 18:06:32 -08004592 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4593 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4594 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4595 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4596 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4597 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004598 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004599}
4600
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004601void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004602 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004603 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004604 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004605 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004606
Ady Abraham97d04232019-03-05 19:48:12 -08004607 StringAppendF(&result, "Scheduler enabled.");
Ana Krulecba13ab32019-02-20 14:14:12 -08004608 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4609 mUseSmart90ForVideo ? "on" : "off");
Ana Krulecc2870422019-01-29 19:00:58 -08004610 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004611}
4612
Yiwei Zhang5434a782018-12-05 18:06:32 -08004613void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4614 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004615 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4616 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004617 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004618 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004619 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004620 }
David Sodman4a36e932017-11-07 14:29:47 -08004621 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004622 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004623 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004624 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4625 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004626}
4627
Dan Stozae77c7662016-05-13 11:37:28 -07004628void SurfaceFlinger::recordBufferingStats(const char* layerName,
4629 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004630 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4631 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004632 for (const auto& segment : history) {
4633 if (!segment.usedThirdBuffer) {
4634 stats.twoBufferTime += segment.totalTime;
4635 }
4636 if (segment.occupancyAverage < 1.0f) {
4637 stats.doubleBufferedTime += segment.totalTime;
4638 } else if (segment.occupancyAverage < 2.0f) {
4639 stats.tripleBufferedTime += segment.totalTime;
4640 }
4641 ++stats.numSegments;
4642 stats.totalTime += segment.totalTime;
4643 }
4644}
4645
Yiwei Zhang5434a782018-12-05 18:06:32 -08004646void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4647 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004648
4649 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4650 const size_t count = currentLayers.size();
4651 for (size_t i=0 ; i<count ; i++) {
4652 currentLayers[i]->dumpFrameEvents(result);
4653 }
4654}
4655
Yiwei Zhang5434a782018-12-05 18:06:32 -08004656void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004657 result.append("Buffering stats:\n");
4658 result.append(" [Layer name] <Active time> <Two buffer> "
4659 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004660 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004661 typedef std::tuple<std::string, float, float, float> BufferTuple;
4662 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004663 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004664 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004665 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004666 if (stats.numSegments == 0) {
4667 continue;
4668 }
4669 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4670 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4671 stats.totalTime;
4672 float doubleBufferRatio = static_cast<float>(
4673 stats.doubleBufferedTime) / stats.totalTime;
4674 float tripleBufferRatio = static_cast<float>(
4675 stats.tripleBufferedTime) / stats.totalTime;
4676 sorted.insert({activeTime, {name, twoBufferRatio,
4677 doubleBufferRatio, tripleBufferRatio}});
4678 }
4679 for (const auto& sortedPair : sorted) {
4680 float activeTime = sortedPair.first;
4681 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004682 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4683 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004684 }
4685 result.append("\n");
4686}
4687
Yiwei Zhang5434a782018-12-05 18:06:32 -08004688void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004689 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004690 const auto displayId = display->getId();
4691 if (!displayId) {
4692 continue;
4693 }
4694 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004695 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004696 continue;
4697 }
4698
Yiwei Zhang5434a782018-12-05 18:06:32 -08004699 StringAppendF(&result,
4700 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4701 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004702 uint8_t port;
4703 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004704 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004705 result.append("no identification data\n");
4706 continue;
4707 }
4708
4709 if (!isEdid(data)) {
4710 result.append("unknown identification data: ");
4711 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004712 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004713 }
4714 result.append("\n");
4715 continue;
4716 }
4717
4718 const auto edid = parseEdid(data);
4719 if (!edid) {
4720 result.append("invalid EDID: ");
4721 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004722 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004723 }
4724 result.append("\n");
4725 continue;
4726 }
4727
Yiwei Zhang5434a782018-12-05 18:06:32 -08004728 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004729 result.append(edid->displayName.data(), edid->displayName.length());
4730 result.append("\"\n");
4731 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004732}
4733
Yiwei Zhang5434a782018-12-05 18:06:32 -08004734void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4735 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4736 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4737 StringAppendF(&result, "DisplayColorSetting: %s\n",
4738 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004739
4740 // TODO: print out if wide-color mode is active or not
4741
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004742 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004743 const auto displayId = display->getId();
4744 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004745 continue;
4746 }
4747
Yiwei Zhang5434a782018-12-05 18:06:32 -08004748 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004749 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004750 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004751 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004752 }
4753
Lloyd Pique32cbe282018-10-19 13:09:22 -07004754 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004755 StringAppendF(&result, " Current color mode: %s (%d)\n",
4756 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004757 }
4758 result.append("\n");
4759}
4760
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004761LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet,
4762 uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004763 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004764 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4765 const State& state = useDrawing ? mDrawingState : mCurrentState;
4766 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004767 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004768 layer->writeToProto(layerProto, stateSet, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004769 });
4770
4771 return layersProto;
4772}
4773
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004774LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4775 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004776 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004777
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004778 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004779 resolution->set_w(displayDevice->getWidth());
4780 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004781
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004782 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004783 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004784
Lloyd Pique32cbe282018-10-19 13:09:22 -07004785 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4786 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4787 layersProto.set_global_transform(displayState.orientation);
4788
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004789 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004790 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004791 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004792 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004793 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004794 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004795 }
4796 });
4797
4798 return layersProto;
4799}
4800
Dominik Laskowskic2867142019-01-21 11:33:38 -08004801void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4802 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004803 Colorizer colorizer(colorize);
4804
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004805 // figure out if we're stuck somewhere
4806 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004807 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004808 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4809
4810 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004811 * Dump library configuration.
4812 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004813
4814 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004815 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004816 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004817 appendSfConfigString(result);
4818 appendUiConfigString(result);
4819 appendGuiConfigString(result);
4820 result.append("\n");
4821
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004822 result.append("\nDisplay identification data:\n");
4823 dumpDisplayIdentificationData(result);
4824
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004825 result.append("\nWide-Color information:\n");
4826 dumpWideColorInfo(result);
4827
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004828 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004829 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004830 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004831 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004832 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004833
Andy McFadden41d67d72014-04-25 16:58:34 -07004834 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004835 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004836 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004837 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004838 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004839
Dan Stozab90cf072015-03-05 11:05:59 -08004840 dumpStaticScreenStats(result);
4841 result.append("\n");
4842
Alec Mouri40189b02019-03-05 15:07:54 -08004843 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4844 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4845 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004846
Dan Stozae77c7662016-05-13 11:37:28 -07004847 dumpBufferingStats(result);
4848
Andy McFadden4803b742012-09-24 19:07:20 -07004849 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004850 * Dump the visible layer list
4851 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004852 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004853 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4854 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4855 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004856 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004857
Chia-I Wu2f884132018-09-13 15:17:58 -07004858 {
4859 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4860 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004861 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004862 result.append("\n");
4863 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004864
Lloyd Pique207def92019-02-28 16:09:52 -08004865 {
4866 StringAppendF(&result, "Composition layers\n");
4867 mDrawingState.traverseInZOrder([&](Layer* layer) {
4868 auto compositionLayer = layer->getCompositionLayer();
4869 if (compositionLayer) compositionLayer->dump(result);
4870 });
4871 }
4872
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004873 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004874 * Dump Display state
4875 */
4876
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004877 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004878 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004879 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004880 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004881 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004882 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004883 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004884
4885 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004886 * Dump SurfaceFlinger global state
4887 */
4888
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004889 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004890 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004891 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004892
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004893 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004894
Dominik Laskowski075d3172018-05-24 15:50:06 -07004895 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004896 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4897 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004898 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4899 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004900 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004901 StringAppendF(&result,
4902 " transaction-flags : %08x\n"
4903 " gpu_to_cpu_unsupported : %d\n",
4904 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004905
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004906 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004907 displayId && getHwComposer().isConnected(*displayId)) {
4908 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004909 StringAppendF(&result,
4910 " refresh-rate : %f fps\n"
4911 " x-dpi : %f\n"
4912 " y-dpi : %f\n",
4913 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4914 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004915 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004916
Yiwei Zhang5434a782018-12-05 18:06:32 -08004917 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004918
Dan Stozae22aec72016-08-01 13:20:59 -07004919 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004920 * Tracing state
4921 */
4922 mTracing.dump(result);
4923 result.append("\n");
4924
4925 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004926 * HWC layer minidump
4927 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004928 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004929 const auto displayId = display->getId();
4930 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004931 continue;
4932 }
4933
Yiwei Zhang5434a782018-12-05 18:06:32 -08004934 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004935 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004936 const sp<DisplayDevice> displayDevice = display;
4937 mCurrentState.traverseInZOrder(
4938 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004939 result.append("\n");
4940 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004941
4942 /*
4943 * Dump HWComposer state
4944 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004945 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004946 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004947 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004948 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004949 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004950 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004951
4952 /*
4953 * Dump gralloc state
4954 */
4955 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4956 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004957
4958 /*
4959 * Dump VrFlinger state if in use.
4960 */
4961 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4962 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004963 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004964 result.append("\n");
4965 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004966
4967 /**
4968 * Scheduler dump state.
4969 */
Ana Krulecc2870422019-01-29 19:00:58 -08004970 result.append("\nScheduler state:\n");
4971 result.append(mScheduler->doDump() + "\n");
Ana Krulecfefd6ae2019-02-13 17:53:08 -08004972 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
Dominik Laskowski22488f62019-03-28 09:53:04 -07004973 result.append(mRefreshRateStats.doDump() + "\n");
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004974
4975 result.append(mTimeStats->miniDump());
4976 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004977}
4978
Dominik Laskowski075d3172018-05-24 15:50:06 -07004979const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004980 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004981 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004982 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004983 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004984 }
4985 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004986
Dominik Laskowski34157762018-10-31 13:07:19 -07004987 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004988 static const Vector<sp<Layer>> empty;
4989 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004990}
4991
Chia-I Wu28f320b2018-05-03 11:02:56 -07004992void SurfaceFlinger::updateColorMatrixLocked() {
4993 mat4 colorMatrix;
4994 if (mGlobalSaturationFactor != 1.0f) {
4995 // Rec.709 luma coefficients
4996 float3 luminance{0.213f, 0.715f, 0.072f};
4997 luminance *= 1.0f - mGlobalSaturationFactor;
4998 mat4 saturationMatrix = mat4(
4999 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
5000 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
5001 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
5002 vec4{0.0f, 0.0f, 0.0f, 1.0f}
5003 );
5004 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
5005 } else {
5006 colorMatrix = mClientColorMatrix * mDaltonizer();
5007 }
5008
5009 if (mCurrentState.colorMatrix != colorMatrix) {
5010 mCurrentState.colorMatrix = colorMatrix;
5011 mCurrentState.colorMatrixChanged = true;
5012 setTransactionFlags(eTransactionNeeded);
5013 }
5014}
5015
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005016status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005017#pragma clang diagnostic push
5018#pragma clang diagnostic error "-Wswitch-enum"
5019 switch (static_cast<ISurfaceComposerTag>(code)) {
5020 // These methods should at minimum make sure that the client requested
5021 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005022 case BOOT_FINISHED:
5023 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005024 case CREATE_DISPLAY:
5025 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005026 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005027 case GET_ANIMATION_FRAME_STATS:
5028 case GET_HDR_CAPABILITIES:
5029 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08005030 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005031 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005032 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005033 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005034 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005035 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005036 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
5037 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005038 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5039 IPCThreadState* ipc = IPCThreadState::self();
5040 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5041 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005042 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005043 }
Robert Carr1db73f62016-12-21 12:58:51 -08005044 return OK;
5045 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005046 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005047 IPCThreadState* ipc = IPCThreadState::self();
5048 const int pid = ipc->getCallingPid();
5049 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005050 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5051 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005052 return PERMISSION_DENIED;
5053 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005054 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005055 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005056 // Used by apps to hook Choreographer to SurfaceFlinger.
5057 case CREATE_DISPLAY_EVENT_CONNECTION:
5058 // The following calls are currently used by clients that do not
5059 // request necessary permissions. However, they do not expose any secret
5060 // information, so it is OK to pass them.
5061 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07005062 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005063 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005064 case GET_PHYSICAL_DISPLAY_IDS:
5065 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005066 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005067 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005068 case GET_DISPLAY_CONFIGS:
5069 case GET_DISPLAY_STATS:
5070 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5071 // Calling setTransactionState is safe, because you need to have been
5072 // granted a reference to Client* and Handle* to do anything with it.
5073 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005074 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005075 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005076 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005077 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00005078 case IS_WIDE_COLOR_DISPLAY:
5079 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5080 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005081 return OK;
5082 }
5083 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08005084 case CAPTURE_SCREEN:
5085 case ADD_REGION_SAMPLING_LISTENER:
5086 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005087 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005088 IPCThreadState* ipc = IPCThreadState::self();
5089 const int pid = ipc->getCallingPid();
5090 const int uid = ipc->getCallingUid();
5091 if ((uid != AID_GRAPHICS) &&
5092 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5093 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5094 return PERMISSION_DENIED;
5095 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005096 return OK;
5097 }
5098 // The following codes are deprecated and should never be allowed to access SF.
5099 case CONNECT_DISPLAY_UNUSED:
5100 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5101 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5102 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005103 }
chaviw93df2ea2019-04-30 16:45:12 -07005104 case CAPTURE_SCREEN_BY_ID: {
5105 IPCThreadState* ipc = IPCThreadState::self();
5106 const int uid = ipc->getCallingUid();
5107 if ((uid == AID_GRAPHICS) || (uid == AID_SYSTEM) || (uid == AID_SHELL)) {
5108 return OK;
5109 }
5110 return PERMISSION_DENIED;
5111 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005112 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005113
5114 // These codes are used for the IBinder protocol to either interrogate the recipient
5115 // side of the transaction for its canonical interface descriptor or to dump its state.
5116 // We let them pass by default.
5117 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5118 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5119 code == IBinder::SYSPROPS_TRANSACTION) {
5120 return OK;
5121 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005122 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005123 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07005124 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005125 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5126 return OK;
5127 }
5128 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5129 return PERMISSION_DENIED;
5130#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005131}
5132
Ana Krulec13be8ad2018-08-21 02:43:56 +00005133status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5134 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005135 status_t credentialCheck = CheckTransactCodeCredentials(code);
5136 if (credentialCheck != OK) {
5137 return credentialCheck;
5138 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005139
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005140 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5141 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005142 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005143 IPCThreadState* ipc = IPCThreadState::self();
5144 const int uid = ipc->getCallingUid();
5145 if (CC_UNLIKELY(uid != AID_SYSTEM
5146 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005147 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005148 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005149 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005150 return PERMISSION_DENIED;
5151 }
5152 int n;
5153 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005154 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005155 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005156 return NO_ERROR;
5157 case 1002: // SHOW_UPDATES
5158 n = data.readInt32();
5159 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005160 invalidateHwcGeometry();
5161 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005162 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005163 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005164 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005165 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005166 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005167 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005168 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005169 setTransactionFlags(
5170 eTransactionNeeded|
5171 eDisplayTransactionNeeded|
5172 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005173 return NO_ERROR;
5174 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005175 case 1006:{ // send empty update
5176 signalRefresh();
5177 return NO_ERROR;
5178 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005179 case 1008: // toggle use of hw composer
5180 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005181 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07005182 invalidateHwcGeometry();
5183 repaintEverything();
5184 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005185 case 1009: // toggle use of transform hint
5186 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005187 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07005188 invalidateHwcGeometry();
5189 repaintEverything();
5190 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005191 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005192 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005193 reply->writeInt32(0);
5194 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005195 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005196 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005197 return NO_ERROR;
5198 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005199 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005200 if (!display) {
5201 return NAME_NOT_FOUND;
5202 }
5203
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005204 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005205 return NO_ERROR;
5206 }
5207 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005208 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005209 // daltonize
5210 n = data.readInt32();
5211 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005212 case 1:
5213 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5214 break;
5215 case 2:
5216 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5217 break;
5218 case 3:
5219 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5220 break;
5221 default:
5222 mDaltonizer.setType(ColorBlindnessType::None);
5223 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005224 }
5225 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005226 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005227 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005228 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005229 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005230
5231 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005232 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005233 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005234 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005235 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005236 // apply a color matrix
5237 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005238 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005239 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005240 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005241 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005242 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005243 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005244 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005245 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005246 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005247 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005248
5249 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5250 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005251 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005252 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5253 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5254 }
5255
Chia-I Wu28f320b2018-05-03 11:02:56 -07005256 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005257 return NO_ERROR;
5258 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005259 // This is an experimental interface
5260 // Needs to be shifted to proper binder interface when we productize
5261 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005262 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005263 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005264 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005265 return NO_ERROR;
5266 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005267 case 1017: {
5268 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005269 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005270 return NO_ERROR;
5271 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005272 case 1018: { // Modify Choreographer's phase offset
5273 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005274 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005275 return NO_ERROR;
5276 }
5277 case 1019: { // Modify SurfaceFlinger's phase offset
5278 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005279 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005280 return NO_ERROR;
5281 }
Irvel468051e2016-06-13 16:44:44 -07005282 case 1020: { // Layer updates interceptor
5283 n = data.readInt32();
5284 if (n) {
5285 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005286 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005287 }
5288 else{
5289 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005290 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005291 }
5292 return NO_ERROR;
5293 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005294 case 1021: { // Disable HWC virtual displays
5295 n = data.readInt32();
5296 mUseHwcVirtualDisplays = !n;
5297 return NO_ERROR;
5298 }
Romain Guy0147a172017-06-01 13:53:56 -07005299 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005300 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005301 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005302
Chia-I Wu28f320b2018-05-03 11:02:56 -07005303 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005304 return NO_ERROR;
5305 }
Romain Guy54f154a2017-10-24 21:40:32 +01005306 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005307 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005308 invalidateHwcGeometry();
5309 repaintEverything();
5310 return NO_ERROR;
5311 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005312 // Deprecate, use 1030 to check whether the device is color managed.
5313 case 1024: {
5314 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005315 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005316 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005317 n = data.readInt32();
5318 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005319 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005320 Mutex::Autolock lock(mStateLock);
5321 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005322 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005323 reply->writeInt32(NO_ERROR);
5324 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005325 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005326 bool writeFile = false;
5327 {
5328 Mutex::Autolock lock(mStateLock);
5329 mTracingEnabledChanged = true;
5330 writeFile = mTracing.disable();
5331 }
5332
5333 if (writeFile) {
5334 reply->writeInt32(mTracing.writeToFile());
5335 } else {
5336 reply->writeInt32(NO_ERROR);
5337 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005338 }
5339 return NO_ERROR;
5340 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005341 case 1026: { // Get layer tracing status
5342 reply->writeBool(mTracing.isEnabled());
5343 return NO_ERROR;
5344 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005345 // Is a DisplayColorSetting supported?
5346 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005347 const auto display = getDefaultDisplayDevice();
5348 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005349 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005350 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005351
5352 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5353 switch (setting) {
5354 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005355 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005356 break;
5357 case DisplayColorSetting::UNMANAGED:
5358 reply->writeBool(true);
5359 break;
5360 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005361 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005362 break;
5363 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005364 reply->writeBool(
5365 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005366 break;
5367 }
5368 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005369 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005370 // Is VrFlinger active?
5371 case 1028: {
5372 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005373 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005374 return NO_ERROR;
5375 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005376 // Set buffer size for SF tracing (value in KB)
5377 case 1029: {
5378 n = data.readInt32();
5379 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5380 ALOGW("Invalid buffer size: %d KB", n);
5381 reply->writeInt32(BAD_VALUE);
5382 return BAD_VALUE;
5383 }
5384
5385 ALOGD("Updating trace buffer to %d KB", n);
5386 mTracing.setBufferSize(n * 1024);
5387 reply->writeInt32(NO_ERROR);
5388 return NO_ERROR;
5389 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005390 // Is device color managed?
5391 case 1030: {
5392 reply->writeBool(useColorManagement);
5393 return NO_ERROR;
5394 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005395 // Override default composition data space
5396 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5397 // && adb shell stop zygote && adb shell start zygote
5398 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5399 // adb shell stop zygote && adb shell start zygote
5400 case 1031: {
5401 Mutex::Autolock _l(mStateLock);
5402 n = data.readInt32();
5403 if (n) {
5404 n = data.readInt32();
5405 if (n) {
5406 Dataspace dataspace = static_cast<Dataspace>(n);
5407 if (!validateCompositionDataspace(dataspace)) {
5408 return BAD_VALUE;
5409 }
5410 mDefaultCompositionDataspace = dataspace;
5411 }
5412 n = data.readInt32();
5413 if (n) {
5414 Dataspace dataspace = static_cast<Dataspace>(n);
5415 if (!validateCompositionDataspace(dataspace)) {
5416 return BAD_VALUE;
5417 }
5418 mWideColorGamutCompositionDataspace = dataspace;
5419 }
5420 } else {
5421 // restore composition data space.
5422 mDefaultCompositionDataspace = defaultCompositionDataspace;
5423 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5424 }
5425 return NO_ERROR;
5426 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005427 // Set trace flags
5428 case 1033: {
5429 n = data.readUint32();
5430 ALOGD("Updating trace flags to 0x%x", n);
5431 mTracing.setTraceFlags(n);
5432 reply->writeInt32(NO_ERROR);
5433 return NO_ERROR;
5434 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005435 case 1034: {
5436 // TODO(b/129297325): expose this via developer menu option
5437 n = data.readInt32();
5438 if (n && !mRefreshRateOverlay) {
5439 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5440 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
5441 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
5442 } else if (!n) {
5443 mRefreshRateOverlay.reset();
5444 }
5445 return NO_ERROR;
5446 }
Ady Abraham34392f72019-04-10 11:29:27 -07005447 case 1035: {
5448 n = data.readInt32();
5449 mDebugDisplayConfigSetByBackdoor = false;
5450 if (n >= 0) {
5451 const auto displayToken = getInternalDisplayToken();
5452 status_t result = setAllowedDisplayConfigs(displayToken, {n});
5453 if (result != NO_ERROR) {
5454 return result;
5455 }
5456 mDebugDisplayConfigSetByBackdoor = true;
5457 }
5458 return NO_ERROR;
5459 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005460 }
5461 }
5462 return err;
5463}
5464
Steven Thomas6d8110b2017-08-31 18:24:21 -07005465void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005466 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005467 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005468}
5469
Ana Krulec7d1d6832018-12-27 11:10:09 -08005470void SurfaceFlinger::repaintEverythingForHWC() {
5471 mRepaintEverything = true;
5472 mEventQueue->invalidateForHWC();
5473}
5474
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005475// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5476class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005477public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005478 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5479 ~WindowDisconnector() {
5480 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005481 }
5482
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005483private:
5484 ANativeWindow* mWindow;
5485 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005486};
5487
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005488status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005489 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
5490 const Dataspace reqDataspace,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005491 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005492 uint32_t reqWidth, uint32_t reqHeight,
5493 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08005494 ISurfaceComposer::Rotation rotation,
5495 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005496 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005497
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005498 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005499
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005500 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5501
Chia-I Wu20261cb2018-08-23 12:55:44 -07005502 sp<DisplayDevice> display;
5503 {
5504 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005505
Chia-I Wu20261cb2018-08-23 12:55:44 -07005506 display = getDisplayDeviceLocked(displayToken);
5507 if (!display) return BAD_VALUE;
5508
Chia-I Wucb023152018-08-28 12:57:23 -07005509 // set the requested width/height to the logical display viewport size
5510 // by default
5511 if (reqWidth == 0 || reqHeight == 0) {
5512 reqWidth = uint32_t(display->getViewport().width());
5513 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005514 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005515 }
5516
Peiyong Lin0e003c92018-09-17 11:09:51 -07005517 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005518 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005519
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005520 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5521 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005522 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005523 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005524}
5525
chaviw93df2ea2019-04-30 16:45:12 -07005526static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5527 switch (colorMode) {
5528 case ColorMode::DISPLAY_P3:
5529 case ColorMode::BT2100_PQ:
5530 case ColorMode::BT2100_HLG:
5531 case ColorMode::DISPLAY_BT2020:
5532 return Dataspace::DISPLAY_P3;
5533 default:
5534 return Dataspace::V0_SRGB;
5535 }
5536}
5537
5538const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5539 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5540 if (displayToken) {
5541 return getDisplayDeviceLocked(displayToken);
5542 }
5543 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5544 // may not have a displayId.
5545 for (const auto& [token, display] : mDisplays) {
5546 if (display->getLayerStack() == displayOrLayerStack) {
5547 return display;
5548 }
5549 }
5550 return nullptr;
5551}
5552
5553status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5554 sp<GraphicBuffer>* outBuffer) {
5555 sp<DisplayDevice> display;
5556 uint32_t width;
5557 uint32_t height;
5558 ui::Transform::orientation_flags captureOrientation;
5559 {
5560 Mutex::Autolock _l(mStateLock);
5561 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5562 if (!display) {
5563 return BAD_VALUE;
5564 }
5565
5566 width = uint32_t(display->getViewport().width());
5567 height = uint32_t(display->getViewport().height());
5568
5569 captureOrientation = fromSurfaceComposerRotation(
5570 static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
5571 *outDataspace =
5572 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5573 }
5574
5575 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5576 false /* captureSecureLayers */);
5577
5578 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5579 std::placeholders::_1);
5580 bool ignored = false;
5581 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5582 false /* useIdentityTransform */,
5583 ignored /* outCapturedSecureLayers */);
5584}
5585
Robert Carr866455f2019-04-02 16:28:26 -07005586status_t SurfaceFlinger::captureLayers(
5587 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5588 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5589 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5590 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005591 ATRACE_CALL();
5592
5593 class LayerRenderArea : public RenderArea {
5594 public:
Robert Carr578038f2018-03-09 12:25:24 -08005595 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005596 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5597 bool childrenOnly)
5598 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005599 mLayer(layer),
5600 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005601 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005602 mFlinger(flinger),
5603 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005604 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005605 Rect getBounds() const override {
5606 const Layer::State& layerState(mLayer->getDrawingState());
5607 return mLayer->getBufferSize(layerState);
5608 }
Marissa Wall61c58622018-07-18 10:12:20 -07005609 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005610 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005611 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005612 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005613 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005614 }
chaviwa76b2712017-09-20 12:02:26 -07005615 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005616 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005617 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005618 Rect getSourceCrop() const override {
5619 if (mCrop.isEmpty()) {
5620 return getBounds();
5621 } else {
5622 return mCrop;
5623 }
5624 }
Robert Carr578038f2018-03-09 12:25:24 -08005625 class ReparentForDrawing {
5626 public:
5627 const sp<Layer>& oldParent;
5628 const sp<Layer>& newParent;
5629
Vishnu Nair4351ad52019-02-11 14:13:02 -08005630 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5631 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005632 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005633 // Compute and cache the bounds for the new parent layer.
5634 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005635 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005636 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005637 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005638 };
5639
5640 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005641 const Rect sourceCrop = getSourceCrop();
5642 // no need to check rotation because there is none
5643 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5644 sourceCrop.height() != getReqHeight();
5645
Robert Carr578038f2018-03-09 12:25:24 -08005646 if (!mChildrenOnly) {
5647 mTransform = mLayer->getTransform().inverse();
5648 drawLayers();
5649 } else {
5650 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005651 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005652 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
Evan Roskya1f1e152019-01-24 16:17:46 -08005653 bounds.getWidth(), bounds.getHeight(), 0,
5654 LayerMetadata()));
Robert Carr578038f2018-03-09 12:25:24 -08005655
Vishnu Nair4351ad52019-02-11 14:13:02 -08005656 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005657 drawLayers();
5658 }
5659 }
chaviwa76b2712017-09-20 12:02:26 -07005660
chaviwa76b2712017-09-20 12:02:26 -07005661 private:
chaviw7206d492017-11-10 16:16:12 -08005662 const sp<Layer> mLayer;
5663 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005664
5665 // In the "childrenOnly" case we reparent the children to a screenshot
5666 // layer which has no properties set and which does not draw.
5667 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005668 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005669 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005670
5671 SurfaceFlinger* mFlinger;
5672 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005673 };
5674
Robert Carrc0df3122019-04-11 13:18:21 -07005675 int reqWidth = 0;
5676 int reqHeight = 0;
5677 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005678 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005679 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
chaviw7206d492017-11-10 16:16:12 -08005680
Robert Carrc0df3122019-04-11 13:18:21 -07005681 {
5682 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005683
Robert Carrc0df3122019-04-11 13:18:21 -07005684 parent = fromHandle(layerHandleBinder);
5685 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5686 ALOGE("captureLayers called with an invalid or removed parent");
5687 return NAME_NOT_FOUND;
5688 }
5689
5690 const int uid = IPCThreadState::self()->getCallingUid();
5691 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5692 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5693 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5694 return PERMISSION_DENIED;
5695 }
5696
5697 if (sourceCrop.width() <= 0) {
5698 crop.left = 0;
5699 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
5700 }
5701
5702 if (sourceCrop.height() <= 0) {
5703 crop.top = 0;
5704 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
5705 }
5706 reqWidth = crop.width() * frameScale;
5707 reqHeight = crop.height() * frameScale;
5708
5709 for (const auto& handle : excludeHandles) {
5710 sp<Layer> excludeLayer = fromHandle(handle);
5711 if (excludeLayer != nullptr) {
5712 excludeLayers.emplace(excludeLayer);
5713 } else {
5714 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5715 return NAME_NOT_FOUND;
5716 }
5717 }
5718 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005719
Chia-I Wu20261cb2018-08-23 12:55:44 -07005720 // really small crop or frameScale
5721 if (reqWidth <= 0) {
5722 reqWidth = 1;
5723 }
5724 if (reqHeight <= 0) {
5725 reqHeight = 1;
5726 }
5727
Robert Carr866455f2019-04-02 16:28:26 -07005728 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
5729 auto traverseLayers = [parent, childrenOnly,
5730 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005731 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5732 if (!layer->isVisible()) {
5733 return;
Robert Carr578038f2018-03-09 12:25:24 -08005734 } else if (childrenOnly && layer == parent.get()) {
5735 return;
chaviwa76b2712017-09-20 12:02:26 -07005736 }
Robert Carr866455f2019-04-02 16:28:26 -07005737
5738 sp<Layer> p = layer;
5739 while (p != nullptr) {
5740 if (excludeLayers.count(p) != 0) {
5741 return;
5742 }
5743 p = p->getParent();
5744 }
5745
chaviwa76b2712017-09-20 12:02:26 -07005746 visitor(layer);
5747 });
5748 };
Robert Carr108b2c72019-04-02 16:32:58 -07005749
5750 bool outCapturedSecureLayers = false;
5751 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5752 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005753}
5754
5755status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5756 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005757 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005758 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005759 bool useIdentityTransform,
5760 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005761 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005762
Peiyong Lin0e003c92018-09-17 11:09:51 -07005763 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005764 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5765 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005766 *outBuffer =
5767 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5768 static_cast<android_pixel_format>(reqPixelFormat), 1,
5769 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005770
Robert Carr108b2c72019-04-02 16:32:58 -07005771 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5772 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005773}
5774
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005775status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5776 TraverseLayersFunction traverseLayers,
5777 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005778 bool useIdentityTransform,
5779 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005780 // This mutex protects syncFd and captureResult for communication of the return values from the
5781 // main thread back to this Binder thread
5782 std::mutex captureMutex;
5783 std::condition_variable captureCondition;
5784 std::unique_lock<std::mutex> captureLock(captureMutex);
5785 int syncFd = -1;
5786 std::optional<status_t> captureResult;
5787
Robert Carr03480e22018-01-04 16:02:06 -08005788 const int uid = IPCThreadState::self()->getCallingUid();
5789 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5790
Dominik Laskowski8c001672018-05-30 16:52:06 -07005791 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005792 // If there is a refresh pending, bug out early and tell the binder thread to try again
5793 // after the refresh.
5794 if (mRefreshPending) {
5795 ATRACE_NAME("Skipping screenshot for now");
5796 std::unique_lock<std::mutex> captureLock(captureMutex);
5797 captureResult = std::make_optional<status_t>(EAGAIN);
5798 captureCondition.notify_one();
5799 return;
5800 }
5801
5802 status_t result = NO_ERROR;
5803 int fd = -1;
5804 {
5805 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005806 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005807 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005808 useIdentityTransform, forSystem, &fd,
5809 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005810 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005811 }
5812
5813 {
5814 std::unique_lock<std::mutex> captureLock(captureMutex);
5815 syncFd = fd;
5816 captureResult = std::make_optional<status_t>(result);
5817 captureCondition.notify_one();
5818 }
5819 });
5820
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005821 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005822 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005823 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005824 while (*captureResult == EAGAIN) {
5825 captureResult.reset();
5826 result = postMessageAsync(message);
5827 if (result != NO_ERROR) {
5828 return result;
5829 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005830 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005831 }
5832 result = *captureResult;
5833 }
5834
5835 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005836 sync_wait(syncFd, -1);
5837 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005838 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005839
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005840 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005841}
5842
chaviwa76b2712017-09-20 12:02:26 -07005843void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005844 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005845 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5846 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005847 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005848
chaviwa76b2712017-09-20 12:02:26 -07005849 const auto reqWidth = renderArea.getReqWidth();
5850 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005851 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005852 const auto transform = renderArea.getTransform();
5853 const auto sourceCrop = renderArea.getSourceCrop();
Dan Stozac1879002014-05-22 15:59:05 -07005854
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005855 renderengine::DisplaySettings clientCompositionDisplay;
5856 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005857
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005858 // assume that bounds are never offset, and that they are the same as the
5859 // buffer bounds.
5860 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005861 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005862 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005863
5864 // Now take into account the rotation flag. We append a transform that
5865 // rotates the layer stack about the origin, then translate by buffer
5866 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005867 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005868 int displacementX = 0;
5869 int displacementY = 0;
5870 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5871 switch (rotation) {
5872 case ui::Transform::ROT_90:
5873 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005874 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005875 break;
5876 case ui::Transform::ROT_180:
5877 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005878 displacementY = renderArea.getBounds().getWidth();
5879 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005880 break;
5881 case ui::Transform::ROT_270:
5882 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005883 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005884 break;
5885 default:
5886 break;
5887 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005888
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005889 // We need to transform the clipping window into the right spot.
5890 // First, rotate the clipping rectangle by the rotation hint to get the
5891 // right orientation
5892 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5893 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5894 const vec4 rotClipTL = rotMatrix * clipTL;
5895 const vec4 rotClipBR = rotMatrix * clipBR;
5896 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5897 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5898 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5899 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5900
5901 // Now reposition the clipping rectangle with the displacement vector
5902 // computed above.
5903 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005904 clientCompositionDisplay.clip =
5905 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5906 newClipRight + displacementX, newClipBottom + displacementY);
5907
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005908 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005909 clientCompositionDisplay.globalTransform =
5910 clipTransform * clientCompositionDisplay.globalTransform;
5911
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005912 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5913 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005914
chaviw50da5042018-04-09 13:49:37 -07005915 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005916
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005917 renderengine::LayerSettings fillLayer;
5918 fillLayer.source.buffer.buffer = nullptr;
5919 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5920 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5921 fillLayer.alpha = half(alpha);
5922 clientCompositionLayers.push_back(fillLayer);
5923
5924 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005925 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005926 renderengine::LayerSettings layerSettings;
5927 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005928 false, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005929 if (prepared) {
5930 clientCompositionLayers.push_back(layerSettings);
5931 }
chaviwa76b2712017-09-20 12:02:26 -07005932 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005933
5934 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005935 // Use an empty fence for the buffer fence, since we just created the buffer so
5936 // there is no need for synchronization with the GPU.
5937 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005938 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005939 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005940 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005941 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005942
5943 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005944}
5945
chaviwa76b2712017-09-20 12:02:26 -07005946status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5947 TraverseLayersFunction traverseLayers,
5948 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005949 bool useIdentityTransform, bool forSystem,
5950 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005951 ATRACE_CALL();
5952
chaviwa76b2712017-09-20 12:02:26 -07005953 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005954 outCapturedSecureLayers =
5955 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005956 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005957
Robert Carr03480e22018-01-04 16:02:06 -08005958 // We allow the system server to take screenshots of secure layers for
5959 // use in situations like the Screen-rotation animation and place
5960 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005961 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005962 ALOGW("FB is protected: PERMISSION_DENIED");
5963 return PERMISSION_DENIED;
5964 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005965 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005966 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005967}
5968
chaviw95ef3c42019-02-14 10:55:09 -08005969void SurfaceFlinger::setInputWindowsFinished() {
5970 Mutex::Autolock _l(mStateLock);
5971
5972 mPendingSyncInputWindows = false;
5973 mTransactionCV.broadcast();
5974}
chaviw5f21a5e2019-02-14 10:00:34 -08005975
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005976// ---------------------------------------------------------------------------
5977
Dan Stoza412903f2017-04-27 13:42:17 -07005978void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5979 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005980}
5981
Dan Stoza412903f2017-04-27 13:42:17 -07005982void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5983 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005984}
5985
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005986void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005987 const LayerVector::Visitor& visitor) {
5988 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005989 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005990 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005991 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005992 continue;
5993 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005994 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005995 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005996 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005997 return;
5998 }
chaviwa76b2712017-09-20 12:02:26 -07005999 if (!layer->isVisible()) {
6000 return;
6001 }
6002 visitor(layer);
6003 });
6004 }
6005}
6006
Dominik Laskowski22488f62019-03-28 09:53:04 -07006007void SurfaceFlinger::setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
6008 const std::vector<int32_t>& allowedConfigs) {
6009 if (!display->isPrimary()) {
Ady Abraham838de062019-02-04 10:24:03 -08006010 return;
6011 }
6012
6013 ALOGV("Updating allowed configs");
Dominik Laskowski22488f62019-03-28 09:53:04 -07006014 mAllowedDisplayConfigs = DisplayConfigs(allowedConfigs.begin(), allowedConfigs.end());
Ady Abraham838de062019-02-04 10:24:03 -08006015
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006016 // Set the highest allowed config by iterating backwards on available refresh rates
Dominik Laskowski22488f62019-03-28 09:53:04 -07006017 const auto& refreshRates = mRefreshRateConfigs.getRefreshRates();
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006018 for (auto iter = refreshRates.crbegin(); iter != refreshRates.crend(); ++iter) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07006019 if (iter->second && isDisplayConfigAllowed(iter->second->configId)) {
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006020 ALOGV("switching to config %d", iter->second->configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -07006021 setDesiredActiveConfig(
6022 {iter->first, iter->second->configId, Scheduler::ConfigEvent::Changed});
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006023 break;
Ady Abraham97d04232019-03-05 19:48:12 -08006024 }
6025 }
Ady Abraham838de062019-02-04 10:24:03 -08006026}
6027
Dominik Laskowski22488f62019-03-28 09:53:04 -07006028status_t SurfaceFlinger::setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abraham838de062019-02-04 10:24:03 -08006029 const std::vector<int32_t>& allowedConfigs) {
6030 ATRACE_CALL();
6031
Dominik Laskowski22488f62019-03-28 09:53:04 -07006032 if (!displayToken || allowedConfigs.empty()) {
Ady Abraham838de062019-02-04 10:24:03 -08006033 return BAD_VALUE;
6034 }
6035
Ady Abraham34392f72019-04-10 11:29:27 -07006036 if (mDebugDisplayConfigSetByBackdoor) {
6037 // ignore this request as config is overridden by backdoor
6038 return NO_ERROR;
6039 }
6040
Ady Abraham838de062019-02-04 10:24:03 -08006041 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski22488f62019-03-28 09:53:04 -07006042 const auto display = getDisplayDeviceLocked(displayToken);
6043 if (!display) {
6044 ALOGE("Attempt to set allowed display configs for invalid display token %p",
6045 displayToken.get());
6046 } else if (display->isVirtual()) {
6047 ALOGW("Attempt to set allowed display configs for virtual display");
6048 } else {
6049 setAllowedDisplayConfigsInternal(display, allowedConfigs);
6050 }
Ady Abraham838de062019-02-04 10:24:03 -08006051 }));
Dominik Laskowski22488f62019-03-28 09:53:04 -07006052
Ady Abraham838de062019-02-04 10:24:03 -08006053 return NO_ERROR;
6054}
6055
Dominik Laskowski22488f62019-03-28 09:53:04 -07006056status_t SurfaceFlinger::getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006057 std::vector<int32_t>* outAllowedConfigs) {
6058 ATRACE_CALL();
6059
Dominik Laskowski22488f62019-03-28 09:53:04 -07006060 if (!displayToken || !outAllowedConfigs) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006061 return BAD_VALUE;
6062 }
6063
Dominik Laskowski22488f62019-03-28 09:53:04 -07006064 Mutex::Autolock lock(mStateLock);
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006065
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006066 const auto display = getDisplayDeviceLocked(displayToken);
6067 if (!display) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006068 return NAME_NOT_FOUND;
6069 }
6070
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006071 if (display->isPrimary()) {
6072 outAllowedConfigs->assign(mAllowedDisplayConfigs.begin(), mAllowedDisplayConfigs.end());
6073 }
6074
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006075 return NO_ERROR;
6076}
6077
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006078void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006079 mFlinger->setInputWindowsFinished();
6080}
6081
Robert Carrc0df3122019-04-11 13:18:21 -07006082sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6083 BBinder *b = handle->localBinder();
6084 if (b == nullptr) {
6085 return nullptr;
6086 }
6087 auto it = mLayersByLocalBinderToken.find(b);
6088 if (it != mLayersByLocalBinderToken.end()) {
6089 return it->second.promote();
6090 }
6091 return nullptr;
6092}
6093
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006094} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006095
Mathias Agopian3f844832013-08-07 21:24:32 -07006096#if defined(__gl_h_)
6097#error "don't include gl/gl.h in this file"
6098#endif
6099
6100#if defined(__gl2_h_)
6101#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006102#endif