blob: 50fabe3c43061b252241fdc85a48d77735d47c59 [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>
Ady Abraham8532d012019-05-08 14:50:56 -0700116#include <android/hardware/power/1.0/IPower.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900117#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900118
chaviw1d044282017-09-27 12:19:28 -0700119#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900120#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700121
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800122namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700123
Jaesoo Lee43518572017-01-23 19:03:16 +0900124using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900125using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900126using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800127
Ady Abraham8532d012019-05-08 14:50:56 -0700128using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800129using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700130using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700131using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800132using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700133using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700134using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900135
Steven Thomasb02664d2017-07-26 18:48:28 -0700136namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700137
138#pragma clang diagnostic push
139#pragma clang diagnostic error "-Wswitch-enum"
140
141bool isWideColorMode(const ColorMode colorMode) {
142 switch (colorMode) {
143 case ColorMode::DISPLAY_P3:
144 case ColorMode::ADOBE_RGB:
145 case ColorMode::DCI_P3:
146 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700147 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700148 case ColorMode::BT2100_PQ:
149 case ColorMode::BT2100_HLG:
150 return true;
151 case ColorMode::NATIVE:
152 case ColorMode::STANDARD_BT601_625:
153 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
154 case ColorMode::STANDARD_BT601_525:
155 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
156 case ColorMode::STANDARD_BT709:
157 case ColorMode::SRGB:
158 return false;
159 }
160 return false;
161}
162
Peiyong Lin34ea5b92019-03-15 18:40:15 -0700163bool isHdrColorMode(const ColorMode colorMode) {
164 switch (colorMode) {
165 case ColorMode::BT2100_PQ:
166 case ColorMode::BT2100_HLG:
167 return true;
168 case ColorMode::DISPLAY_P3:
169 case ColorMode::ADOBE_RGB:
170 case ColorMode::DCI_P3:
171 case ColorMode::BT2020:
172 case ColorMode::DISPLAY_BT2020:
173 case ColorMode::NATIVE:
174 case ColorMode::STANDARD_BT601_625:
175 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
176 case ColorMode::STANDARD_BT601_525:
177 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
178 case ColorMode::STANDARD_BT709:
179 case ColorMode::SRGB:
180 return false;
181 }
182 return false;
183}
184
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700185ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
186 switch (rotation) {
187 case ISurfaceComposer::eRotateNone:
188 return ui::Transform::ROT_0;
189 case ISurfaceComposer::eRotate90:
190 return ui::Transform::ROT_90;
191 case ISurfaceComposer::eRotate180:
192 return ui::Transform::ROT_180;
193 case ISurfaceComposer::eRotate270:
194 return ui::Transform::ROT_270;
195 }
196 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
197 return ui::Transform::ROT_0;
198}
199
Peiyong Linfca547f2018-07-09 13:03:33 -0700200#pragma clang diagnostic pop
201
Steven Thomasb02664d2017-07-26 18:48:28 -0700202class ConditionalLock {
203public:
204 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
205 if (lock) {
206 mMutex.lock();
207 }
208 }
209 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
210private:
211 Mutex& mMutex;
212 bool mLocked;
213};
Peiyong Linfca547f2018-07-09 13:03:33 -0700214
Peiyong Lin9d846a52018-11-05 13:18:20 -0800215// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
216bool validateCompositionDataspace(Dataspace dataspace) {
217 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
218}
219
Steven Thomasb02664d2017-07-26 18:48:28 -0700220} // namespace anonymous
221
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800222// ---------------------------------------------------------------------------
223
Mathias Agopian99b49842011-06-27 16:05:52 -0700224const String16 sHardwareTest("android.permission.HARDWARE_TEST");
225const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
226const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
227const String16 sDump("android.permission.DUMP");
228
229// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700230int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700231bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800232uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800233bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800234bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800235int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600236bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700237int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700238bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700239bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700240Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
241ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
242Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
243ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700244
Kalle Raitaa099a242017-01-11 11:17:29 -0800245std::string getHwcServiceName() {
246 char value[PROPERTY_VALUE_MAX] = {};
247 property_get("debug.sf.hwc_service_name", value, "default");
248 ALOGI("Using HWComposer service: '%s'", value);
249 return std::string(value);
250}
251
252bool useTrebleTestingOverride() {
253 char value[PROPERTY_VALUE_MAX] = {};
254 property_get("debug.sf.treble_testing_override", value, "false");
255 ALOGI("Treble testing override: '%s'", value);
256 return std::string(value) == "true";
257}
258
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800259std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
260 switch(displayColorSetting) {
261 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700262 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800263 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700264 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800265 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700266 return std::string("Enhanced");
267 default:
268 return std::string("Unknown ") +
269 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800270 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800271}
272
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700273SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800274
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700275SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
276 : mFactory(factory),
277 mPhaseOffsets(mFactory.createPhaseOffsets()),
278 mInterceptor(mFactory.createSurfaceInterceptor(this)),
279 mTimeStats(mFactory.createTimeStats()),
280 mEventQueue(mFactory.createMessageQueue()),
281 mCompositionEngine(mFactory.createCompositionEngine()) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800282
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700283SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800284 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800285
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900286 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800287
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900288 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700289
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900290 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700291
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900292 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800293
Steven Thomas050b2c82017-03-06 11:45:16 -0800294 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900295 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800296
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900297 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800298
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900299 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700300
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900301 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600302
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900303 mDefaultCompositionDataspace =
304 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
305 mWideColorGamutCompositionDataspace =
306 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
307 defaultCompositionDataspace = mDefaultCompositionDataspace;
308 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
309 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
310 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
311 wideColorGamutCompositionPixelFormat =
312 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700313
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900314 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800315
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900316 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
317 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
318 switch (tmpPrimaryDisplayOrientation) {
319 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700320 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800321 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900322 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700323 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800324 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900325 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700326 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800327 break;
328 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700329 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800330 break;
331 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700332 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800333
Sundong Ahn85131bd2019-02-18 15:51:53 +0900334 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800335
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800336 // debugging stuff...
337 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700338
Mathias Agopianb4b17302013-03-20 18:36:41 -0700339 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700340 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700341
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800342 property_get("debug.sf.showupdates", value, "0");
343 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700344
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700345 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000346
347 // DDMS debugging deprecated (b/120782499)
348 property_get("debug.sf.ddms", value, "0");
349 int debugDdms = atoi(value);
350 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700351
352 property_get("debug.sf.disable_backpressure", value, "0");
353 mPropagateBackpressure = !atoi(value);
354 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700355
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800356 property_get("debug.sf.enable_hwc_vds", value, "0");
357 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800358 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800359
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800360 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800361 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800362 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700363
Yiwei Zhang243b3782018-05-15 17:40:04 -0700364 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700365 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
366 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
367
Ana Krulece5a06e02019-03-06 17:09:03 -0800368 mUseSmart90ForVideo = use_smart_90_for_video(false);
Ana Krulecba13ab32019-02-20 14:14:12 -0800369 property_get("debug.sf.use_smart_90_for_video", value, "0");
Ana Krulece5a06e02019-03-06 17:09:03 -0800370
371 int int_value = atoi(value);
372 if (int_value) {
373 mUseSmart90ForVideo = true;
374 }
Ana Krulecba13ab32019-02-20 14:14:12 -0800375
Dan Stozaec460082018-12-17 15:35:09 -0800376 property_get("debug.sf.luma_sampling", value, "1");
377 mLumaSampling = atoi(value);
378
Ana Krulec757f63a2019-01-25 10:46:18 -0800379 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
380 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700381
Romain Guy11d63f42017-07-20 12:47:14 -0700382 // We should be reading 'persist.sys.sf.color_saturation' here
383 // but since /data may be encrypted, we need to wait until after vold
384 // comes online to attempt to read the property. The property is
385 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800386
387 if (useTrebleTestingOverride()) {
388 // Without the override SurfaceFlinger cannot connect to HIDL
389 // services that are not listed in the manifests. Considered
390 // deriving the setting from the set service name, but it
391 // would be brittle if the name that's not 'default' is used
392 // for production purposes later on.
393 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
394 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800395}
396
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800397void SurfaceFlinger::onFirstRef()
398{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800399 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800400}
401
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700402SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800403
Dan Stozac7014012014-02-14 15:03:43 -0800404void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800405{
406 // the window manager died on us. prepare its eulogy.
407
Andy McFadden13a082e2012-08-24 10:16:42 -0700408 // restore initial conditions (default device unblank, etc)
409 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800410
411 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700412 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800413}
414
Robert Carr1db73f62016-12-21 12:58:51 -0800415static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700416 status_t err = client->initCheck();
417 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800418 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800419 }
Robert Carr1db73f62016-12-21 12:58:51 -0800420 return nullptr;
421}
422
423sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
424 return initClient(new Client(this));
425}
426
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700427sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
428 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700429{
430 class DisplayToken : public BBinder {
431 sp<SurfaceFlinger> flinger;
432 virtual ~DisplayToken() {
433 // no more references, this display must be terminated
434 Mutex::Autolock _l(flinger->mStateLock);
435 flinger->mCurrentState.displays.removeItem(this);
436 flinger->setTransactionFlags(eDisplayTransactionNeeded);
437 }
438 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700439 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700440 : flinger(flinger) {
441 }
442 };
443
444 sp<BBinder> token = new DisplayToken(this);
445
446 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700447 // Display ID is assigned when virtual display is allocated by HWC.
448 DisplayDeviceState state;
449 state.isSecure = secure;
450 state.displayName = displayName;
451 mCurrentState.displays.add(token, state);
452 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700453 return token;
454}
455
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700456void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700457 Mutex::Autolock _l(mStateLock);
458
Dominik Laskowski075d3172018-05-24 15:50:06 -0700459 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
460 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700461 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700462 return;
463 }
464
Dominik Laskowski075d3172018-05-24 15:50:06 -0700465 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
466 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700467 ALOGE("destroyDisplay called for non-virtual display");
468 return;
469 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700470 mInterceptor->saveDisplayDeletion(state.sequenceId);
471 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700472 setTransactionFlags(eDisplayTransactionNeeded);
473}
474
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800475std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
476 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700477
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800478 const auto internalDisplayId = getInternalDisplayIdLocked();
479 if (!internalDisplayId) {
480 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700481 }
482
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800483 std::vector<PhysicalDisplayId> displayIds;
484 displayIds.reserve(mPhysicalDisplayTokens.size());
485 displayIds.push_back(internalDisplayId->value);
486
487 for (const auto& [id, token] : mPhysicalDisplayTokens) {
488 if (id != *internalDisplayId) {
489 displayIds.push_back(id.value);
490 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700491 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700492
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800493 return displayIds;
494}
495
496sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
497 Mutex::Autolock lock(mStateLock);
498 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700499}
500
Ady Abraham37965d42018-11-01 13:43:32 -0700501status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
502 if (!outGetColorManagement) {
503 return BAD_VALUE;
504 }
505 *outGetColorManagement = useColorManagement;
506 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700507}
508
Lloyd Pique441d5042018-10-18 16:49:51 -0700509HWComposer& SurfaceFlinger::getHwComposer() const {
510 return mCompositionEngine->getHwComposer();
511}
512
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700513renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
514 return mCompositionEngine->getRenderEngine();
515}
516
Lloyd Pique70d91362018-10-18 16:02:55 -0700517compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
518 return *mCompositionEngine.get();
519}
520
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800521void SurfaceFlinger::bootFinished()
522{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700523 if (mStartPropertySetThread->join() != NO_ERROR) {
524 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800525 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800526 const nsecs_t now = systemTime();
527 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000528 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700529
530 // wait patiently for the window manager death
531 const String16 name("window");
532 sp<IBinder> window(defaultServiceManager()->getService(name));
533 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700534 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700535 }
Robert Carr720e5062018-07-30 17:45:14 -0700536 sp<IBinder> input(defaultServiceManager()->getService(
537 String16("inputflinger")));
538 if (input == nullptr) {
539 ALOGE("Failed to link to input service");
540 } else {
541 mInputFlinger = interface_cast<IInputFlinger>(input);
542 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700543
Steven Thomas050b2c82017-03-06 11:45:16 -0800544 if (mVrFlinger) {
545 mVrFlinger->OnBootFinished();
546 }
547
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700548 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700549 // formerly we would just kill the process, but we now ask it to exit so it
550 // can choose where to stop the animation.
551 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700552
553 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
554 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
555 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700556
Ana Krulecbd6654b2019-02-15 15:18:15 -0800557 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800558 readPersistentProperties();
559 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800560
Ady Abraham97d04232019-03-05 19:48:12 -0800561 // set the refresh rate according to the policy
Alec Mouri0a1cc962019-03-14 12:33:02 -0700562 const auto& performanceRefreshRate =
Dominik Laskowski22488f62019-03-28 09:53:04 -0700563 mRefreshRateConfigs.getRefreshRate(RefreshRateType::PERFORMANCE);
Ady Abraham97d04232019-03-05 19:48:12 -0800564
Dominik Laskowski22488f62019-03-28 09:53:04 -0700565 if (performanceRefreshRate && isDisplayConfigAllowed(performanceRefreshRate->configId)) {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800566 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800567 } else {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800568 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800569 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800570 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800571}
572
Dan Stoza436ccf32018-06-21 12:10:12 -0700573uint32_t SurfaceFlinger::getNewTexture() {
574 {
575 std::lock_guard lock(mTexturePoolMutex);
576 if (!mTexturePool.empty()) {
577 uint32_t name = mTexturePool.back();
578 mTexturePool.pop_back();
579 ATRACE_INT("TexturePoolSize", mTexturePool.size());
580 return name;
581 }
582
583 // The pool was too small, so increase it for the future
584 ++mTexturePoolSize;
585 }
586
587 // The pool was empty, so we need to get a new texture name directly using a
588 // blocking call to the main thread
589 uint32_t name = 0;
590 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
591 return name;
592}
593
Mathias Agopian3f844832013-08-07 21:24:32 -0700594void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700595 std::lock_guard lock(mTexturePoolMutex);
596 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
597 // to actually delete this or not based on mTexturePoolSize
598 mTexturePool.push_back(texture);
599 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700600}
601
Wei Wangf9b05ee2017-07-19 20:59:39 -0700602// Do not call property_set on main thread which will be blocked by init
603// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700604void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700605 ALOGI( "SurfaceFlinger's main thread ready to run. "
606 "Initializing graphics H/W...");
607
Ana Krulec757f63a2019-01-25 10:46:18 -0800608 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900609
Steven Thomasb02664d2017-07-26 18:48:28 -0700610 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700611 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800612 mScheduler =
Ady Abraham09bd3922019-04-08 10:44:56 -0700613 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
614 mRefreshRateConfigs);
Ana Krulecc2870422019-01-29 19:00:58 -0800615 auto resyncCallback =
616 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800617
Ana Krulecc2870422019-01-29 19:00:58 -0800618 mAppConnectionHandle =
619 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
620 resyncCallback,
621 impl::EventThread::InterceptVSyncsCallback());
622 mSfConnectionHandle = mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
623 resyncCallback, [this](nsecs_t timestamp) {
624 mInterceptor->saveVSyncEvent(timestamp);
625 });
626
627 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
628 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
629 mSfConnectionHandle.get());
630
Kevin DuBois413287f2019-02-25 08:46:47 -0800631 mRegionSamplingThread =
632 new RegionSamplingThread(*this, *mScheduler,
633 RegionSamplingThread::EnvironmentTimingTunables());
634
Steven Thomasb02664d2017-07-26 18:48:28 -0700635 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700636 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700637 renderEngineFeature |= (useColorManagement ?
638 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700639 renderEngineFeature |= (useContextPriority ?
640 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin6a043d52019-04-01 17:18:21 -0700641 renderEngineFeature |=
642 (enable_protected_contents(false) ? renderengine::RenderEngine::ENABLE_PROTECTED_CONTEXT
643 : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700644
645 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800646 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700647 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700648 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800649 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700650
651 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
652 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700653 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
654 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800655 // Process any initial hotplug and resulting display changes.
656 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700657 const auto display = getDefaultDisplayDeviceLocked();
658 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700659 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700660 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800661
Steven Thomas050b2c82017-03-06 11:45:16 -0800662 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700663 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700664 // This callback is called from the vr flinger dispatch thread. We
665 // need to call signalTransaction(), which requires holding
666 // mStateLock when we're not on the main thread. Acquiring
667 // mStateLock from the vr flinger dispatch thread might trigger a
668 // deadlock in surface flinger (see b/66916578), so post a message
669 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700670 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700671 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
672 mVrFlingerRequestsDisplay = requestDisplay;
673 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700674 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800675 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700676 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
677 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700678 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700679 .value_or(0),
680 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800681 if (!mVrFlinger) {
682 ALOGE("Failed to start vrflinger");
683 }
684 }
685
Mathias Agopian92a979a2012-08-02 18:32:23 -0700686 // initialize our drawing state
687 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700688
Andy McFadden13a082e2012-08-24 10:16:42 -0700689 // set initial conditions (e.g. unblank default device)
690 initializeDisplays();
691
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700692 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700693
Wei Wangf9b05ee2017-07-19 20:59:39 -0700694 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700695
696 const bool presentFenceReliable =
697 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
698 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700699
700 if (mStartPropertySetThread->Start() != NO_ERROR) {
701 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800702 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800703
Alec Mouri93bc83d2019-04-17 14:47:43 -0700704 mScheduler->setChangeRefreshRateCallback(
705 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
706 Mutex::Autolock lock(mStateLock);
707 setRefreshRateTo(type, event);
708 });
Alec Mouridc28b372019-04-18 21:17:13 -0700709 mScheduler->setGetVsyncPeriodCallback([this] {
710 Mutex::Autolock lock(mStateLock);
711 return getVsyncPeriod();
712 });
Ady Abraham09bd3922019-04-08 10:44:56 -0700713
Dominik Laskowski22488f62019-03-28 09:53:04 -0700714 mRefreshRateConfigs.populate(getHwComposer().getConfigs(*display->getId()));
715 mRefreshRateStats.setConfigMode(getHwComposer().getActiveConfigIndex(*display->getId()));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800716
Dan Stoza9e56aa02015-11-02 13:00:03 -0800717 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700718}
719
Romain Guy11d63f42017-07-20 12:47:14 -0700720void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700721 Mutex::Autolock _l(mStateLock);
722
Romain Guy11d63f42017-07-20 12:47:14 -0700723 char value[PROPERTY_VALUE_MAX];
724
725 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800726 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700727 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800728 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100729
730 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700731 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800732
733 property_get("persist.sys.sf.color_mode", value, "0");
734 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700735}
736
Mathias Agopiana67e4182012-06-19 17:26:12 -0700737void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800738 // Start boot animation service by setting a property mailbox
739 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700740 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800741 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700742 if (mStartPropertySetThread->join() != NO_ERROR) {
743 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800744 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700745}
746
Mathias Agopian875d8e12013-06-07 15:35:48 -0700747size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700748 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700749}
750
Mathias Agopian875d8e12013-06-07 15:35:48 -0700751size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700752 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700753}
754
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800755// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800756
Jamie Gennis582270d2011-08-17 18:19:00 -0700757bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800758 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800759 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800760 return authenticateSurfaceTextureLocked(bufferProducer);
761}
762
763bool SurfaceFlinger::authenticateSurfaceTextureLocked(
764 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800765 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800766 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800767}
768
Brian Anderson6b376712017-04-04 10:51:39 -0700769status_t SurfaceFlinger::getSupportedFrameTimestamps(
770 std::vector<FrameEvent>* outSupported) const {
771 *outSupported = {
772 FrameEvent::REQUESTED_PRESENT,
773 FrameEvent::ACQUIRE,
774 FrameEvent::LATCH,
775 FrameEvent::FIRST_REFRESH_START,
776 FrameEvent::LAST_REFRESH_START,
777 FrameEvent::GPU_COMPOSITION_DONE,
778 FrameEvent::DEQUEUE_READY,
779 FrameEvent::RELEASE,
780 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700781 ConditionalLock _l(mStateLock,
782 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700783 if (!getHwComposer().hasCapability(
784 HWC2::Capability::PresentFenceIsNotReliable)) {
785 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
786 }
787 return NO_ERROR;
788}
789
Dominik Laskowski22488f62019-03-28 09:53:04 -0700790status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
791 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700792 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700793 return BAD_VALUE;
794 }
795
Dominik Laskowski22488f62019-03-28 09:53:04 -0700796 Mutex::Autolock lock(mStateLock);
797
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800798 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700799 if (!displayId) {
800 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700801 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700802
Mathias Agopian8b736f12012-08-13 17:54:26 -0700803 // TODO: Not sure if display density should handled by SF any longer
804 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700805 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700806 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700807 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800808 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700809 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700810 }
811 return density;
812 }
813 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700814 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700815 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700816 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700817 return getDensityFromProperty("ro.sf.lcd_density"); }
818 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700819
Dan Stoza7f7da322014-05-02 15:26:25 -0700820 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700821
Dominik Laskowski075d3172018-05-24 15:50:06 -0700822 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700823 DisplayInfo info = DisplayInfo();
824
Dan Stoza9e56aa02015-11-02 13:00:03 -0800825 float xdpi = hwConfig->getDpiX();
826 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700827
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700828 info.w = hwConfig->getWidth();
829 info.h = hwConfig->getHeight();
830 // Default display viewport to display width and height
831 info.viewportW = info.w;
832 info.viewportH = info.h;
833
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800834 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700835 // The density of the device is provided by a build property
836 float density = Density::getBuildDensity() / 160.0f;
837 if (density == 0) {
838 // the build doesn't provide a density -- this is wrong!
839 // use xdpi instead
840 ALOGE("ro.sf.lcd_density must be defined as a build property");
841 density = xdpi / 160.0f;
842 }
843 if (Density::getEmuDensity()) {
844 // if "qemu.sf.lcd_density" is specified, it overrides everything
845 xdpi = ydpi = density = Density::getEmuDensity();
846 density /= 160.0f;
847 }
848 info.density = density;
849
850 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700851 const auto display = getDefaultDisplayDeviceLocked();
852 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700853
854 // This is for screenrecord
855 const Rect viewport = display->getViewport();
856 if (viewport.isValid()) {
857 info.viewportW = uint32_t(viewport.getWidth());
858 info.viewportH = uint32_t(viewport.getHeight());
859 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700860 } else {
861 // TODO: where should this value come from?
862 static const int TV_DENSITY = 213;
863 info.density = TV_DENSITY / 160.0f;
864 info.orientation = 0;
865 }
866
Dan Stoza7f7da322014-05-02 15:26:25 -0700867 info.xdpi = xdpi;
868 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800869 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ady Abraham796beb02019-04-11 15:23:07 -0700870 const auto refreshRateType = mRefreshRateConfigs.getRefreshRateType(hwConfig->getId());
871 const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
872 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800873
Andy McFadden91b2ca82014-06-13 14:04:23 -0700874 // This is how far in advance a buffer must be queued for
875 // presentation at a given time. If you want a buffer to appear
876 // on the screen at time N, you must submit the buffer before
877 // (N - presentationDeadline).
878 //
879 // Normally it's one full refresh period (to give SF a chance to
880 // latch the buffer), but this can be reduced by configuring a
881 // DispSync offset. Any additional delays introduced by the hardware
882 // composer or panel must be accounted for here.
883 //
884 // We add an additional 1ms to allow for processing time and
885 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700886 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700887
888 // All non-virtual displays are currently considered secure.
889 info.secure = true;
890
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800891 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700892 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800893 std::swap(info.w, info.h);
894 }
895
Michael Wright28f24d02016-07-12 13:30:53 -0700896 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700897 }
898
Dan Stoza7f7da322014-05-02 15:26:25 -0700899 return NO_ERROR;
900}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700901
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700902status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
903 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700904 return BAD_VALUE;
905 }
906
Ana Krulecc2870422019-01-29 19:00:58 -0800907 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700908 return NO_ERROR;
909}
910
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700911int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
912 const auto display = getDisplayDevice(displayToken);
913 if (!display) {
914 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800915 return BAD_VALUE;
916 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700917
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700918 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700919}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700920
Ady Abraham03b02dd2019-03-21 15:40:11 -0700921void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800922 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800923
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800924 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800925 // config twice. However event generation config might have changed so we need to update it
926 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800927 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700928 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
929 mDesiredActiveConfig = info;
930 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800931
932 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800933 // This will trigger HWC refresh without resetting the idle timer.
934 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700935 // Start receiving vsync samples now, so that we can detect a period
936 // switch.
937 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700938 // As we called to set period, we will call to onRefreshRateChangeCompleted once
939 // DispSync model is locked.
940 mVsyncModulator.onRefreshRateChangeInitiated();
Alec Mouri754c98a2019-03-18 18:53:42 -0700941 mPhaseOffsets->setRefreshRateType(info.type);
942 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Alec Mouri754c98a2019-03-18 18:53:42 -0700943 mVsyncModulator.setPhaseOffsets(early, gl, late);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800944 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800945 mDesiredActiveConfigChanged = true;
946 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700947
948 if (mRefreshRateOverlay) {
949 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
950 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800951}
952
953status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
954 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800955
956 std::vector<int32_t> allowedConfig;
957 allowedConfig.push_back(mode);
958
959 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800960}
961
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800962void SurfaceFlinger::setActiveConfigInternal() {
963 ATRACE_CALL();
964
Dominik Laskowski22488f62019-03-28 09:53:04 -0700965 const auto display = getDefaultDisplayDeviceLocked();
966 if (!display) {
967 return;
968 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800969
Dominik Laskowski22488f62019-03-28 09:53:04 -0700970 std::lock_guard<std::mutex> lock(mActiveConfigLock);
971 mRefreshRateStats.setConfigMode(mUpcomingActiveConfig.configId);
972
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800973 display->setActiveConfig(mUpcomingActiveConfig.configId);
974
Alec Mouri754c98a2019-03-18 18:53:42 -0700975 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Alec Mouri1c9e82b2019-03-07 12:24:05 -0800976 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
977 mVsyncModulator.setPhaseOffsets(early, gl, late);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800978 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700979
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800980 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -0800981 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
982 mUpcomingActiveConfig.configId);
983 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800984}
985
Ady Abraham53852a52019-05-28 18:07:44 -0700986void SurfaceFlinger::desiredActiveConfigChangeDone() {
987 std::lock_guard<std::mutex> lock(mActiveConfigLock);
988 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
989 mDesiredActiveConfigChanged = false;
990 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
991
992 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
993 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
994 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
995 mVsyncModulator.setPhaseOffsets(early, gl, late);
996}
997
Dominik Laskowski22488f62019-03-28 09:53:04 -0700998bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -0800999 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001000 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001001 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001002 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001003 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001004 return true;
1005 }
1006
1007 // We received the present fence from the HWC, so we assume it successfully updated
1008 // the config, hence we update SF.
1009 mCheckPendingFence = false;
1010 setActiveConfigInternal();
1011 }
1012
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001013 // Store the local variable to release the lock.
1014 ActiveConfigInfo desiredActiveConfig;
1015 {
1016 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001017 if (!mDesiredActiveConfigChanged) {
1018 return false;
1019 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001020 desiredActiveConfig = mDesiredActiveConfig;
1021 }
1022
Dominik Laskowski22488f62019-03-28 09:53:04 -07001023 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001024 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1025 // display is not valid or we are already in the requested mode
1026 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001027 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001028 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001029 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001030
Ady Abraham838de062019-02-04 10:24:03 -08001031 // Desired active config was set, it is different than the config currently in use, however
1032 // allowed configs might have change by the time we process the refresh.
1033 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001034 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001035 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001036 return false;
1037 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001038 mUpcomingActiveConfig = desiredActiveConfig;
1039 const auto displayId = display->getId();
1040 LOG_ALWAYS_FATAL_IF(!displayId);
1041
1042 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1043 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1044
1045 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -08001046 mCheckPendingFence = true;
Ady Abraham8532d012019-05-08 14:50:56 -07001047 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001048 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001049}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001050
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001051status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1052 Vector<ColorMode>* outColorModes) {
1053 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001054 return BAD_VALUE;
1055 }
1056
Peiyong Lina52f0292018-03-14 17:26:31 -07001057 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001058 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001059 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001060 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1061
1062 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1063 if (!displayId) {
1064 return NAME_NOT_FOUND;
1065 }
1066
Dominik Laskowski075d3172018-05-24 15:50:06 -07001067 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001068 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001069 }
Michael Wright28f24d02016-07-12 13:30:53 -07001070 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001071
1072 // If it's built-in display and the configuration claims it's not wide color capable,
1073 // filter out all wide color modes. The typical reason why this happens is that the
1074 // hardware is not good enough to support GPU composition of wide color, and thus the
1075 // OEMs choose to disable this capability.
1076 if (isInternalDisplay && !hasWideColorDisplay) {
1077 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1078 isWideColorMode);
1079 } else {
1080 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1081 }
Michael Wright28f24d02016-07-12 13:30:53 -07001082
1083 return NO_ERROR;
1084}
1085
Daniel Solomon42d04562019-01-20 21:03:19 -08001086status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1087 ui::DisplayPrimaries &primaries) {
1088 if (!displayToken) {
1089 return BAD_VALUE;
1090 }
1091
1092 // Currently we only support this API for a single internal display.
1093 if (getInternalDisplayToken() != displayToken) {
1094 return BAD_VALUE;
1095 }
1096
1097 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1098 return NO_ERROR;
1099}
1100
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001101ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1102 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001103 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001104 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001105 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001106}
1107
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001108status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001109 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001110 Vector<ColorMode> modes;
1111 getDisplayColorModes(displayToken, &modes);
1112 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1113 if (mode < ColorMode::NATIVE || !exists) {
1114 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1115 decodeColorMode(mode).c_str(), mode, displayToken.get());
1116 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001117 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001118 const auto display = getDisplayDevice(displayToken);
1119 if (!display) {
1120 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1121 decodeColorMode(mode).c_str(), mode, displayToken.get());
1122 } else if (display->isVirtual()) {
1123 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1124 decodeColorMode(mode).c_str(), mode);
1125 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001126 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1127 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001128 }
1129 }));
1130
Michael Wright28f24d02016-07-12 13:30:53 -07001131 return NO_ERROR;
1132}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001133
Svetoslavd85084b2014-03-20 10:28:31 -07001134status_t SurfaceFlinger::clearAnimationFrameStats() {
1135 Mutex::Autolock _l(mStateLock);
1136 mAnimFrameTracker.clearStats();
1137 return NO_ERROR;
1138}
1139
1140status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1141 Mutex::Autolock _l(mStateLock);
1142 mAnimFrameTracker.getStats(outStats);
1143 return NO_ERROR;
1144}
1145
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001146status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1147 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001148 Mutex::Autolock _l(mStateLock);
1149
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001150 const auto display = getDisplayDeviceLocked(displayToken);
1151 if (!display) {
1152 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001153 return BAD_VALUE;
1154 }
1155
Peiyong Linfb069302018-04-25 14:34:31 -07001156 // At this point the DisplayDeivce should already be set up,
1157 // meaning the luminance information is already queried from
1158 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001159 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001160 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1161 capabilities.getDesiredMaxLuminance(),
1162 capabilities.getDesiredMaxAverageLuminance(),
1163 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001164
1165 return NO_ERROR;
1166}
1167
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001168status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1169 ui::PixelFormat* outFormat,
1170 ui::Dataspace* outDataspace,
1171 uint8_t* outComponentMask) const {
1172 if (!outFormat || !outDataspace || !outComponentMask) {
1173 return BAD_VALUE;
1174 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001175 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001176 if (!display || !display->getId()) {
1177 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1178 return BAD_VALUE;
1179 }
1180 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1181 outDataspace, outComponentMask);
1182}
1183
Kevin DuBois74e53772018-11-19 10:52:38 -08001184status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1185 bool enable, uint8_t componentMask,
1186 uint64_t maxFrames) const {
1187 const auto display = getDisplayDevice(displayToken);
1188 if (!display || !display->getId()) {
1189 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1190 return BAD_VALUE;
1191 }
1192
1193 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1194 componentMask, maxFrames);
1195}
1196
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001197status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1198 uint64_t maxFrames, uint64_t timestamp,
1199 DisplayedFrameStats* outStats) const {
1200 const auto display = getDisplayDevice(displayToken);
1201 if (!display || !display->getId()) {
1202 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1203 return BAD_VALUE;
1204 }
1205
1206 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1207 outStats);
1208}
1209
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001210status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1211 if (!outSupported) {
1212 return BAD_VALUE;
1213 }
1214 *outSupported = getRenderEngine().supportsProtectedContent();
1215 return NO_ERROR;
1216}
1217
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001218status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1219 bool* outIsWideColorDisplay) const {
1220 if (!displayToken || !outIsWideColorDisplay) {
1221 return BAD_VALUE;
1222 }
1223 Mutex::Autolock _l(mStateLock);
1224 const auto display = getDisplayDeviceLocked(displayToken);
1225 if (!display) {
1226 return BAD_VALUE;
1227 }
Peiyong Linff84a152019-05-17 18:36:19 -07001228
1229 // Use hasWideColorDisplay to override built-in display.
1230 const auto displayId = display->getId();
1231 if (displayId && displayId == getInternalDisplayIdLocked()) {
1232 *outIsWideColorDisplay = hasWideColorDisplay;
1233 return NO_ERROR;
1234 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001235 *outIsWideColorDisplay = display->hasWideColorGamut();
1236 return NO_ERROR;
1237}
1238
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001239status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001240 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001241 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001242
Chia-I Wu90f669f2017-10-05 14:24:41 -07001243 if (mInjectVSyncs == enable) {
1244 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001245 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001246
Ana Krulecc2870422019-01-29 19:00:58 -08001247 auto resyncCallback =
1248 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001249
Ady Abraham46e2f3e2019-03-18 16:40:15 -07001250 // TODO(b/128863962): Part of the Injector should be refactored, so that it
Ana Krulec98b5b242018-08-10 15:03:23 -07001251 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001252 if (enable) {
1253 ALOGV("VSync Injections enabled");
1254 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001255 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001256 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001257 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001258 impl::EventThread::InterceptVSyncsCallback(),
1259 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001260 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001261 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001262 } else {
1263 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001264 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1265 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001266 }
1267
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001268 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001269 }));
1270
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001271 return NO_ERROR;
1272}
1273
1274status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001275 Mutex::Autolock _l(mStateLock);
1276
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001277 if (!mInjectVSyncs) {
1278 ALOGE("VSync Injections not enabled");
1279 return BAD_VALUE;
1280 }
1281 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1282 ALOGV("Injecting VSync inside SurfaceFlinger");
1283 mVSyncInjector->onInjectSyncEvent(when);
1284 }
1285 return NO_ERROR;
1286}
1287
Lloyd Pique755e3192018-01-31 16:46:15 -08001288status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1289 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001290 // Try to acquire a lock for 1s, fail gracefully
1291 const status_t err = mStateLock.timedLock(s2ns(1));
1292 const bool locked = (err == NO_ERROR);
1293 if (!locked) {
1294 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1295 return TIMED_OUT;
1296 }
1297
1298 outLayers->clear();
1299 mCurrentState.traverseInZOrder([&](Layer* layer) {
1300 outLayers->push_back(layer->getLayerDebugInfo());
1301 });
1302
1303 mStateLock.unlock();
1304 return NO_ERROR;
1305}
1306
Peiyong Linc6780972018-10-28 15:24:08 -07001307status_t SurfaceFlinger::getCompositionPreference(
1308 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1309 Dataspace* outWideColorGamutDataspace,
1310 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001311 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001312 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001313 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001314 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001315 return NO_ERROR;
1316}
1317
Dan Stozaec460082018-12-17 15:35:09 -08001318status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1319 const sp<IBinder>& stopLayerHandle,
1320 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001321 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001322 return BAD_VALUE;
1323 }
1324 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001325 return NO_ERROR;
1326}
1327
Dan Stozaec460082018-12-17 15:35:09 -08001328status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001329 if (!listener) {
1330 return BAD_VALUE;
1331 }
Dan Stozaec460082018-12-17 15:35:09 -08001332 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001333 return NO_ERROR;
1334}
Dan Gittik57e63c52019-01-18 16:37:54 +00001335
1336status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1337 bool* outSupport) const {
1338 if (!displayToken || !outSupport) {
1339 return BAD_VALUE;
1340 }
1341 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1342 if (!displayId) {
1343 return NAME_NOT_FOUND;
1344 }
1345 *outSupport =
1346 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1347 return NO_ERROR;
1348}
1349
1350status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1351 float brightness) const {
1352 if (!displayToken) {
1353 return BAD_VALUE;
1354 }
1355 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1356 if (!displayId) {
1357 return NAME_NOT_FOUND;
1358 }
1359 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1360}
1361
Ady Abraham8532d012019-05-08 14:50:56 -07001362status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1363 PowerHint powerHint = static_cast<PowerHint>(hintId);
1364
1365 if (powerHint == PowerHint::INTERACTION) {
1366 mScheduler->notifyTouchEvent();
1367 }
1368
1369 return NO_ERROR;
1370}
1371
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001372// ----------------------------------------------------------------------------
1373
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001374sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1375 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulecc2870422019-01-29 19:00:58 -08001376 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001377 Mutex::Autolock lock(mStateLock);
1378 return getVsyncPeriod();
1379 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001380
Ana Krulecc2870422019-01-29 19:00:58 -08001381 const auto& handle =
1382 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001383
Ana Krulecc2870422019-01-29 19:00:58 -08001384 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Mathias Agopianbb641242010-05-18 17:06:55 -07001385}
1386
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001387// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001388
1389void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001390 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001391}
1392
1393void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001394 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001395 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001396}
1397
1398void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001399 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001400 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001401}
1402
1403void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001404 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001405 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001406}
1407
1408status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001409 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001410 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001411}
1412
1413status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001414 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001415 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001416 if (res == NO_ERROR) {
1417 msg->wait();
1418 }
1419 return res;
1420}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001421
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001422void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001423 do {
1424 waitForEvent();
1425 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001426}
1427
Dominik Laskowski83b88212018-12-11 13:34:06 -08001428nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001429 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001430 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1431 return 0;
1432 }
1433
1434 const auto config = getHwComposer().getActiveConfig(*displayId);
1435 return config ? config->getVsyncPeriod() : 0;
1436}
1437
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001438void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1439 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001440 ATRACE_NAME("SF onVsync");
1441
Steven Thomas3cfac282017-02-06 12:29:30 -08001442 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001443 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001444 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001445 return;
1446 }
1447
Dominik Laskowski075d3172018-05-24 15:50:06 -07001448 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001449 return;
1450 }
1451
Dominik Laskowski075d3172018-05-24 15:50:06 -07001452 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001453 // For now, we don't do anything with external display vsyncs.
1454 return;
1455 }
1456
Alec Mourif8e689c2019-05-20 18:32:22 -07001457 bool periodFlushed = false;
1458 mScheduler->addResyncSample(timestamp, &periodFlushed);
1459 if (periodFlushed) {
1460 mVsyncModulator.onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001461 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001462}
1463
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001464void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001465 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1466 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001467}
1468
Dominik Laskowski22488f62019-03-28 09:53:04 -07001469bool SurfaceFlinger::isDisplayConfigAllowed(int32_t configId) {
1470 return mAllowedDisplayConfigs.empty() || mAllowedDisplayConfigs.count(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001471}
1472
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001473void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001474 const auto display = getDefaultDisplayDeviceLocked();
1475 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001476 return;
1477 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001478 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001479
Ana Krulec7d1d6832018-12-27 11:10:09 -08001480 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowski22488f62019-03-28 09:53:04 -07001481 const auto& refreshRateConfig = mRefreshRateConfigs.getRefreshRate(refreshRate);
Alec Mouri0a1cc962019-03-14 12:33:02 -07001482 if (!refreshRateConfig) {
1483 ALOGV("Skipping refresh rate change request for unsupported rate.");
Ady Abraham1902d072019-03-01 17:18:59 -08001484 return;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001485 }
Ady Abraham1902d072019-03-01 17:18:59 -08001486
Alec Mouri0a1cc962019-03-14 12:33:02 -07001487 const int desiredConfigId = refreshRateConfig->configId;
1488
Dominik Laskowski22488f62019-03-28 09:53:04 -07001489 if (!isDisplayConfigAllowed(desiredConfigId)) {
Ady Abraham1902d072019-03-01 17:18:59 -08001490 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1491 return;
1492 }
1493
Dominik Laskowski22488f62019-03-28 09:53:04 -07001494 setDesiredActiveConfig({refreshRate, desiredConfigId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001495}
1496
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001497void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001498 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001499 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001500 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001501
Lloyd Piqueba04e622017-12-14 17:11:26 -08001502 // Ignore events that do not have the right sequenceId.
1503 if (sequenceId != getBE().mComposerSequenceId) {
1504 return;
1505 }
1506
Steven Thomasb02664d2017-07-26 18:48:28 -07001507 // Only lock if we're not on the main thread. This function is normally
1508 // called on a hwbinder thread, but for the primary display it's called on
1509 // the main thread with the state lock already held, so don't attempt to
1510 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001511 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001512
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001513 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001514
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001515 if (std::this_thread::get_id() == mMainThreadId) {
1516 // Process all pending hot plug events immediately if we are on the main thread.
1517 processDisplayHotplugEventsLocked();
1518 }
1519
Lloyd Piqueba04e622017-12-14 17:11:26 -08001520 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001521}
1522
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001523void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001524 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001525 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001526 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001527 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001528 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001529}
1530
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001531void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001532 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001533 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001534 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001535 getHwComposer().setVsyncEnabled(*displayId,
1536 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1537 }
Mathias Agopian86303202012-07-24 22:46:10 -07001538}
1539
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001540// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001541void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001542 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001543 // Clear the drawing state so that the logic inside of
1544 // handleTransactionLocked will fire. It will determine the delta between
1545 // mCurrentState and mDrawingState and re-apply all changes when we make the
1546 // transition.
1547 mDrawingState.displays.clear();
1548 mDisplays.clear();
1549}
1550
Steven Thomas050b2c82017-03-06 11:45:16 -08001551void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001552 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001553 if (!mVrFlinger)
1554 return;
1555 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001556 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001557 return;
1558 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001559
Lloyd Pique441d5042018-10-18 16:49:51 -07001560 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001561 ALOGE("Vr flinger is only supported for remote hardware composer"
1562 " service connections. Ignoring request to transition to vr"
1563 " flinger.");
1564 mVrFlingerRequestsDisplay = false;
1565 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001566 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001567
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001568 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001569
Steven Thomas0123ac62018-07-12 11:32:34 -07001570 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001571 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001572
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001573 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001574
1575 // Clear out all the output layers from the composition engine for all
1576 // displays before destroying the hardware composer interface. This ensures
1577 // any HWC layers are destroyed through that interface before it becomes
1578 // invalid.
1579 for (const auto& [token, displayDevice] : mDisplays) {
1580 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1581 compositionengine::Output::OutputLayers());
1582 }
1583
Steven Thomas0123ac62018-07-12 11:32:34 -07001584 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1585 // called below. Clear the reference now so we don't accidentally use it
1586 // later.
1587 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001588
Steven Thomasb02664d2017-07-26 18:48:28 -07001589 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001590 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001591 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001592
Steven Thomasb02664d2017-07-26 18:48:28 -07001593 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001594 // Delete the current instance before creating the new one
1595 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1596 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1597 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1598 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001599
Lloyd Pique441d5042018-10-18 16:49:51 -07001600 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001601 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001602
1603 if (vrFlingerRequestsDisplay) {
1604 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001605 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001606
1607 mVisibleRegionsDirty = true;
1608 invalidateHwcGeometry();
1609
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001610 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001611 display = getDefaultDisplayDeviceLocked();
1612 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001613 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001614
Steven Thomasb02664d2017-07-26 18:48:28 -07001615 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001616 const nsecs_t vsyncPeriod = getVsyncPeriod();
1617 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001618
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001619 // The present fences returned from vr_hwc are not an accurate
1620 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001621 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001622
Steven Thomasb02664d2017-07-26 18:48:28 -07001623 // Use phase of 0 since phase is not known.
1624 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001625 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001626 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001627
Ana Krulecc2870422019-01-29 19:00:58 -08001628 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001629
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001630 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001631 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001632}
1633
Ady Abrahambe0f9482019-04-24 15:41:53 -07001634bool SurfaceFlinger::previousFrameMissed() NO_THREAD_SAFETY_ANALYSIS {
1635 // We are storing the last 2 present fences. If sf's phase offset is to be
1636 // woken up before the actual vsync but targeting the next vsync, we need to check
1637 // fence N-2
1638 const sp<Fence>& fence =
1639 mVsyncModulator.getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
1640 ? mPreviousPresentFences[0]
1641 : mPreviousPresentFences[1];
1642
1643 return fence != Fence::NO_FENCE && (fence->getStatus() == Fence::Status::Unsignaled);
1644}
1645
Dominik Laskowski22488f62019-03-28 09:53:04 -07001646void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001647 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001648 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001649 case MessageQueue::INVALIDATE: {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001650 bool frameMissed = previousFrameMissed();
Alec Mouricc0fc602019-02-26 21:45:19 -08001651 bool hwcFrameMissed = mHadDeviceComposition && frameMissed;
1652 bool gpuFrameMissed = mHadClientComposition && frameMissed;
1653 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
1654 ATRACE_INT("HwcFrameMissed", static_cast<int>(hwcFrameMissed));
1655 ATRACE_INT("GpuFrameMissed", static_cast<int>(gpuFrameMissed));
1656 if (frameMissed) {
1657 mFrameMissedCount++;
1658 mTimeStats->incrementMissedFrames();
1659 }
1660
Alec Mouri40189b02019-03-05 15:07:54 -08001661 if (hwcFrameMissed) {
1662 mHwcFrameMissedCount++;
1663 }
1664
1665 if (gpuFrameMissed) {
1666 mGpuFrameMissedCount++;
1667 }
1668
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001669 if (mUseSmart90ForVideo) {
1670 // This call is made each time SF wakes up and creates a new frame. It is part
1671 // of video detection feature.
Ady Abraham09bd3922019-04-08 10:44:56 -07001672 mScheduler->updateFpsBasedOnContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001673 }
1674
Ady Abrahamb838aed2019-02-12 15:30:16 -08001675 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001676 break;
1677 }
1678
Alec Mourife3dc942019-02-12 14:19:18 -08001679 // For now, only propagate backpressure when missing a hwc frame.
Alec Mourib0f45822019-05-06 11:01:35 -07001680 if (hwcFrameMissed && !gpuFrameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001681 if (mPropagateBackpressure) {
1682 signalLayerUpdate();
1683 break;
1684 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001685 }
Dan Stoza50182882016-07-08 12:02:20 -07001686
Steven Thomas050b2c82017-03-06 11:45:16 -08001687 // Now that we're going to make it to the handleMessageTransaction()
1688 // call below it's safe to call updateVrFlinger(), which will
1689 // potentially trigger a display handoff.
1690 updateVrFlinger();
1691
Dan Stoza6b9454d2014-11-07 16:00:59 -08001692 bool refreshNeeded = handleMessageTransaction();
1693 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001694
1695 updateCursorAsync();
1696 updateInputFlinger();
1697
Dan Stoza58784442014-12-02 16:58:17 -08001698 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001699 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001700 // Signal a refresh if a transaction modified the window state,
1701 // a new buffer was latched, or if HWC has requested a full
1702 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001703 signalRefresh();
1704 }
1705 break;
1706 }
1707 case MessageQueue::REFRESH: {
1708 handleMessageRefresh();
1709 break;
1710 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001711 }
1712}
1713
Dan Stoza6b9454d2014-11-07 16:00:59 -08001714bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001715 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001716 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001717
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001718 bool flushedATransaction = flushTransactionQueues();
1719
1720 bool runHandleTransaction = transactionFlags &&
1721 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1722
1723 if (runHandleTransaction) {
1724 handleTransaction(eTransactionMask);
1725 } else {
1726 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001727 }
1728
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001729 if (transactionFlushNeeded()) {
1730 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001731 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001732
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001733 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001734}
1735
Mathias Agopian4fec8732012-06-29 14:12:52 -07001736void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001737 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001738
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001739 mRefreshPending = false;
1740
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001741 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001742 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001743 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001744 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001745 for (const auto& [token, display] : mDisplays) {
1746 beginFrame(display);
1747 prepareFrame(display);
1748 doDebugFlashRegions(display, repaintEverything);
1749 doComposition(display, repaintEverything);
1750 }
1751
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001752 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001753
1754 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001755 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001756
Dan Stozabfbffeb2016-07-21 14:49:33 -07001757 mHadClientComposition = false;
Alec Mouricc0fc602019-02-26 21:45:19 -08001758 mHadDeviceComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001759 for (const auto& [token, displayDevice] : mDisplays) {
1760 auto display = displayDevice->getCompositionDisplay();
1761 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001762 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001763 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Alec Mouricc0fc602019-02-26 21:45:19 -08001764 mHadDeviceComposition =
1765 mHadDeviceComposition || getHwComposer().hasDeviceComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001766 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001767
Jorim Jaggi90535212018-05-23 23:44:06 +02001768 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001769
David Sodman7e4ae112018-02-09 15:02:28 -08001770 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001771}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001772
David Sodmanfa9b2af2017-12-24 13:28:59 -08001773
1774bool SurfaceFlinger::handleMessageInvalidate() {
1775 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001776 bool refreshNeeded = handlePageFlip();
1777
Vishnu Nair4351ad52019-02-11 14:13:02 -08001778 if (mVisibleRegionsDirty) {
1779 computeLayerBounds();
Nataniel Borges2b796da2019-02-15 13:32:18 -08001780 if (mTracingEnabled) {
1781 mTracing.notify("visibleRegionsDirty");
1782 }
Vishnu Nair4351ad52019-02-11 14:13:02 -08001783 }
1784
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001785 for (auto& layer : mLayersPendingRefresh) {
1786 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001787 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001788 invalidateLayerStack(layer, visibleReg);
1789 }
1790 mLayersPendingRefresh.clear();
1791 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001792}
1793
David Sodman79bba0e2018-08-05 18:07:49 -07001794void SurfaceFlinger::calculateWorkingSet() {
1795 ATRACE_CALL();
1796 ALOGV(__FUNCTION__);
1797
David Sodman79bba0e2018-08-05 18:07:49 -07001798 // build the h/w work list
1799 if (CC_UNLIKELY(mGeometryInvalid)) {
1800 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001801 for (const auto& [token, displayDevice] : mDisplays) {
1802 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001803
Lloyd Piquea83776c2019-01-29 18:42:32 -08001804 uint32_t zOrder = 0;
David Sodman79bba0e2018-08-05 18:07:49 -07001805
Lloyd Piquea83776c2019-01-29 18:42:32 -08001806 for (auto& layer : display->getOutputLayersOrderedByZ()) {
1807 auto& compositionState = layer->editState();
1808 compositionState.forceClientComposition = false;
1809 if (!compositionState.hwc || mDebugDisableHWC || mDebugRegion) {
1810 compositionState.forceClientComposition = true;
David Sodman79bba0e2018-08-05 18:07:49 -07001811 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001812
Lloyd Piquea83776c2019-01-29 18:42:32 -08001813 // The output Z order is set here based on a simple counter.
1814 compositionState.z = zOrder++;
1815
1816 // Update the display independent composition state. This goes
1817 // to the general composition layer state structure.
1818 // TODO: Do this once per compositionengine::CompositionLayer.
1819 layer->getLayerFE().latchCompositionState(layer->getLayer().editState().frontEnd,
1820 true);
1821
1822 // Recalculate the geometry state of the output layer.
1823 layer->updateCompositionState(true);
1824
1825 // Write the updated geometry state to the HWC
1826 layer->writeStateToHWC(true);
David Sodman79bba0e2018-08-05 18:07:49 -07001827 }
1828 }
1829 }
1830
1831 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001832 for (const auto& [token, displayDevice] : mDisplays) {
1833 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001834 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001835 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001836 continue;
1837 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001838 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001839
1840 if (mDrawingState.colorMatrixChanged) {
1841 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001842 }
Peiyong Linc502cb72019-03-01 15:00:23 -08001843 Dataspace targetDataspace = Dataspace::UNKNOWN;
1844 if (useColorManagement) {
1845 ColorMode colorMode;
1846 RenderIntent renderIntent;
1847 pickColorMode(displayDevice, &colorMode, &targetDataspace, &renderIntent);
1848 display->setColorMode(colorMode, targetDataspace, renderIntent);
1849 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001850 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001851 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001852 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001853 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1854 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001855 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001856 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001857 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1858 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001859 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001860 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001861 }
1862
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001863 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001864 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001865 }
1866
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001867 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001868 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001869 layer->setCompositionType(displayDevice,
1870 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001871 continue;
1872 }
1873
Lloyd Pique32cbe282018-10-19 13:09:22 -07001874 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001875 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Peiyong Lin34ea5b92019-03-15 18:40:15 -07001876 displayDevice->getSupportedPerFrameMetadata(),
1877 isHdrColorMode(displayState.colorMode) ? Dataspace::UNKNOWN
1878 : targetDataspace);
David Sodman79bba0e2018-08-05 18:07:49 -07001879 }
1880 }
1881
1882 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001883
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001884 for (const auto& [token, displayDevice] : mDisplays) {
1885 auto display = displayDevice->getCompositionDisplay();
1886 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Lloyd Pique0b785d82018-12-04 17:25:27 -08001887 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1888 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1889 layer->getCompositionType(displayDevice));
David Sodmanba340492018-08-05 21:51:33 -07001890 }
1891 }
David Sodman79bba0e2018-08-05 18:07:49 -07001892}
1893
Lloyd Pique32cbe282018-10-19 13:09:22 -07001894void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1895 bool repaintEverything) {
1896 auto display = displayDevice->getCompositionDisplay();
1897 const auto& displayState = display->getState();
1898
Mathias Agopiancd60f992012-08-16 16:28:27 -07001899 // is debugging enabled
1900 if (CC_LIKELY(!mDebugRegion))
1901 return;
1902
Lloyd Pique32cbe282018-10-19 13:09:22 -07001903 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001904 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001905 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001906 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001907 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001908 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001909 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001910
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001911 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001912 }
1913 }
1914
Lloyd Pique32cbe282018-10-19 13:09:22 -07001915 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001916
1917 if (mDebugRegion > 1) {
1918 usleep(mDebugRegion * 1000);
1919 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001920
Lloyd Pique32cbe282018-10-19 13:09:22 -07001921 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001922}
1923
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001924void SurfaceFlinger::logLayerStats() {
1925 ATRACE_CALL();
1926 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001927 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001928 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001929 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001930 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001931 }
1932 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001933
1934 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001935 }
1936}
1937
David Sodman2b406362017-12-15 13:33:47 -08001938void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001939{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001940 ATRACE_CALL();
1941 ALOGV("preComposition");
1942
David Sodman2b406362017-12-15 13:33:47 -08001943 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1944
Mathias Agopiancd60f992012-08-16 16:28:27 -07001945 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001946 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001947 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001948 needExtraInvalidate = true;
1949 }
Robert Carr2047fae2016-11-28 14:09:09 -08001950 });
1951
Mathias Agopiancd60f992012-08-16 16:28:27 -07001952 if (needExtraInvalidate) {
1953 signalLayerUpdate();
1954 }
1955}
1956
Ana Krulece588e312018-09-18 12:32:24 -07001957void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1958 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001959 // Update queue of past composite+present times and determine the
1960 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001961 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001962 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001963 while (!getBE().mCompositePresentTimes.empty()) {
1964 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001965 // Cached values should have been updated before calling this method,
1966 // which helps avoid duplicate syscalls.
1967 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1968 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1969 break;
1970 }
1971 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001972 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001973 }
1974
1975 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001976 while (getBE().mCompositePresentTimes.size() > 16) {
1977 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001978 }
1979
Ana Krulece588e312018-09-18 12:32:24 -07001980 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001981}
1982
Ana Krulece588e312018-09-18 12:32:24 -07001983void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1984 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001985 // Integer division and modulo round toward 0 not -inf, so we need to
1986 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001987 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1988 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1989 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001990
Ana Krulec757f63a2019-01-25 10:46:18 -08001991 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001992 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001993 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001994 }
1995
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001996 // Snap the latency to a value that removes scheduling jitter from the
1997 // composition and present times, which often have >1ms of jitter.
1998 // Reducing jitter is important if an app attempts to extrapolate
1999 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08002000 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002001 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002002 nsecs_t bias = stats.vsyncPeriod / 2;
2003 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2004 nsecs_t snappedCompositeToPresentLatency =
2005 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002006
David Sodman99974d22017-11-28 12:04:33 -08002007 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002008 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2009 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002010 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002011}
2012
David Sodman2b406362017-12-15 13:33:47 -08002013void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002014{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002015 ATRACE_CALL();
2016 ALOGV("postComposition");
2017
Brian Anderson3546a3f2016-07-14 11:51:14 -07002018 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002019 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002020 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002021 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002022 }
2023
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002024 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002025 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002026
David Sodman73beded2017-11-15 11:56:06 -08002027 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002028 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002029 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002030 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002031 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2032 ->getRenderSurface()
2033 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002034 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002035 } else {
2036 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2037 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002038
David Sodman73beded2017-11-15 11:56:06 -08002039 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002040 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2041 mPreviousPresentFences[0] = displayDevice
2042 ? getHwComposer().getPresentFence(*displayDevice->getId())
2043 : Fence::NO_FENCE;
2044 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002045 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002046
Ana Krulece588e312018-09-18 12:32:24 -07002047 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002048 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002049
David Sodman2b406362017-12-15 13:33:47 -08002050 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002051 // when we started doing work for this frame, but that should be okay
2052 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002053 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002054 CompositorTiming compositorTiming;
2055 {
David Sodman99974d22017-11-28 12:04:33 -08002056 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2057 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002058 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002059
Robert Carr2047fae2016-11-28 14:09:09 -08002060 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002061 bool frameLatched =
2062 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2063 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002064 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002065 recordBufferingStats(layer->getName().string(),
2066 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002067 }
Robert Carr2047fae2016-11-28 14:09:09 -08002068 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002069
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002070 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002071 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002072 }
2073
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002074 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002075 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2076 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002077 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002078 }
2079 }
2080
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002081 if (mAnimCompositionPending) {
2082 mAnimCompositionPending = false;
2083
Brian Anderson4e606e32017-03-16 15:34:57 -07002084 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002085 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002086 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002087 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002088 // The HWC doesn't support present fences, so use the refresh
2089 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002090 const nsecs_t presentTime =
2091 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002092 mAnimFrameTracker.setActualPresentTime(presentTime);
2093 }
2094 mAnimFrameTracker.advanceFrame();
2095 }
Dan Stozab90cf072015-03-05 11:05:59 -08002096
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002097 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002098 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002099 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002100 }
2101
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002102 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002103
Lloyd Pique32cbe282018-10-19 13:09:22 -07002104 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2105 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002106 return;
2107 }
2108
2109 nsecs_t currentTime = systemTime();
2110 if (mHasPoweredOff) {
2111 mHasPoweredOff = false;
2112 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002113 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002114 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002115 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2116 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002117 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002118 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002119 }
David Sodman4a36e932017-11-07 14:29:47 -08002120 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002121 }
David Sodman4a36e932017-11-07 14:29:47 -08002122 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002123
2124 {
2125 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002126 if (mTexturePool.size() < mTexturePoolSize) {
2127 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002128 const size_t offset = mTexturePool.size();
2129 mTexturePool.resize(mTexturePoolSize);
2130 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2131 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002132 } else if (mTexturePool.size() > mTexturePoolSize) {
2133 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2134 const size_t offset = mTexturePoolSize;
2135 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2136 mTexturePool.resize(mTexturePoolSize);
2137 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002138 }
2139 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002140
Ady Abrahambe0f9482019-04-24 15:41:53 -07002141 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Walle2ffb422018-10-12 11:33:52 -07002142 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002143
Kevin DuBois413287f2019-02-25 08:46:47 -08002144 if (mLumaSampling && mRegionSamplingThread) {
2145 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002146 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002147
2148 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2149 // side-effect of getTotalSize(), so we check that again here
2150 if (ATRACE_ENABLED()) {
2151 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2152 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002153}
2154
Vishnu Nair4351ad52019-02-11 14:13:02 -08002155void SurfaceFlinger::computeLayerBounds() {
2156 for (const auto& pair : mDisplays) {
2157 const auto& displayDevice = pair.second;
2158 const auto display = displayDevice->getCompositionDisplay();
2159 for (const auto& layer : mDrawingState.layersSortedByZ) {
2160 // only consider the layers on the given layer stack
2161 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002162 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002163 }
2164
2165 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2166 }
2167 }
2168}
2169
Mathias Agopiancd60f992012-08-16 16:28:27 -07002170void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002171 ATRACE_CALL();
2172 ALOGV("rebuildLayerStacks");
2173
Mathias Agopiancd60f992012-08-16 16:28:27 -07002174 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002175 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002176 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002177 mVisibleRegionsDirty = false;
2178 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002179
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002180 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002181 const auto& displayDevice = pair.second;
2182 auto display = displayDevice->getCompositionDisplay();
2183 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002184 Region opaqueRegion;
2185 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002186 compositionengine::Output::OutputLayers layersSortedByZ;
2187 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002188 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002189 const ui::Transform& tr = displayState.transform;
2190 const Rect bounds = displayState.bounds;
2191 if (displayState.isEnabled) {
2192 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002193
Jeff Sharkey76488112017-02-27 14:15:18 -07002194 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002195 auto compositionLayer = layer->getCompositionLayer();
2196 if (compositionLayer == nullptr) {
2197 return;
2198 }
2199
Lloyd Pique32cbe282018-10-19 13:09:22 -07002200 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002201 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2202 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2203
Lloyd Pique07e33212018-12-18 16:33:37 -08002204 bool needsOutputLayer = false;
2205
Lloyd Piqueef36b002019-01-23 17:52:04 -08002206 if (display->belongsInOutput(layer->getLayerStack(),
2207 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002208 Region drawRegion(tr.transform(
2209 layer->visibleNonTransparentRegion));
2210 drawRegion.andSelf(bounds);
2211 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002212 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002213 }
Chia-I Wu83806892017-11-16 10:50:20 -08002214 }
2215
Lloyd Pique07e33212018-12-18 16:33:37 -08002216 if (needsOutputLayer) {
2217 layersSortedByZ.emplace_back(
2218 display->getOrCreateOutputLayer(displayId, compositionLayer,
2219 layerFE));
2220 deprecated_layersSortedByZ.add(layer);
2221
2222 auto& outputLayerState = layersSortedByZ.back()->editState();
2223 outputLayerState.visibleRegion =
2224 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2225 } else if (displayId) {
2226 // For layers that are being removed from a HWC display,
2227 // and that have queued frames, add them to a a list of
2228 // released layers so we can properly set a fence.
2229 bool hasExistingOutputLayer =
2230 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2231 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2232 mLayersWithQueuedFrames.cend(),
2233 layer) != mLayersWithQueuedFrames.cend();
2234
2235 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002236 layersNeedingFences.add(layer);
2237 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002238 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002239 });
2240 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002241
2242 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2243
2244 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002245 displayDevice->setLayersNeedingFences(layersNeedingFences);
2246
2247 Region undefinedRegion{bounds};
2248 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2249
2250 display->editState().undefinedRegion = undefinedRegion;
2251 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002252 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002253 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002254}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002255
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002256// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002257// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002258// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002259// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002260// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002261// The returned HDR data space is one of
2262// - Dataspace::UNKNOWN
2263// - Dataspace::BT2020_HLG
2264// - Dataspace::BT2020_PQ
Peiyong Lin03912882019-04-16 15:34:46 -07002265Dataspace SurfaceFlinger::getBestDataspace(const sp<DisplayDevice>& display,
2266 Dataspace* outHdrDataSpace,
2267 bool* outIsHdrClientComposition) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002268 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002269 *outHdrDataSpace = Dataspace::UNKNOWN;
2270
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002271 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002272 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002273 case Dataspace::V0_SCRGB:
2274 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002275 case Dataspace::BT2020:
2276 case Dataspace::BT2020_ITU:
2277 case Dataspace::BT2020_LINEAR:
2278 case Dataspace::DISPLAY_BT2020:
2279 bestDataSpace = Dataspace::DISPLAY_BT2020;
2280 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002281 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002282 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002283 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002284 case Dataspace::BT2020_PQ:
2285 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002286 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002287 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lin03912882019-04-16 15:34:46 -07002288 *outIsHdrClientComposition = layer->getForceClientComposition(display);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002289 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002290 case Dataspace::BT2020_HLG:
2291 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002292 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002293 // When there's mixed PQ content and HLG content, we set the HDR
2294 // data space to be BT2020_PQ and convert HLG to PQ.
2295 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2296 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002297 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002298 break;
2299 default:
2300 break;
2301 }
Romain Guy54f154a2017-10-24 21:40:32 +01002302 }
2303
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002304 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002305}
2306
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002307// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002308void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2309 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002310 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2311 *outMode = ColorMode::NATIVE;
2312 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002313 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002314 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002315 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002316
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002317 Dataspace hdrDataSpace;
Peiyong Lin03912882019-04-16 15:34:46 -07002318 bool isHdrClientComposition = false;
2319 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace, &isHdrClientComposition);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002320
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002321 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2322
Peiyong Lina3ea5592019-02-10 14:45:00 -08002323 switch (mForceColorMode) {
2324 case ColorMode::SRGB:
2325 bestDataSpace = Dataspace::V0_SRGB;
2326 break;
2327 case ColorMode::DISPLAY_P3:
2328 bestDataSpace = Dataspace::DISPLAY_P3;
2329 break;
2330 default:
2331 break;
2332 }
2333
Peiyong Lindfde5112018-06-05 10:58:41 -07002334 // respect hdrDataSpace only when there is no legacy HDR support
Peiyong Lin03912882019-04-16 15:34:46 -07002335 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
2336 !profile->hasLegacyHdrSupport(hdrDataSpace) && !isHdrClientComposition;
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002337 if (isHdr) {
2338 bestDataSpace = hdrDataSpace;
2339 }
2340
Chia-I Wu0d711262018-05-21 15:19:35 -07002341 RenderIntent intent;
2342 switch (mDisplayColorSetting) {
2343 case DisplayColorSetting::MANAGED:
2344 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002345 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002346 break;
2347 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002348 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002349 break;
2350 default: // vendor display color setting
2351 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2352 break;
2353 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002354
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002355 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002356}
2357
Lloyd Pique32cbe282018-10-19 13:09:22 -07002358void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2359 auto display = displayDevice->getCompositionDisplay();
2360 const auto& displayState = display->getState();
2361
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002362 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002363 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2364 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002365
David Sodmanfa9b2af2017-12-24 13:28:59 -08002366 // If nothing has changed (!dirty), don't recompose.
2367 // If something changed, but we don't currently have any visible layers,
2368 // and didn't when we last did a composition, then skip it this time.
2369 // The second rule does two things:
2370 // - When all layers are removed from a display, we'll emit one black
2371 // frame, then nothing more until we get new layers.
2372 // - When a display is created with a private layer stack, we won't
2373 // emit any black frames until a layer is added to the layer stack.
2374 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002375
Dominik Laskowski075d3172018-05-24 15:50:06 -07002376 const char flagPrefix[] = {'-', '+'};
2377 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002378 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2379 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2380 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2381 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002382
Lloyd Pique31cb2942018-10-19 17:23:03 -07002383 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002384
David Sodmanfa9b2af2017-12-24 13:28:59 -08002385 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002386 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002387 }
2388}
2389
Lloyd Pique32cbe282018-10-19 13:09:22 -07002390void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2391 auto display = displayDevice->getCompositionDisplay();
2392 const auto& displayState = display->getState();
2393
2394 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002395 return;
David Sodman2b406362017-12-15 13:33:47 -08002396 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002397
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002398 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002399 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002400 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002401}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002402
Lloyd Pique32cbe282018-10-19 13:09:22 -07002403void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002404 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002405 ALOGV("doComposition");
2406
Lloyd Pique32cbe282018-10-19 13:09:22 -07002407 auto display = displayDevice->getCompositionDisplay();
2408 const auto& displayState = display->getState();
2409
2410 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002411 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002412 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002413
David Sodmanfa9b2af2017-12-24 13:28:59 -08002414 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002415 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002416
Lloyd Pique32cbe282018-10-19 13:09:22 -07002417 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002418 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002419 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002420 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002421}
2422
David Sodmanfa9b2af2017-12-24 13:28:59 -08002423void SurfaceFlinger::postFrame()
2424{
2425 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002426 const auto display = getDefaultDisplayDeviceLocked();
2427 if (display && getHwComposer().isConnected(*display->getId())) {
2428 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002429 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2430 logFrameStats();
2431 }
2432 }
2433}
2434
Lloyd Pique32cbe282018-10-19 13:09:22 -07002435void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002436 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002437 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002438
Lloyd Pique32cbe282018-10-19 13:09:22 -07002439 auto display = displayDevice->getCompositionDisplay();
2440 const auto& displayState = display->getState();
2441 const auto displayId = display->getId();
2442
Lloyd Pique32cbe282018-10-19 13:09:22 -07002443 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002444 if (displayId) {
2445 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002446 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002447 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002448 for (auto& layer : display->getOutputLayersOrderedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002449 sp<Fence> releaseFence = Fence::NO_FENCE;
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002450 bool usedClientComposition = true;
David Sodman15094112018-10-11 09:39:37 -07002451
Chia-I Wu7b549592017-11-15 09:14:57 -08002452 // The layer buffer from the previous frame (if any) is released
2453 // by HWC only when the release fence from this frame (if any) is
2454 // signaled. Always get the release fence from HWC first.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002455 if (layer->getState().hwc) {
2456 const auto& hwcState = *layer->getState().hwc;
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002457 releaseFence =
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002458 getHwComposer().getLayerReleaseFence(*displayId, hwcState.hwcLayer.get());
2459 usedClientComposition =
2460 hwcState.hwcCompositionType == Hwc2::IComposerClient::Composition::CLIENT;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002461 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002462
2463 // If the layer was client composited in the previous frame, we
2464 // need to merge with the previous client target acquire fence.
2465 // Since we do not track that, always merge with the current
2466 // client target acquire fence when it is available, even though
2467 // this is suboptimal.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002468 if (usedClientComposition) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002469 releaseFence =
2470 Fence::merge("LayerRelease", releaseFence,
2471 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002472 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002473
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002474 layer->getLayerFE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002475 }
Chia-I Wu83806892017-11-16 10:50:20 -08002476
2477 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002478 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002479 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002480 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002481 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002482 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002483 for (auto& layer : displayDevice->getLayersNeedingFences()) {
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002484 layer->getCompositionLayer()->getLayerFE()->onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002485 }
2486 }
2487
Dominik Laskowski075d3172018-05-24 15:50:06 -07002488 if (displayId) {
2489 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002490 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002491 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002492}
2493
Mathias Agopian87baae12012-07-31 12:38:26 -07002494void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002495{
Mathias Agopian841cde52012-03-01 15:44:37 -08002496 ATRACE_CALL();
2497
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002498 // here we keep a copy of the drawing state (that is the state that's
2499 // going to be overwritten by handleTransactionLocked()) outside of
2500 // mStateLock so that the side-effects of the State assignment
2501 // don't happen with mStateLock held (which can cause deadlocks).
2502 State drawingState(mDrawingState);
2503
Mathias Agopianca4d3602011-05-19 15:38:14 -07002504 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002505 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002506
Mathias Agopianca4d3602011-05-19 15:38:14 -07002507 // Here we're guaranteed that some transaction flags are set
2508 // so we can call handleTransactionLocked() unconditionally.
2509 // We call getTransactionFlags(), which will also clear the flags,
2510 // with mStateLock held to guarantee that mCurrentState won't change
2511 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002512
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002513 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002514 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002515 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002516
Mathias Agopianca4d3602011-05-19 15:38:14 -07002517 mDebugInTransaction = 0;
2518 invalidateHwcGeometry();
2519 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002520}
2521
Lloyd Piqueba04e622017-12-14 17:11:26 -08002522void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2523 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002524 const std::optional<DisplayIdentificationInfo> info =
2525 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002526
Dominik Laskowski075d3172018-05-24 15:50:06 -07002527 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002528 continue;
2529 }
2530
Lloyd Piqueba04e622017-12-14 17:11:26 -08002531 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002532 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002533 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002534 mPhysicalDisplayTokens[info->id] = new BBinder();
2535 DisplayDeviceState state;
2536 state.displayId = info->id;
2537 state.isSecure = true; // All physical displays are currently considered secure.
2538 state.displayName = info->name;
2539 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2540 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002541 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002542 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002543 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002544
Dominik Laskowski075d3172018-05-24 15:50:06 -07002545 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2546 if (index >= 0) {
2547 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2548 mInterceptor->saveDisplayDeletion(state.sequenceId);
2549 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002550 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002551 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002552 }
2553
2554 processDisplayChangesLocked();
2555 }
2556
2557 mPendingHotplugEvents.clear();
2558}
2559
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002560void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002561 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2562 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002563}
2564
Lloyd Pique99d3da52018-01-22 17:48:03 -08002565sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002566 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002567 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002568 const sp<IGraphicBufferProducer>& producer) {
2569 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002570 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002571 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002572 creationArgs.isSecure = state.isSecure;
2573 creationArgs.displaySurface = dispSurface;
2574 creationArgs.hasWideColorGamut = false;
2575 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002576
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002577 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002578 creationArgs.isPrimary = isInternalDisplay;
2579
2580 if (useColorManagement && displayId) {
2581 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002582 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002583 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002584 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002585 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002586
Dominik Laskowski7e045462018-05-30 13:02:02 -07002587 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002588 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002589 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002590 }
tangrobin6753a022018-08-10 10:58:54 +08002591 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002592
Dominik Laskowski075d3172018-05-24 15:50:06 -07002593 if (displayId) {
2594 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002595 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002596 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002597 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002598
Lloyd Pique90c115d2018-09-18 21:39:42 -07002599 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002600 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002601 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002602
Lloyd Pique99d3da52018-01-22 17:48:03 -08002603 // Make sure that composition can never be stalled by a virtual display
2604 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002605 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002606 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002607 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2608 }
2609
Dominik Laskowski075d3172018-05-24 15:50:06 -07002610 creationArgs.displayInstallOrientation =
2611 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002612
Lloyd Pique99d3da52018-01-22 17:48:03 -08002613 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002614 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002615
Lloyd Pique90c115d2018-09-18 21:39:42 -07002616 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002617
2618 if (maxFrameBufferAcquiredBuffers >= 3) {
2619 nativeWindowSurface->preallocateBuffers();
2620 }
2621
2622 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002623 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002624 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002625 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002626 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002627 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002628 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2629 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002630 if (!state.isVirtual()) {
2631 LOG_ALWAYS_FATAL_IF(!displayId);
2632 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002633 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002634
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002635 display->setLayerStack(state.layerStack);
2636 display->setProjection(state.orientation, state.viewport, state.frame);
2637 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002638
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002639 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002640}
2641
Lloyd Pique347200f2017-12-14 17:00:15 -08002642void SurfaceFlinger::processDisplayChangesLocked() {
2643 // here we take advantage of Vector's copy-on-write semantics to
2644 // improve performance by skipping the transaction entirely when
2645 // know that the lists are identical
2646 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2647 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2648 if (!curr.isIdenticalTo(draw)) {
2649 mVisibleRegionsDirty = true;
2650 const size_t cc = curr.size();
2651 size_t dc = draw.size();
2652
2653 // find the displays that were removed
2654 // (ie: in drawing state but not in current state)
2655 // also handle displays that changed
2656 // (ie: displays that are in both lists)
2657 for (size_t i = 0; i < dc;) {
2658 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2659 if (j < 0) {
2660 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002661 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002662 // Save display ID before disconnecting.
2663 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002664 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002665
2666 if (!display->isVirtual()) {
2667 LOG_ALWAYS_FATAL_IF(!displayId);
2668 dispatchDisplayHotplugEvent(displayId->value, false);
2669 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002670 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002671
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002672 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002673 } else {
2674 // this display is in both lists. see if something changed.
2675 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002676 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002677 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2678 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2679 if (state_binder != draw_binder) {
2680 // changing the surface is like destroying and
2681 // recreating the DisplayDevice, so we just remove it
2682 // from the drawing state, so that it get re-added
2683 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002684 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002685 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002686 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002687 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002688 mDrawingState.displays.removeItemsAt(i);
2689 dc--;
2690 // at this point we must loop to the next item
2691 continue;
2692 }
2693
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002694 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002695 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002696 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002697 }
2698 if ((state.orientation != draw[i].orientation) ||
2699 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002700 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002701 }
2702 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002703 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002704 }
2705 }
2706 }
2707 ++i;
2708 }
2709
2710 // find displays that were added
2711 // (ie: in current state but not in drawing state)
2712 for (size_t i = 0; i < cc; i++) {
2713 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2714 const DisplayDeviceState& state(curr[i]);
2715
Lloyd Pique542307f2018-10-19 13:24:08 -07002716 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002717 sp<IGraphicBufferProducer> producer;
2718 sp<IGraphicBufferProducer> bqProducer;
2719 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002720 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002721
Dominik Laskowski075d3172018-05-24 15:50:06 -07002722 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002723 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002724 // Virtual displays without a surface are dormant:
2725 // they have external state (layer stack, projection,
2726 // etc.) but no internal state (i.e. a DisplayDevice).
2727 if (state.surface != nullptr) {
2728 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002729 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002730 int width = 0;
2731 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2732 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2733 int height = 0;
2734 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2735 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2736 int intFormat = 0;
2737 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2738 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002739 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002740
Dominik Laskowski075d3172018-05-24 15:50:06 -07002741 displayId =
2742 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002743 }
2744
2745 // TODO: Plumb requested format back up to consumer
2746
2747 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002748 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002749 bqProducer, bqConsumer,
2750 state.displayName);
2751
2752 dispSurface = vds;
2753 producer = vds;
2754 }
2755 } else {
2756 ALOGE_IF(state.surface != nullptr,
2757 "adding a supported display, but rendering "
2758 "surface is provided (%p), ignoring it",
2759 state.surface.get());
2760
Dominik Laskowski075d3172018-05-24 15:50:06 -07002761 displayId = state.displayId;
2762 LOG_ALWAYS_FATAL_IF(!displayId);
2763 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002764 producer = bqProducer;
2765 }
2766
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002767 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002768 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002769 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002770 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002771 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002772 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002773 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002774 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002775 }
2776 }
2777 }
2778 }
2779 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002780
2781 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002782}
2783
Mathias Agopian87baae12012-07-31 12:38:26 -07002784void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002785{
Dan Stoza7dde5992015-05-22 09:51:44 -07002786 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002787 mCurrentState.traverseInZOrder([](Layer* layer) {
2788 layer->notifyAvailableFrames();
2789 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002790
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002791 /*
2792 * Traversal of the children
2793 * (perform the transaction for each of them if needed)
2794 */
2795
Marissa Wall06255332019-03-27 13:48:27 -07002796 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002797 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002798 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002799 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002800
2801 const uint32_t flags = layer->doTransaction(0);
2802 if (flags & Layer::eVisibleRegion)
2803 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002804
2805 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002806 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002807 }
Robert Carr2047fae2016-11-28 14:09:09 -08002808 });
Marissa Wall06255332019-03-27 13:48:27 -07002809 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002810 }
2811
2812 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002813 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002814 */
2815
Mathias Agopiane57f2922012-08-09 16:29:12 -07002816 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002817 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002818 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002819 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002820
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002821 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002822 // The transform hint might have changed for some layers
2823 // (either because a display has changed, or because a layer
2824 // as changed).
2825 //
2826 // Walk through all the layers in currentLayers,
2827 // and update their transform hint.
2828 //
2829 // If a layer is visible only on a single display, then that
2830 // display is used to calculate the hint, otherwise we use the
2831 // default display.
2832 //
2833 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2834 // the hint is set before we acquire a buffer from the surface texture.
2835 //
2836 // NOTE: layer transactions have taken place already, so we use their
2837 // drawing state. However, SurfaceFlinger's own transaction has not
2838 // happened yet, so we must use the current state layer list
2839 // (soon to become the drawing state list).
2840 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002841 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002842 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002843 bool first = true;
2844 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002845 // NOTE: we rely on the fact that layers are sorted by
2846 // layerStack first (so we don't have to traverse the list
2847 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002848 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002849 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002850 currentlayerStack = layerStack;
2851 // figure out if this layerstack is mirrored
2852 // (more than one display) if so, pick the default display,
2853 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002854 hintDisplay = nullptr;
2855 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002856 if (display->getCompositionDisplay()
2857 ->belongsInOutput(layer->getLayerStack(),
2858 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002859 if (hintDisplay) {
2860 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002861 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002862 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002863 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002864 }
2865 }
2866 }
2867 }
Chet Haase91d25932013-04-11 15:24:55 -07002868
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002869 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002870 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2871 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002872
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002873 // could be null when this layer is using a layerStack
2874 // that is not visible on any display. Also can occur at
2875 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002876 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002877 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002878
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002879 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002880 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002881 if (hintDisplay) {
2882 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002883 }
Robert Carr2047fae2016-11-28 14:09:09 -08002884
2885 first = false;
2886 });
Mathias Agopian84300952012-11-21 16:02:13 -08002887 }
2888
2889
Mathias Agopian3559b072012-08-15 13:46:03 -07002890 /*
2891 * Perform our own transaction if needed
2892 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002893
2894 if (mLayersAdded) {
2895 mLayersAdded = false;
2896 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002897 mVisibleRegionsDirty = true;
2898 }
2899
2900 // some layers might have been removed, so
2901 // we need to update the regions they're exposing.
2902 if (mLayersRemoved) {
2903 mLayersRemoved = false;
2904 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002905 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002906 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002907 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002908 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002909 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002910 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002911 }
Robert Carr2047fae2016-11-28 14:09:09 -08002912 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002913 }
2914
Vishnu Nairec0ab382019-02-13 15:32:56 -08002915 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002916 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002917}
2918
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002919void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002920 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002921 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002922 return;
2923 }
2924
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002925 if (mVisibleRegionsDirty || mInputInfoChanged) {
2926 mInputInfoChanged = false;
2927 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002928 } else if (mInputWindowCommands.syncInputWindows) {
2929 // If the caller requested to sync input windows, but there are no
2930 // changes to input windows, notify immediately.
2931 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002932 }
2933
2934 executeInputWindowCommands();
2935}
2936
2937void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002938 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002939
2940 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2941 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002942 // When calculating the screen bounds we ignore the transparent region since it may
2943 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002944 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002945 }
2946 });
chaviw291d88a2019-02-14 10:33:58 -08002947
2948 mInputFlinger->setInputWindows(inputHandles,
2949 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2950 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002951}
2952
Vishnu Nairec0ab382019-02-13 15:32:56 -08002953void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002954 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002955 mPendingInputWindowCommands.clear();
2956}
2957
chaviwfbe5d9c2018-12-26 12:23:37 -08002958void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08002959 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2960 if (transferTouchFocusCommand.fromToken != nullptr &&
2961 transferTouchFocusCommand.toToken != nullptr &&
2962 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2963 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2964 transferTouchFocusCommand.toToken);
2965 }
2966 }
2967
2968 mInputWindowCommands.clear();
2969}
2970
Riley Andrews03414a12014-07-01 14:22:59 -07002971void SurfaceFlinger::updateCursorAsync()
2972{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002973 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002974 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002975 continue;
2976 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002977
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002978 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2979 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002980 }
2981 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002982}
2983
chaviw61626f22018-11-15 16:26:27 -08002984void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2985 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08002986 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08002987 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08002988 }
2989 layer->releasePendingBuffer(systemTime());
2990}
2991
Mathias Agopian4fec8732012-06-29 14:12:52 -07002992void SurfaceFlinger::commitTransaction()
2993{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002994 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002995 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002996 for (const auto& l : mLayersPendingRemoval) {
2997 recordBufferingStats(l->getName().string(),
2998 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002999
Lloyd Pique07e33212018-12-18 16:33:37 -08003000 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07003001 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003002 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003003 }
chaviw74d90ad2019-04-26 14:45:26 -07003004
3005 // If the layer has been removed and has no parent, then it will not be reachable
3006 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3007 // ensure we can copy its current to drawing state.
3008 if (!l->getParent()) {
3009 mOffscreenLayers.emplace(l.get());
3010 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003011 }
3012 mLayersPendingRemoval.clear();
3013 }
3014
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003015 // If this transaction is part of a window animation then the next frame
3016 // we composite should be considered an animation as well.
3017 mAnimCompositionPending = mAnimTransactionPending;
3018
Nataniel Borges2b796da2019-02-15 13:32:18 -08003019 withTracingLock([&]() {
3020 mDrawingState = mCurrentState;
3021 // clear the "changed" flags in current state
3022 mCurrentState.colorMatrixChanged = false;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003023
chaviw74d90ad2019-04-26 14:45:26 -07003024 mDrawingState.traverseInZOrder([&](Layer* layer) {
3025 layer->commitChildList();
3026
3027 // If the layer can be reached when traversing mDrawingState, then the layer is no
3028 // longer offscreen. Remove the layer from the offscreenLayer set.
3029 if (mOffscreenLayers.count(layer)) {
3030 mOffscreenLayers.erase(layer);
3031 }
3032 });
3033
3034 commitOffscreenLayers();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003035 });
Nataniel Borges2b796da2019-02-15 13:32:18 -08003036
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003037 mTransactionPending = false;
3038 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003039 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003040}
3041
Nataniel Borges2b796da2019-02-15 13:32:18 -08003042void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
3043 if (mTracingEnabledChanged) {
3044 mTracingEnabled = mTracing.isEnabled();
3045 mTracingEnabledChanged = false;
3046 }
3047
3048 // Synchronize with Tracing thread
3049 std::unique_lock<std::mutex> lock;
3050 if (mTracingEnabled) {
3051 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
3052 }
3053
3054 lockedOperation();
3055
3056 // Synchronize with Tracing thread
3057 if (mTracingEnabled) {
3058 lock.unlock();
3059 }
3060}
3061
chaviw74d90ad2019-04-26 14:45:26 -07003062void SurfaceFlinger::commitOffscreenLayers() {
3063 for (Layer* offscreenLayer : mOffscreenLayers) {
3064 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
3065 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3066 if (!trFlags) return;
3067
3068 layer->doTransaction(0);
3069 layer->commitChildList();
3070 });
3071 }
3072}
3073
Lloyd Pique32cbe282018-10-19 13:09:22 -07003074void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003075 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003076 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003077 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003078
Lloyd Pique32cbe282018-10-19 13:09:22 -07003079 auto display = displayDevice->getCompositionDisplay();
3080
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003081 Region aboveOpaqueLayers;
3082 Region aboveCoveredLayers;
3083 Region dirty;
3084
Mathias Agopian87baae12012-07-31 12:38:26 -07003085 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003086
Robert Carr2047fae2016-11-28 14:09:09 -08003087 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003088 // start with the whole surface at its current location
3089 const Layer::State& s(layer->getDrawingState());
3090
Jesse Hall01e29052013-02-19 16:13:35 -08003091 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003092 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003093 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003094 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003095
Mathias Agopianab028732010-03-16 16:41:46 -07003096 /*
3097 * opaqueRegion: area of a surface that is fully opaque.
3098 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003099 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003100
3101 /*
3102 * visibleRegion: area of a surface that is visible on screen
3103 * and not fully transparent. This is essentially the layer's
3104 * footprint minus the opaque regions above it.
3105 * Areas covered by a translucent surface are considered visible.
3106 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003107 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003108
3109 /*
3110 * coveredRegion: area of a surface that is covered by all
3111 * visible regions above it (which includes the translucent areas).
3112 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003113 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003114
Jesse Halla8026d22012-09-25 13:25:04 -07003115 /*
3116 * transparentRegion: area of a surface that is hinted to be completely
3117 * transparent. This is only used to tell when the layer has no visible
3118 * non-transparent regions and can be removed from the layer list. It
3119 * does not affect the visibleRegion of this layer or any layers
3120 * beneath it. The hint may not be correct if apps don't respect the
3121 * SurfaceView restrictions (which, sadly, some don't).
3122 */
3123 Region transparentRegion;
3124
Mathias Agopianab028732010-03-16 16:41:46 -07003125
3126 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003127 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003128 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003129 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003130
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003131 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003132 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003133 if (!visibleRegion.isEmpty()) {
3134 // Remove the transparent area from the visible region
3135 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003136 if (tr.preserveRects()) {
3137 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003138 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003139 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003140 // transformation too complex, can't do the
3141 // transparent region optimization.
3142 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003143 }
Mathias Agopianab028732010-03-16 16:41:46 -07003144 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003145
Mathias Agopianab028732010-03-16 16:41:46 -07003146 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003147 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003148 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003149 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003150 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003151 // the opaque region is the layer's footprint
3152 opaqueRegion = visibleRegion;
3153 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003154 }
3155 }
3156
Robert Carre5f4f692018-01-12 13:12:28 -08003157 if (visibleRegion.isEmpty()) {
3158 layer->clearVisibilityRegions();
3159 return;
3160 }
3161
Mathias Agopianab028732010-03-16 16:41:46 -07003162 // Clip the covered region to the visible region
3163 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3164
3165 // Update aboveCoveredLayers for next (lower) layer
3166 aboveCoveredLayers.orSelf(visibleRegion);
3167
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003168 // subtract the opaque region covered by the layers above us
3169 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003170
3171 // compute this layer's dirty region
3172 if (layer->contentDirty) {
3173 // we need to invalidate the whole region
3174 dirty = visibleRegion;
3175 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003176 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003177 layer->contentDirty = false;
3178 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003179 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003180 * the exposed region consists of two components:
3181 * 1) what's VISIBLE now and was COVERED before
3182 * 2) what's EXPOSED now less what was EXPOSED before
3183 *
3184 * note that (1) is conservative, we start with the whole
3185 * visible region but only keep what used to be covered by
3186 * something -- which mean it may have been exposed.
3187 *
3188 * (2) handles areas that were not covered by anything but got
3189 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003190 */
Mathias Agopianab028732010-03-16 16:41:46 -07003191 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003192 const Region oldVisibleRegion = layer->visibleRegion;
3193 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003194 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3195 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003196 }
3197 dirty.subtractSelf(aboveOpaqueLayers);
3198
3199 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003200 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003201
Mathias Agopianab028732010-03-16 16:41:46 -07003202 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003203 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003204
Jesse Halla8026d22012-09-25 13:25:04 -07003205 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003206 layer->setVisibleRegion(visibleRegion);
3207 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003208 layer->setVisibleNonTransparentRegion(
3209 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003210 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003211
Mathias Agopian87baae12012-07-31 12:38:26 -07003212 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003213}
3214
Chia-I Wuab0c3192017-08-01 11:29:00 -07003215void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003216 for (const auto& [token, displayDevice] : mDisplays) {
3217 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003218 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003219 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003220 }
3221 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003222}
3223
Dan Stoza6b9454d2014-11-07 16:00:59 -08003224bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003225{
Ady Abraham09bd3922019-04-08 10:44:56 -07003226 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003227 ALOGV("handlePageFlip");
3228
Brian Andersond6927fb2016-07-23 23:37:30 -07003229 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003230
Mathias Agopian4fec8732012-06-29 14:12:52 -07003231 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003232 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003233 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003234
3235 // Store the set of layers that need updates. This set must not change as
3236 // buffers are being latched, as this could result in a deadlock.
3237 // Example: Two producers share the same command stream and:
3238 // 1.) Layer 0 is latched
3239 // 2.) Layer 0 gets a new frame
3240 // 2.) Layer 1 gets a new frame
3241 // 3.) Layer 1 is latched.
3242 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3243 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003244 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003245 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003246 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003247 nsecs_t expectedPresentTime;
Ana Krulecc2870422019-01-29 19:00:58 -08003248 expectedPresentTime = mScheduler->expectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003249 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003250 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003251 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003252 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003253 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003254 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003255 } else {
3256 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003257 }
Robert Carr2047fae2016-11-28 14:09:09 -08003258 });
3259
Lloyd Piquef2c79392018-12-20 16:23:33 -08003260 if (!mLayersWithQueuedFrames.empty()) {
3261 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3262 // writes to Layer current state. See also b/119481871
3263 Mutex::Autolock lock(mStateLock);
3264
3265 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003266 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003267 mLayersPendingRefresh.push_back(layer);
3268 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003269 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003270 if (layer->isBufferLatched()) {
3271 newDataLatched = true;
3272 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003273 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003274 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003275
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003276 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003277
3278 // If we will need to wake up at some time in the future to deal with a
3279 // queued frame that shouldn't be displayed during this vsync period, wake
3280 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003281 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003282 signalLayerUpdate();
3283 }
3284
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003285 // enter boot animation on first buffer latch
3286 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3287 ALOGI("Enter boot animation");
3288 mBootStage = BootStage::BOOTANIMATION;
3289 }
3290
Dan Stoza6b9454d2014-11-07 16:00:59 -08003291 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003292 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003293}
3294
Mathias Agopianad456f92011-01-13 17:53:01 -08003295void SurfaceFlinger::invalidateHwcGeometry()
3296{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003297 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003298}
3299
Lloyd Pique32cbe282018-10-19 13:09:22 -07003300void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003301 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003302 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003303 // We only need to actually compose the display if:
3304 // 1) It is being handled by hardware composer, which may need this to
3305 // keep its virtual display state machine in sync, or
3306 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003307 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003308 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003309 return;
3310 }
3311
Dan Stoza9e56aa02015-11-02 13:00:03 -08003312 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003313 base::unique_fd readyFence;
3314 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003315
3316 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003317 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003318}
3319
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003320bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3321 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003322 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003323 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003324
Lloyd Pique32cbe282018-10-19 13:09:22 -07003325 auto display = displayDevice->getCompositionDisplay();
3326 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003327 const auto displayId = display->getId();
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003328 auto& renderEngine = getRenderEngine();
Peiyong Lin548d4fa2019-04-02 18:14:44 -07003329 const bool supportProtectedContent = renderEngine.supportsProtectedContent();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003330
3331 const Region bounds(displayState.bounds);
3332 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003333 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003334 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003335
Chia-I Wu8e50e692018-05-04 10:12:37 -07003336 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003337
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003338 renderengine::DisplaySettings clientCompositionDisplay;
3339 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3340 sp<GraphicBuffer> buf;
Alec Mouri6338c9d2019-02-07 16:57:51 -08003341 base::unique_fd fd;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003342
Dan Stoza9e56aa02015-11-02 13:00:03 -08003343 if (hasClientComposition) {
3344 ALOGV("hasClientComposition");
3345
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003346 if (displayDevice->isPrimary() && supportProtectedContent) {
3347 bool needsProtected = false;
3348 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3349 // If the layer is a protected layer, mark protected context is needed.
3350 if (layer->isProtected()) {
3351 needsProtected = true;
3352 break;
3353 }
3354 }
Peiyong Lin52010312019-05-02 14:22:16 -07003355 if (needsProtected != renderEngine.isProtected()) {
3356 renderEngine.useProtectedContext(needsProtected);
3357 }
3358 if (needsProtected != display->getRenderSurface()->isProtected() &&
3359 needsProtected == renderEngine.isProtected()) {
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003360 display->getRenderSurface()->setProtected(needsProtected);
3361 }
3362 }
3363
Alec Mouri6338c9d2019-02-07 16:57:51 -08003364 buf = display->getRenderSurface()->dequeueBuffer(&fd);
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003365
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003366 if (buf == nullptr) {
3367 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3368 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003369 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003370 return false;
3371 }
3372
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003373 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3374 clientCompositionDisplay.clip = displayState.scissor;
3375 const ui::Transform& displayTransform = displayState.transform;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07003376 clientCompositionDisplay.globalTransform = displayTransform.asMatrix4();
Peiyong Linb1925962019-04-01 16:37:10 -07003377 clientCompositionDisplay.orientation = displayState.orientation;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003378
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003379 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003380 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003381 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003382 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003383 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003384 clientCompositionDisplay.outputDataspace = outputDataspace;
3385 clientCompositionDisplay.maxLuminance =
3386 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003387
Lloyd Pique441d5042018-10-18 16:49:51 -07003388 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003389 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003390 getHwComposer()
3391 .hasDisplayCapability(displayId,
3392 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003393
Peiyong Lind3788632018-09-18 16:01:31 -07003394 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003395 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3396 if (applyColorMatrix) {
Alec Mouric7e8ce82019-04-02 12:28:05 -07003397 clientCompositionDisplay.colorTransform = displayState.colorTransformMat;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003398 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003399 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003400
Mathias Agopian85d751c2012-08-29 16:59:24 -07003401 /*
3402 * and then, render the layers targeted at the framebuffer
3403 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003404
Dan Stoza9e56aa02015-11-02 13:00:03 -08003405 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003406 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003407 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003408 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003409 const Region viewportRegion(displayState.viewport);
3410 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003411 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003412 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003413 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003414 switch (layer->getCompositionType(displayDevice)) {
3415 case Hwc2::IComposerClient::Composition::CURSOR:
3416 case Hwc2::IComposerClient::Composition::DEVICE:
3417 case Hwc2::IComposerClient::Composition::SIDEBAND:
3418 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003419 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003420 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003421 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003422 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003423 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003424 // never clear the very first layer since we're
3425 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003426 renderengine::LayerSettings layerSettings;
3427 Region dummyRegion;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003428 bool prepared =
3429 layer->prepareClientLayer(renderArea, clip, dummyRegion,
3430 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003431
3432 if (prepared) {
3433 layerSettings.source.buffer.buffer = nullptr;
3434 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3435 layerSettings.alpha = half(0.0);
3436 layerSettings.disableBlending = true;
3437 clientCompositionLayers.push_back(layerSettings);
3438 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003439 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003440 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003441 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003442 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003443 renderengine::LayerSettings layerSettings;
3444 bool prepared =
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003445 layer->prepareClientLayer(renderArea, clip, clearRegion,
3446 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003447 if (prepared) {
3448 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003449 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003450 break;
3451 }
3452 default:
3453 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003454 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003455 } else {
3456 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003457 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003458 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003459 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003460
Alec Mouri820c7402019-01-23 13:02:39 -08003461 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003462 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003463 clientCompositionDisplay.clearRegion = clearRegion;
Peiyong Lin74ca2f42019-01-14 19:36:57 -08003464
3465 // We boost GPU frequency here because there will be color spaces conversion
3466 // and it's expensive. We boost the GPU frequency so that GPU composition can
3467 // finish in time. We must reset GPU frequency afterwards, because high frequency
3468 // consumes extra battery.
3469 const bool expensiveRenderingExpected =
3470 clientCompositionDisplay.outputDataspace == Dataspace::DISPLAY_P3;
3471 if (expensiveRenderingExpected && displayId) {
3472 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, true);
3473 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003474 if (!debugRegion.isEmpty()) {
3475 Region::const_iterator it = debugRegion.begin();
3476 Region::const_iterator end = debugRegion.end();
3477 while (it != end) {
3478 const Rect& rect = *it++;
3479 renderengine::LayerSettings layerSettings;
3480 layerSettings.source.buffer.buffer = nullptr;
3481 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3482 layerSettings.geometry.boundaries = rect.toFloatRect();
3483 layerSettings.alpha = half(1.0);
3484 clientCompositionLayers.push_back(layerSettings);
3485 }
3486 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003487 renderEngine.drawLayers(clientCompositionDisplay, clientCompositionLayers,
Alec Mourife0d72b2019-03-21 14:05:56 -07003488 buf->getNativeBuffer(), /*useFramebufferCache=*/true, std::move(fd),
3489 readyFence);
Peiyong Lin8ec87f82019-04-05 11:30:51 -07003490 } else if (displayId) {
3491 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, false);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003492 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003493 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003494}
3495
Chia-I Wu28e3a252018-09-07 12:05:02 -07003496void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003497 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003498 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003499}
3500
Robert Carrc0df3122019-04-11 13:18:21 -07003501status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3502 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3503 const sp<IBinder>& parentHandle,
3504 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003505 // add this layer to the current state list
3506 {
3507 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003508 sp<Layer> parent;
3509 if (parentHandle != nullptr) {
3510 parent = fromHandle(parentHandle);
3511 if (parent == nullptr) {
3512 return NAME_NOT_FOUND;
3513 }
3514 } else {
3515 parent = parentLayer;
3516 }
3517
Robert Carr1f0a16a2016-10-24 16:27:39 -07003518 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003519 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3520 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003521 return NO_MEMORY;
3522 }
Robert Carrc0df3122019-04-11 13:18:21 -07003523
3524 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3525
Robert Carrb89ea9d2018-12-10 13:01:14 -08003526 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003527 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003528 } else if (parent == nullptr) {
3529 lbc->onRemovedFromCurrentState();
3530 } else if (parent->isRemovedFromCurrentState()) {
3531 parent->addChild(lbc);
3532 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003533 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003534 parent->addChild(lbc);
3535 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003536
Yiwei Zhang243b3782018-05-15 17:40:04 -07003537 if (gbc != nullptr) {
3538 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3539 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3540 mMaxGraphicBufferProducerListSize,
3541 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3542 mGraphicBufferProducerList.size(),
3543 mMaxGraphicBufferProducerListSize, mNumLayers);
3544 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003545 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003546 }
3547
Mathias Agopian96f08192010-06-02 23:28:45 -07003548 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003549 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003550
Dan Stoza7d89d062015-04-30 13:29:25 -07003551 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003552}
3553
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003554uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003555 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003556}
3557
Mathias Agopian3f844832013-08-07 21:24:32 -07003558uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003559 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003560}
3561
Mathias Agopian3f844832013-08-07 21:24:32 -07003562uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003563 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003564}
3565
3566uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003567 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003568 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003569 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003570 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003571 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003572 }
3573 return old;
3574}
3575
Marissa Wall713b63f2018-10-17 15:42:43 -07003576bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003577 // to prevent onHandleDestroyed from being called while the lock is held,
3578 // we must keep a copy of the transactions (specifically the composer
3579 // states) around outside the scope of the lock
3580 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003581 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003582 {
3583 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003584
Valerie Haufce31b82019-04-30 16:41:14 -07003585 auto it = mTransactionQueues.begin();
3586 while (it != mTransactionQueues.end()) {
3587 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003588
Valerie Haufce31b82019-04-30 16:41:14 -07003589 while (!transactionQueue.empty()) {
3590 const auto& transaction = transactionQueue.front();
3591 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
3592 transaction.states)) {
3593 setTransactionFlags(eTransactionFlushNeeded);
3594 break;
3595 }
3596 transactions.push_back(transaction);
3597 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3598 mPendingInputWindowCommands, transaction.desiredPresentTime,
3599 transaction.buffer, transaction.callback,
3600 transaction.postTime, transaction.privileged,
3601 /*isMainThread*/ true);
3602 transactionQueue.pop();
3603 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003604 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003605
Valerie Haufce31b82019-04-30 16:41:14 -07003606 if (transactionQueue.empty()) {
3607 it = mTransactionQueues.erase(it);
3608 mTransactionCV.broadcast();
3609 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003610 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003611 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003612 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003613 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003614 return flushedATransaction;
3615}
3616
3617bool SurfaceFlinger::transactionFlushNeeded() {
3618 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003619}
3620
chaviwca27f252018-02-06 16:46:39 -08003621bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3622 for (const ComposerState& state : states) {
3623 // Here we need to check that the interface we're given is indeed
3624 // one of our own. A malicious client could give us a nullptr
3625 // IInterface, or one of its own or even one of our own but a
3626 // different type. All these situations would cause us to crash.
3627 if (state.client == nullptr) {
3628 return true;
3629 }
3630
3631 sp<IBinder> binder = IInterface::asBinder(state.client);
3632 if (binder == nullptr) {
3633 return true;
3634 }
3635
3636 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3637 return true;
3638 }
3639 }
3640 return false;
3641}
3642
Marissa Wall17b4e452018-12-26 16:32:34 -08003643bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3644 const Vector<ComposerState>& states) {
Ana Krulecc2870422019-01-29 19:00:58 -08003645 nsecs_t expectedPresentTime = mScheduler->expectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003646 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3647 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3648 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3649 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3650 return false;
3651 }
3652
Marissa Wall713b63f2018-10-17 15:42:43 -07003653 for (const ComposerState& state : states) {
3654 const layer_state_t& s = state.state;
3655 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3656 continue;
3657 }
3658 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003659 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003660 }
3661 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003662 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003663}
3664
3665void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3666 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003667 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003668 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003669 int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003670 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003671 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003672 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003673
Valerie Haubc6ddb12019-03-08 11:10:15 -08003674 const int64_t postTime = systemTime();
3675
Robert Carr14167e02019-02-13 13:50:55 -08003676 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3677
Mathias Agopian698c0872011-06-28 19:09:31 -07003678 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003679
chaviwca27f252018-02-06 16:46:39 -08003680 if (containsAnyInvalidClientState(states)) {
3681 return;
3682 }
3683
Marissa Wall713b63f2018-10-17 15:42:43 -07003684 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003685 auto itr = mTransactionQueues.find(applyToken);
3686 // if this is an animation frame, wait until prior animation frame has
3687 // been applied by SF
3688 if (flags & eAnimation) {
3689 while (itr != mTransactionQueues.end()) {
3690 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3691 if (CC_UNLIKELY(err != NO_ERROR)) {
3692 ALOGW_IF(err == TIMED_OUT,
3693 "setTransactionState timed out "
3694 "waiting for animation frame to apply");
3695 break;
3696 }
3697 itr = mTransactionQueues.find(applyToken);
3698 }
3699 }
3700 if (itr != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003701 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003702 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003703 uncacheBuffer, listenerCallbacks, postTime,
3704 privileged);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003705 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003706 return;
3707 }
3708
Valerie Haubc6ddb12019-03-08 11:10:15 -08003709 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003710 uncacheBuffer, listenerCallbacks, postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003711}
3712
3713void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003714 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003715 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003716 const int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003717 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003718 const std::vector<ListenerCallbacks>& listenerCallbacks,
Marissa Wall78b72202019-03-15 14:58:34 -07003719 const int64_t postTime, bool privileged,
3720 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003721 uint32_t transactionFlags = 0;
3722
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003723 if (flags & eAnimation) {
3724 // For window updates that are part of an animation we must wait for
3725 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003726 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003727 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003728 if (CC_UNLIKELY(err != NO_ERROR)) {
3729 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003730 // caller after a few seconds.
3731 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3732 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003733 mAnimTransactionPending = false;
3734 break;
3735 }
3736 }
3737 }
3738
chaviwca27f252018-02-06 16:46:39 -08003739 for (const DisplayState& display : displays) {
3740 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003741 }
3742
Marissa Walld600d572019-03-26 15:38:50 -07003743 // In case the client has sent a Transaction that should receive callbacks but without any
3744 // SurfaceControls that should be included in the callback, send the listener and callbackIds
3745 // to the callback thread so it can send an empty callback
3746 if (!listenerCallbacks.empty()) {
3747 mTransactionCompletedThread.run();
3748 }
3749 for (const auto& [listener, callbackIds] : listenerCallbacks) {
3750 mTransactionCompletedThread.addCallback(listener, callbackIds);
3751 }
3752
Marissa Walle2ffb422018-10-12 11:33:52 -07003753 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003754 for (const ComposerState& state : states) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07003755 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, listenerCallbacks,
3756 postTime, privileged);
3757 }
3758
Marissa Walle2ffb422018-10-12 11:33:52 -07003759 // If the state doesn't require a traversal and there are callbacks, send them now
Marissa Wallb0022cc2019-04-16 14:19:55 -07003760 if (!(clientStateFlags & eTraversalNeeded) && !listenerCallbacks.empty()) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003761 mTransactionCompletedThread.sendCallbacks();
3762 }
3763 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003764
chaviw273171b2018-12-26 11:46:30 -08003765 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3766
Marissa Wall947d34e2019-03-29 14:03:53 -07003767 if (uncacheBuffer.isValid()) {
3768 ClientCache::getInstance().erase(uncacheBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003769 }
3770
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003771 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3772 // anyway. This can be used as a flush mechanism for previous async transactions.
3773 // Empty animation transaction can be used to simulate back-pressure, so also force a
3774 // transaction for empty animation transactions.
3775 if (transactionFlags == 0 &&
3776 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003777 transactionFlags = eTransactionNeeded;
3778 }
3779
Marissa Wall06255332019-03-27 13:48:27 -07003780 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3781 // so we don't have to wake up again next frame to preform an uneeded traversal.
3782 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3783 transactionFlags = transactionFlags & (~eTraversalNeeded);
3784 mTraversalNeededMainThread = true;
3785 }
3786
Mathias Agopian386aa982011-11-07 21:58:03 -08003787 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003788 if (mInterceptor->isEnabled()) {
3789 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003790 }
Irvel468051e2016-06-13 16:44:44 -07003791
Mathias Agopian386aa982011-11-07 21:58:03 -08003792 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003793 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3794 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003795 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003796
3797 // if this is a synchronous transaction, wait for it to take effect
3798 // before returning.
3799 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003800 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003801 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003802 if (flags & eAnimation) {
3803 mAnimTransactionPending = true;
3804 }
chaviw4fe36852019-04-15 16:25:49 -07003805 if (mPendingInputWindowCommands.syncInputWindows) {
3806 mPendingSyncInputWindows = true;
3807 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003808
3809 // applyTransactionState can be called by either the main SF thread or by
3810 // another process through setTransactionState. While a given process may wish
3811 // to wait on synchronous transactions, the main SF thread should never
3812 // be blocked. Therefore, we only wait if isMainThread is false.
3813 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003814 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3815 if (CC_UNLIKELY(err != NO_ERROR)) {
3816 // just in case something goes wrong in SF, return to the
3817 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003818 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3819 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003820 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003821 break;
3822 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003823 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003824 }
3825}
3826
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003827uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3828 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3829 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003830
Mathias Agopiane57f2922012-08-09 16:29:12 -07003831 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003832 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3833
3834 const uint32_t what = s.what;
3835 if (what & DisplayState::eSurfaceChanged) {
3836 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3837 state.surface = s.surface;
3838 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003839 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003840 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003841 if (what & DisplayState::eLayerStackChanged) {
3842 if (state.layerStack != s.layerStack) {
3843 state.layerStack = s.layerStack;
3844 flags |= eDisplayTransactionNeeded;
3845 }
3846 }
3847 if (what & DisplayState::eDisplayProjectionChanged) {
3848 if (state.orientation != s.orientation) {
3849 state.orientation = s.orientation;
3850 flags |= eDisplayTransactionNeeded;
3851 }
3852 if (state.frame != s.frame) {
3853 state.frame = s.frame;
3854 flags |= eDisplayTransactionNeeded;
3855 }
3856 if (state.viewport != s.viewport) {
3857 state.viewport = s.viewport;
3858 flags |= eDisplayTransactionNeeded;
3859 }
3860 }
3861 if (what & DisplayState::eDisplaySizeChanged) {
3862 if (state.width != s.width) {
3863 state.width = s.width;
3864 flags |= eDisplayTransactionNeeded;
3865 }
3866 if (state.height != s.height) {
3867 state.height = s.height;
3868 flags |= eDisplayTransactionNeeded;
3869 }
3870 }
3871
Mathias Agopiane57f2922012-08-09 16:29:12 -07003872 return flags;
3873}
3874
Robert Carr14167e02019-02-13 13:50:55 -08003875bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003876 IPCThreadState* ipc = IPCThreadState::self();
3877 const int pid = ipc->getCallingPid();
3878 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003879 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003880 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003881 return false;
3882 }
3883 return true;
3884}
3885
Marissa Wall3dad52d2019-03-22 14:03:19 -07003886uint32_t SurfaceFlinger::setClientStateLocked(
3887 const ComposerState& composerState, int64_t desiredPresentTime,
3888 const std::vector<ListenerCallbacks>& listenerCallbacks, int64_t postTime,
3889 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003890 const layer_state_t& s = composerState.state;
3891 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3892
Mathias Agopian13127d82013-03-05 17:47:11 -08003893 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003894 if (layer == nullptr) {
3895 return 0;
3896 }
3897
chaviw8b3871a2017-11-01 17:41:01 -07003898 uint32_t flags = 0;
3899
Garfield Tan8a3083e2018-12-03 13:21:07 -08003900 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003901 bool geometryAppliesWithResize =
3902 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003903
3904 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3905 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003906 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003907 layer->pushPendingState();
3908 }
3909
chaviw8b3871a2017-11-01 17:41:01 -07003910 if (what & layer_state_t::ePositionChanged) {
3911 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3912 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003913 }
chaviw8b3871a2017-11-01 17:41:01 -07003914 }
3915 if (what & layer_state_t::eLayerChanged) {
3916 // NOTE: index needs to be calculated before we update the state
3917 const auto& p = layer->getParent();
3918 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003919 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003920 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003921 mCurrentState.layersSortedByZ.removeAt(idx);
3922 mCurrentState.layersSortedByZ.add(layer);
3923 // we need traversal (state changed)
3924 // AND transaction (list changed)
3925 flags |= eTransactionNeeded|eTraversalNeeded;
3926 }
chaviw8b3871a2017-11-01 17:41:01 -07003927 } else {
3928 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003929 flags |= eTransactionNeeded|eTraversalNeeded;
3930 }
3931 }
chaviw8b3871a2017-11-01 17:41:01 -07003932 }
3933 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003934 // NOTE: index needs to be calculated before we update the state
3935 const auto& p = layer->getParent();
3936 if (p == nullptr) {
3937 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3938 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3939 mCurrentState.layersSortedByZ.removeAt(idx);
3940 mCurrentState.layersSortedByZ.add(layer);
3941 // we need traversal (state changed)
3942 // AND transaction (list changed)
3943 flags |= eTransactionNeeded|eTraversalNeeded;
3944 }
3945 } else {
3946 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3947 flags |= eTransactionNeeded|eTraversalNeeded;
3948 }
chaviw8b3871a2017-11-01 17:41:01 -07003949 }
3950 }
3951 if (what & layer_state_t::eSizeChanged) {
3952 if (layer->setSize(s.w, s.h)) {
3953 flags |= eTraversalNeeded;
3954 }
3955 }
3956 if (what & layer_state_t::eAlphaChanged) {
3957 if (layer->setAlpha(s.alpha))
3958 flags |= eTraversalNeeded;
3959 }
3960 if (what & layer_state_t::eColorChanged) {
3961 if (layer->setColor(s.color))
3962 flags |= eTraversalNeeded;
3963 }
Peiyong Lind3788632018-09-18 16:01:31 -07003964 if (what & layer_state_t::eColorTransformChanged) {
3965 if (layer->setColorTransform(s.colorTransform)) {
3966 flags |= eTraversalNeeded;
3967 }
3968 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003969 if (what & layer_state_t::eBackgroundColorChanged) {
3970 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3971 flags |= eTraversalNeeded;
3972 }
3973 }
chaviw8b3871a2017-11-01 17:41:01 -07003974 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003975 // TODO: b/109894387
3976 //
3977 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3978 // rotation. To see the problem observe that if we have a square parent, and a child
3979 // of the same size, then we rotate the child 45 degrees around it's center, the child
3980 // must now be cropped to a non rectangular 8 sided region.
3981 //
3982 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3983 // private API, and the WindowManager only uses rotation in one case, which is on a top
3984 // level layer in which cropping is not an issue.
3985 //
3986 // However given that abuse of rotation matrices could lead to surfaces extending outside
3987 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3988 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3989 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003990 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003991 flags |= eTraversalNeeded;
3992 }
3993 if (what & layer_state_t::eTransparentRegionChanged) {
3994 if (layer->setTransparentRegionHint(s.transparentRegion))
3995 flags |= eTraversalNeeded;
3996 }
3997 if (what & layer_state_t::eFlagsChanged) {
3998 if (layer->setFlags(s.flags, s.mask))
3999 flags |= eTraversalNeeded;
4000 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004001 if (what & layer_state_t::eCropChanged_legacy) {
4002 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07004003 flags |= eTraversalNeeded;
4004 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004005 if (what & layer_state_t::eCornerRadiusChanged) {
4006 if (layer->setCornerRadius(s.cornerRadius))
4007 flags |= eTraversalNeeded;
4008 }
chaviw8b3871a2017-11-01 17:41:01 -07004009 if (what & layer_state_t::eLayerStackChanged) {
4010 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4011 // We only allow setting layer stacks for top level layers,
4012 // everything else inherits layer stack from its parent.
4013 if (layer->hasParent()) {
4014 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
4015 layer->getName().string());
4016 } else if (idx < 0) {
4017 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
4018 "that also does not appear in the top level layer list. Something"
4019 " has gone wrong.", layer->getName().string());
4020 } else if (layer->setLayerStack(s.layerStack)) {
4021 mCurrentState.layersSortedByZ.removeAt(idx);
4022 mCurrentState.layersSortedByZ.add(layer);
4023 // we need traversal (state changed)
4024 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07004025 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07004026 }
4027 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004028 if (what & layer_state_t::eDeferTransaction_legacy) {
4029 if (s.barrierHandle_legacy != nullptr) {
4030 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
4031 } else if (s.barrierGbp_legacy != nullptr) {
4032 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07004033 if (authenticateSurfaceTextureLocked(gbp)) {
4034 const auto& otherLayer =
4035 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07004036 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07004037 } else {
4038 ALOGE("Attempt to defer transaction to to an"
4039 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08004040 }
4041 }
chaviw8b3871a2017-11-01 17:41:01 -07004042 // We don't trigger a traversal here because if no other state is
4043 // changed, we don't want this to cause any more work
4044 }
4045 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08004046 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07004047 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08004048 if (!hadParent) {
4049 mCurrentState.layersSortedByZ.remove(layer);
4050 }
chaviw8b3871a2017-11-01 17:41:01 -07004051 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08004052 }
chaviw8b3871a2017-11-01 17:41:01 -07004053 }
4054 if (what & layer_state_t::eReparentChildren) {
4055 if (layer->reparentChildren(s.reparentHandle)) {
4056 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07004057 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004058 }
chaviw8b3871a2017-11-01 17:41:01 -07004059 if (what & layer_state_t::eDetachChildren) {
4060 layer->detachChildren();
4061 }
4062 if (what & layer_state_t::eOverrideScalingModeChanged) {
4063 layer->setOverrideScalingMode(s.overrideScalingMode);
4064 // We don't trigger a traversal here because if no other state is
4065 // changed, we don't want this to cause any more work
4066 }
Marissa Wall61c58622018-07-18 10:12:20 -07004067 if (what & layer_state_t::eTransformChanged) {
4068 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4069 }
4070 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4071 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4072 flags |= eTraversalNeeded;
4073 }
4074 if (what & layer_state_t::eCropChanged) {
4075 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4076 }
Marissa Wall861616d2018-10-22 12:52:23 -07004077 if (what & layer_state_t::eFrameChanged) {
4078 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
4079 }
Marissa Wall61c58622018-07-18 10:12:20 -07004080 if (what & layer_state_t::eAcquireFenceChanged) {
4081 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4082 }
4083 if (what & layer_state_t::eDataspaceChanged) {
4084 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4085 }
4086 if (what & layer_state_t::eHdrMetadataChanged) {
4087 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4088 }
4089 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4090 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4091 }
4092 if (what & layer_state_t::eApiChanged) {
4093 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4094 }
4095 if (what & layer_state_t::eSidebandStreamChanged) {
4096 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4097 }
Robert Carr720e5062018-07-30 17:45:14 -07004098 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08004099 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004100 layer->setInputInfo(s.inputInfo);
4101 flags |= eTraversalNeeded;
4102 } else {
4103 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4104 }
Robert Carr720e5062018-07-30 17:45:14 -07004105 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004106 if (what & layer_state_t::eMetadataChanged) {
4107 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4108 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004109 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4110 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4111 flags |= eTraversalNeeded;
4112 }
4113 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004114 std::vector<sp<CallbackHandle>> callbackHandles;
Marissa Wall3dad52d2019-03-22 14:03:19 -07004115 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!listenerCallbacks.empty())) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07004116 for (const auto& [listener, callbackIds] : listenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07004117 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4118 }
4119 }
Marissa Wall78b72202019-03-15 14:58:34 -07004120 bool bufferChanged = what & layer_state_t::eBufferChanged;
4121 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
4122 sp<GraphicBuffer> buffer;
4123 if (bufferChanged && cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004124 ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004125 buffer = s.buffer;
4126 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004127 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004128 } else if (bufferChanged) {
4129 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08004130 }
Marissa Wall78b72202019-03-15 14:58:34 -07004131 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004132 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08004133 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08004134 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004135 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004136 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4137 // Do not put anything that updates layer state or modifies flags after
4138 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004139 return flags;
4140}
4141
chaviw273171b2018-12-26 11:46:30 -08004142uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4143 uint32_t flags = 0;
4144 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4145 flags |= eTraversalNeeded;
4146 }
4147
chaviwa911b102019-02-14 10:18:33 -08004148 if (inputWindowCommands.syncInputWindows) {
4149 flags |= eTraversalNeeded;
4150 }
4151
Vishnu Nairec0ab382019-02-13 15:32:56 -08004152 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004153 return flags;
4154}
4155
Marissa Wall2d814fb2019-04-09 18:52:57 +00004156status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4157 uint32_t h, PixelFormat format, uint32_t flags,
4158 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07004159 sp<IGraphicBufferProducer>* gbp,
4160 const sp<IBinder>& parentHandle,
4161 const sp<Layer>& parentLayer) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004162 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004163 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004164 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004165 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004166 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004167
Robert Carrc0df3122019-04-11 13:18:21 -07004168 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4169 "Expected only one of parentLayer or parentHandle to be non-null. "
4170 "Programmer error?");
4171
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004172 status_t result = NO_ERROR;
4173
4174 sp<Layer> layer;
4175
Cody Northropbc755282017-03-31 12:00:08 -06004176 String8 uniqueName = getUniqueLayerName(name);
4177
Evan Roskya1f1e152019-01-24 16:17:46 -08004178 bool primaryDisplayOnly = false;
4179
4180 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4181 // TODO b/64227542
4182 if (metadata.has(METADATA_WINDOW_TYPE)) {
4183 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4184 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07004185 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08004186 primaryDisplayOnly = true;
4187 }
4188 }
4189
Mathias Agopian3165cc22012-08-08 19:42:09 -07004190 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004191 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Evan Roskya1f1e152019-01-24 16:17:46 -08004192 result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata),
4193 format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004194
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004195 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004196 case ISurfaceComposerClient::eFXSurfaceBufferState:
Evan Roskya1f1e152019-01-24 16:17:46 -08004197 result = createBufferStateLayer(client, uniqueName, w, h, flags, std::move(metadata),
4198 handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07004199 break;
chaviw13fdc492017-06-27 12:40:18 -07004200 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004201 // check if buffer size is set for color layer.
4202 if (w > 0 || h > 0) {
4203 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4204 int(w), int(h));
4205 return BAD_VALUE;
4206 }
4207
Evan Roskya1f1e152019-01-24 16:17:46 -08004208 result = createColorLayer(client, uniqueName, w, h, flags, std::move(metadata), handle,
4209 &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004210 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004211 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004212 // check if buffer size is set for container layer.
4213 if (w > 0 || h > 0) {
4214 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4215 int(w), int(h));
4216 return BAD_VALUE;
4217 }
Evan Roskya1f1e152019-01-24 16:17:46 -08004218 result = createContainerLayer(client, uniqueName, w, h, flags, std::move(metadata),
4219 handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004220 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004221 default:
4222 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004223 break;
4224 }
4225
Dan Stoza7d89d062015-04-30 13:29:25 -07004226 if (result != NO_ERROR) {
4227 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004228 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004229
Evan Roskya1f1e152019-01-24 16:17:46 -08004230 if (primaryDisplayOnly) {
4231 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07004232 }
4233
Robert Carrb89ea9d2018-12-10 13:01:14 -08004234 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07004235 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
4236 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004237 if (result != NO_ERROR) {
4238 return result;
4239 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004240 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004241
4242 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004243 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004244}
4245
Cody Northropbc755282017-03-31 12:00:08 -06004246String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4247{
4248 bool matchFound = true;
4249 uint32_t dupeCounter = 0;
4250
4251 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4252 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4253
Dan Stoza436ccf32018-06-21 12:10:12 -07004254 // Grab the state lock since we're accessing mCurrentState
4255 Mutex::Autolock lock(mStateLock);
4256
Cody Northropbc755282017-03-31 12:00:08 -06004257 // Loop over layers until we're sure there is no matching name
4258 while (matchFound) {
4259 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004260 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004261 if (layer->getName() == uniqueName) {
4262 matchFound = true;
4263 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4264 }
4265 });
4266 }
4267
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004268 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4269 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004270
4271 return uniqueName;
4272}
4273
Marissa Wallfd668622018-05-10 10:21:13 -07004274status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4275 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004276 LayerMetadata metadata, PixelFormat& format,
4277 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004278 sp<IGraphicBufferProducer>* gbp,
4279 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004280 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004281 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004282 case PIXEL_FORMAT_TRANSPARENT:
4283 case PIXEL_FORMAT_TRANSLUCENT:
4284 format = PIXEL_FORMAT_RGBA_8888;
4285 break;
4286 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004287 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004288 break;
4289 }
4290
Evan Roskya1f1e152019-01-24 16:17:46 -08004291 sp<BufferQueueLayer> layer = getFactory().createBufferQueueLayer(
4292 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wallfd668622018-05-10 10:21:13 -07004293 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004294 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004295 *handle = layer->getHandle();
4296 *gbp = layer->getProducer();
4297 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004298 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004299
Marissa Wallfd668622018-05-10 10:21:13 -07004300 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004301 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004302}
4303
Marissa Wall61c58622018-07-18 10:12:20 -07004304status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4305 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004306 LayerMetadata metadata, sp<IBinder>* handle,
4307 sp<Layer>* outLayer) {
4308 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(
4309 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wall61c58622018-07-18 10:12:20 -07004310 *handle = layer->getHandle();
4311 *outLayer = layer;
4312
4313 return NO_ERROR;
4314}
4315
Evan Roskya1f1e152019-01-24 16:17:46 -08004316status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, uint32_t w,
4317 uint32_t h, uint32_t flags, LayerMetadata metadata,
4318 sp<IBinder>* handle, sp<Layer>* outLayer) {
4319 *outLayer = getFactory().createColorLayer(
4320 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004321 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004322 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004323}
4324
Evan Roskya1f1e152019-01-24 16:17:46 -08004325status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name,
4326 uint32_t w, uint32_t h, uint32_t flags,
4327 LayerMetadata metadata, sp<IBinder>* handle,
4328 sp<Layer>* outLayer) {
4329 *outLayer = getFactory().createContainerLayer(
4330 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004331 *handle = (*outLayer)->getHandle();
4332 return NO_ERROR;
4333}
4334
4335
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004336void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004337 mLayersPendingRemoval.add(layer);
4338 mLayersRemoved = true;
4339 setTransactionFlags(eTransactionNeeded);
4340}
4341
Robert Carr695d5282018-12-18 15:27:58 -08004342void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004343{
Robert Carr2e102c92018-10-23 12:11:15 -07004344 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004345 // If a layer has a parent, we allow it to out-live it's handle
4346 // with the idea that the parent holds a reference and will eventually
4347 // be cleaned up. However no one cleans up the top-level so we do so
4348 // here.
4349 if (layer->getParent() == nullptr) {
4350 mCurrentState.layersSortedByZ.remove(layer);
4351 }
4352 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004353
4354 auto it = mLayersByLocalBinderToken.begin();
4355 while (it != mLayersByLocalBinderToken.end()) {
4356 if (it->second == layer) {
4357 it = mLayersByLocalBinderToken.erase(it);
4358 } else {
4359 it++;
4360 }
4361 }
4362
Robert Carr695d5282018-12-18 15:27:58 -08004363 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004364}
4365
Mathias Agopianb60314a2012-04-10 22:09:54 -07004366// ---------------------------------------------------------------------------
4367
Andy McFadden13a082e2012-08-24 10:16:42 -07004368void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004369 const auto display = getDefaultDisplayDeviceLocked();
4370 if (!display) return;
4371
4372 const sp<IBinder> token = display->getDisplayToken().promote();
4373 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004374
Jesse Hall01e29052013-02-19 16:13:35 -08004375 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004376 Vector<ComposerState> state;
4377 Vector<DisplayState> displays;
4378 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004379 d.what = DisplayState::eDisplayProjectionChanged |
4380 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004381 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004382 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004383 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004384 d.frame.makeInvalid();
4385 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004386 d.width = 0;
4387 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004388 displays.add(d);
Marissa Wall3dad52d2019-03-22 14:03:19 -07004389 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004390
Dominik Laskowskie9774092018-12-11 10:04:24 -08004391 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004392
Dominik Laskowski83b88212018-12-11 13:34:06 -08004393 const nsecs_t vsyncPeriod = getVsyncPeriod();
4394 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004395
Brian Andersond0010582017-03-07 13:20:31 -08004396 // Use phase of 0 since phase is not known.
4397 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004398 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004399 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004400}
4401
4402void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004403 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004404 postMessageAsync(
4405 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004406}
4407
Dominik Laskowskie9774092018-12-11 10:04:24 -08004408void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004409 if (display->isVirtual()) {
4410 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004411 return;
4412 }
4413
Dominik Laskowski075d3172018-05-24 15:50:06 -07004414 const auto displayId = display->getId();
4415 LOG_ALWAYS_FATAL_IF(!displayId);
4416
Dominik Laskowski34157762018-10-31 13:07:19 -07004417 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004418
4419 int currentMode = display->getPowerMode();
4420 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004421 return;
4422 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004423
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004424 display->setPowerMode(mode);
4425
Lloyd Pique4dccc412018-01-22 17:21:36 -08004426 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004427 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004428 }
4429
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004430 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004431 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004432 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004433 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004434 mScheduler->onScreenAcquired(mAppConnectionHandle);
4435 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004436 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004437
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004438 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004439 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004440 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004441
4442 struct sched_param param = {0};
4443 param.sched_priority = 1;
4444 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4445 ALOGW("Couldn't set SCHED_FIFO on display on");
4446 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004447 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004448 // Turn off the display
4449 struct sched_param param = {0};
4450 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4451 ALOGW("Couldn't set SCHED_OTHER on display off");
4452 }
4453
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004454 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004455 mScheduler->disableHardwareVsync(true);
4456 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004457 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004458
Dominik Laskowski075d3172018-05-24 15:50:06 -07004459 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004460 mVisibleRegionsDirty = true;
4461 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004462 } else if (mode == HWC_POWER_MODE_DOZE ||
4463 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004464 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004465 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004466 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004467 mScheduler->onScreenAcquired(mAppConnectionHandle);
4468 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004469 }
4470 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4471 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004472 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004473 mScheduler->disableHardwareVsync(true);
4474 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004475 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004476 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004477 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004478 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004479 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004480 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004481
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004482 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004483 mTimeStats->setPowerMode(mode);
Dominik Laskowski22488f62019-03-28 09:53:04 -07004484 mRefreshRateStats.setPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004485 }
4486
Dominik Laskowski34157762018-10-31 13:07:19 -07004487 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004488}
4489
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004490void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004491 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004492 const auto display = getDisplayDevice(displayToken);
4493 if (!display) {
4494 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4495 displayToken.get());
4496 } else if (display->isVirtual()) {
4497 ALOGW("Attempt to set power mode %d for virtual display", mode);
4498 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004499 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004500 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004501 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004502}
4503
4504// ---------------------------------------------------------------------------
4505
Dominik Laskowskic2867142019-01-21 11:33:38 -08004506status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4507 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004508 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004509
Mathias Agopianbd115332013-04-18 16:41:04 -07004510 IPCThreadState* ipc = IPCThreadState::self();
4511 const int pid = ipc->getCallingPid();
4512 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004513
Mathias Agopianbd115332013-04-18 16:41:04 -07004514 if ((uid != AID_SHELL) &&
4515 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004516 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4517 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004518 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004519 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004520 // (this would indicate SF is stuck, but we want to be able to
4521 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004522 status_t err = mStateLock.timedLock(s2ns(1));
4523 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004524 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004525 StringAppendF(&result,
4526 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4527 "(no locks held)\n",
4528 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004529 }
4530
Dominik Laskowskic2867142019-01-21 11:33:38 -08004531 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004532
Dominik Laskowskic2867142019-01-21 11:33:38 -08004533 static const std::unordered_map<std::string, Dumper> dumpers = {
4534 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4535 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4536 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004537 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004538 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004539 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004540 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4541 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004542 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4543 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4544 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4545 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4546 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4547 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004548 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004549 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4550 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004551
Dominik Laskowskic2867142019-01-21 11:33:38 -08004552 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004553
Dominik Laskowskic2867142019-01-21 11:33:38 -08004554 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4555 (it->second)(args, asProto, result);
4556 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004557 if (asProto) {
4558 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4559 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4560 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004561 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004562 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004563 }
4564
Mathias Agopian9795c422009-08-26 16:36:26 -07004565 if (locked) {
4566 mStateLock.unlock();
4567 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004568 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004569 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004570 return NO_ERROR;
4571}
4572
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004573status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4574 if (asProto && mTracing.isEnabled()) {
4575 mTracing.writeToFileAsync();
4576 }
4577
4578 return doDump(fd, DumpArgs(), asProto);
4579}
4580
Dominik Laskowskic2867142019-01-21 11:33:38 -08004581void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004582 mCurrentState.traverseInZOrder(
4583 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004584}
4585
Dominik Laskowskic2867142019-01-21 11:33:38 -08004586void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004587 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004588
Dominik Laskowskic2867142019-01-21 11:33:38 -08004589 if (args.size() > 1) {
4590 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004591 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004592 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004593 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004594 }
Robert Carr2047fae2016-11-28 14:09:09 -08004595 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004596 } else {
4597 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004598 }
4599}
4600
Dominik Laskowskic2867142019-01-21 11:33:38 -08004601void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004602 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004603 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004604 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004605 }
Robert Carr2047fae2016-11-28 14:09:09 -08004606 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004607
Svetoslavd85084b2014-03-20 10:28:31 -07004608 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004609}
4610
Dominik Laskowskic2867142019-01-21 11:33:38 -08004611void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4612 mTimeStats->parseArgs(asProto, args, result);
4613}
4614
Jamie Gennis6547ff42013-07-16 20:12:42 -07004615// This should only be called from the main thread. Otherwise it would need
4616// the lock and should use mCurrentState rather than mDrawingState.
4617void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004618 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004619 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004620 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004621
4622 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4623}
4624
Yiwei Zhang5434a782018-12-05 18:06:32 -08004625void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004626 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004627
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004628 if (isLayerTripleBufferingDisabled())
4629 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004630
Yiwei Zhang5434a782018-12-05 18:06:32 -08004631 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4632 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4633 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4634 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4635 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4636 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004637 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004638}
4639
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004640void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004641 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004642 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004643 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004644 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004645
Ady Abraham97d04232019-03-05 19:48:12 -08004646 StringAppendF(&result, "Scheduler enabled.");
Ana Krulecba13ab32019-02-20 14:14:12 -08004647 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4648 mUseSmart90ForVideo ? "on" : "off");
Ana Krulecc2870422019-01-29 19:00:58 -08004649 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004650}
4651
Yiwei Zhang5434a782018-12-05 18:06:32 -08004652void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4653 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004654 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4655 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004656 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004657 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004658 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004659 }
David Sodman4a36e932017-11-07 14:29:47 -08004660 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004661 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004662 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004663 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4664 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004665}
4666
Dan Stozae77c7662016-05-13 11:37:28 -07004667void SurfaceFlinger::recordBufferingStats(const char* layerName,
4668 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004669 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4670 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004671 for (const auto& segment : history) {
4672 if (!segment.usedThirdBuffer) {
4673 stats.twoBufferTime += segment.totalTime;
4674 }
4675 if (segment.occupancyAverage < 1.0f) {
4676 stats.doubleBufferedTime += segment.totalTime;
4677 } else if (segment.occupancyAverage < 2.0f) {
4678 stats.tripleBufferedTime += segment.totalTime;
4679 }
4680 ++stats.numSegments;
4681 stats.totalTime += segment.totalTime;
4682 }
4683}
4684
Yiwei Zhang5434a782018-12-05 18:06:32 -08004685void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4686 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004687
4688 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4689 const size_t count = currentLayers.size();
4690 for (size_t i=0 ; i<count ; i++) {
4691 currentLayers[i]->dumpFrameEvents(result);
4692 }
4693}
4694
Yiwei Zhang5434a782018-12-05 18:06:32 -08004695void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004696 result.append("Buffering stats:\n");
4697 result.append(" [Layer name] <Active time> <Two buffer> "
4698 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004699 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004700 typedef std::tuple<std::string, float, float, float> BufferTuple;
4701 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004702 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004703 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004704 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004705 if (stats.numSegments == 0) {
4706 continue;
4707 }
4708 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4709 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4710 stats.totalTime;
4711 float doubleBufferRatio = static_cast<float>(
4712 stats.doubleBufferedTime) / stats.totalTime;
4713 float tripleBufferRatio = static_cast<float>(
4714 stats.tripleBufferedTime) / stats.totalTime;
4715 sorted.insert({activeTime, {name, twoBufferRatio,
4716 doubleBufferRatio, tripleBufferRatio}});
4717 }
4718 for (const auto& sortedPair : sorted) {
4719 float activeTime = sortedPair.first;
4720 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004721 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4722 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004723 }
4724 result.append("\n");
4725}
4726
Yiwei Zhang5434a782018-12-05 18:06:32 -08004727void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004728 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004729 const auto displayId = display->getId();
4730 if (!displayId) {
4731 continue;
4732 }
4733 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004734 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004735 continue;
4736 }
4737
Yiwei Zhang5434a782018-12-05 18:06:32 -08004738 StringAppendF(&result,
4739 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4740 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004741 uint8_t port;
4742 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004743 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004744 result.append("no identification data\n");
4745 continue;
4746 }
4747
4748 if (!isEdid(data)) {
4749 result.append("unknown identification data: ");
4750 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004751 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004752 }
4753 result.append("\n");
4754 continue;
4755 }
4756
4757 const auto edid = parseEdid(data);
4758 if (!edid) {
4759 result.append("invalid EDID: ");
4760 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004761 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004762 }
4763 result.append("\n");
4764 continue;
4765 }
4766
Yiwei Zhang5434a782018-12-05 18:06:32 -08004767 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004768 result.append(edid->displayName.data(), edid->displayName.length());
4769 result.append("\"\n");
4770 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004771}
4772
Yiwei Zhang5434a782018-12-05 18:06:32 -08004773void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004774 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004775 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4776 StringAppendF(&result, "DisplayColorSetting: %s\n",
4777 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004778
4779 // TODO: print out if wide-color mode is active or not
4780
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004781 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004782 const auto displayId = display->getId();
4783 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004784 continue;
4785 }
4786
Yiwei Zhang5434a782018-12-05 18:06:32 -08004787 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004788 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004789 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004790 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004791 }
4792
Lloyd Pique32cbe282018-10-19 13:09:22 -07004793 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004794 StringAppendF(&result, " Current color mode: %s (%d)\n",
4795 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004796 }
4797 result.append("\n");
4798}
4799
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004800LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet,
4801 uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004802 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004803 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4804 const State& state = useDrawing ? mDrawingState : mCurrentState;
4805 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004806 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004807 layer->writeToProto(layerProto, stateSet, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004808 });
4809
4810 return layersProto;
4811}
4812
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004813LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4814 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004815 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004816
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004817 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004818 resolution->set_w(displayDevice->getWidth());
4819 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004820
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004821 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004822 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004823
Lloyd Pique32cbe282018-10-19 13:09:22 -07004824 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4825 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4826 layersProto.set_global_transform(displayState.orientation);
4827
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004828 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004829 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004830 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004831 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004832 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004833 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004834 }
4835 });
4836
4837 return layersProto;
4838}
4839
Dominik Laskowskic2867142019-01-21 11:33:38 -08004840void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4841 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004842 Colorizer colorizer(colorize);
4843
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004844 // figure out if we're stuck somewhere
4845 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004846 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004847 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4848
4849 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004850 * Dump library configuration.
4851 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004852
4853 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004854 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004855 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004856 appendSfConfigString(result);
4857 appendUiConfigString(result);
4858 appendGuiConfigString(result);
4859 result.append("\n");
4860
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004861 result.append("\nDisplay identification data:\n");
4862 dumpDisplayIdentificationData(result);
4863
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004864 result.append("\nWide-Color information:\n");
4865 dumpWideColorInfo(result);
4866
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004867 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004868 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004869 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004870 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004871 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004872
Andy McFadden41d67d72014-04-25 16:58:34 -07004873 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004874 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004875 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004876 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004877 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004878
Dan Stozab90cf072015-03-05 11:05:59 -08004879 dumpStaticScreenStats(result);
4880 result.append("\n");
4881
Alec Mouri40189b02019-03-05 15:07:54 -08004882 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4883 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4884 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004885
Dan Stozae77c7662016-05-13 11:37:28 -07004886 dumpBufferingStats(result);
4887
Andy McFadden4803b742012-09-24 19:07:20 -07004888 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004889 * Dump the visible layer list
4890 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004891 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004892 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4893 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4894 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004895 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004896
Chia-I Wu2f884132018-09-13 15:17:58 -07004897 {
4898 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4899 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004900 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004901 result.append("\n");
4902 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004903
Lloyd Pique207def92019-02-28 16:09:52 -08004904 {
4905 StringAppendF(&result, "Composition layers\n");
4906 mDrawingState.traverseInZOrder([&](Layer* layer) {
4907 auto compositionLayer = layer->getCompositionLayer();
4908 if (compositionLayer) compositionLayer->dump(result);
4909 });
4910 }
4911
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004912 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004913 * Dump Display state
4914 */
4915
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004916 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004917 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004918 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004919 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004920 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004921 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004922 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004923
4924 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004925 * Dump SurfaceFlinger global state
4926 */
4927
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004928 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004929 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004930 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004931
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004932 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004933
Dominik Laskowski075d3172018-05-24 15:50:06 -07004934 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004935 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4936 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004937 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4938 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004939 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004940 StringAppendF(&result,
4941 " transaction-flags : %08x\n"
4942 " gpu_to_cpu_unsupported : %d\n",
4943 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004944
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004945 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004946 displayId && getHwComposer().isConnected(*displayId)) {
4947 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004948 StringAppendF(&result,
4949 " refresh-rate : %f fps\n"
4950 " x-dpi : %f\n"
4951 " y-dpi : %f\n",
4952 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4953 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004954 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004955
Yiwei Zhang5434a782018-12-05 18:06:32 -08004956 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004957
Dan Stozae22aec72016-08-01 13:20:59 -07004958 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004959 * Tracing state
4960 */
4961 mTracing.dump(result);
4962 result.append("\n");
4963
4964 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004965 * HWC layer minidump
4966 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004967 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004968 const auto displayId = display->getId();
4969 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004970 continue;
4971 }
4972
Yiwei Zhang5434a782018-12-05 18:06:32 -08004973 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004974 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004975 const sp<DisplayDevice> displayDevice = display;
4976 mCurrentState.traverseInZOrder(
4977 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004978 result.append("\n");
4979 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004980
4981 /*
4982 * Dump HWComposer state
4983 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004984 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004985 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004986 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004987 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004988 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004989 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004990
4991 /*
4992 * Dump gralloc state
4993 */
4994 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4995 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004996
4997 /*
4998 * Dump VrFlinger state if in use.
4999 */
5000 if (mVrFlingerRequestsDisplay && mVrFlinger) {
5001 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08005002 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005003 result.append("\n");
5004 }
Ana Krulecb43429d2019-01-09 14:28:51 -08005005
5006 /**
5007 * Scheduler dump state.
5008 */
Ana Krulecc2870422019-01-29 19:00:58 -08005009 result.append("\nScheduler state:\n");
5010 result.append(mScheduler->doDump() + "\n");
Ana Krulecfefd6ae2019-02-13 17:53:08 -08005011 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
Dominik Laskowski22488f62019-03-28 09:53:04 -07005012 result.append(mRefreshRateStats.doDump() + "\n");
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07005013
5014 result.append(mTimeStats->miniDump());
5015 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005016}
5017
Dominik Laskowski075d3172018-05-24 15:50:06 -07005018const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07005019 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005020 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07005021 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005022 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07005023 }
5024 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005025
Dominik Laskowski34157762018-10-31 13:07:19 -07005026 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005027 static const Vector<sp<Layer>> empty;
5028 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07005029}
5030
Chia-I Wu28f320b2018-05-03 11:02:56 -07005031void SurfaceFlinger::updateColorMatrixLocked() {
5032 mat4 colorMatrix;
5033 if (mGlobalSaturationFactor != 1.0f) {
5034 // Rec.709 luma coefficients
5035 float3 luminance{0.213f, 0.715f, 0.072f};
5036 luminance *= 1.0f - mGlobalSaturationFactor;
5037 mat4 saturationMatrix = mat4(
5038 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
5039 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
5040 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
5041 vec4{0.0f, 0.0f, 0.0f, 1.0f}
5042 );
5043 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
5044 } else {
5045 colorMatrix = mClientColorMatrix * mDaltonizer();
5046 }
5047
5048 if (mCurrentState.colorMatrix != colorMatrix) {
5049 mCurrentState.colorMatrix = colorMatrix;
5050 mCurrentState.colorMatrixChanged = true;
5051 setTransactionFlags(eTransactionNeeded);
5052 }
5053}
5054
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005055status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005056#pragma clang diagnostic push
5057#pragma clang diagnostic error "-Wswitch-enum"
5058 switch (static_cast<ISurfaceComposerTag>(code)) {
5059 // These methods should at minimum make sure that the client requested
5060 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005061 case BOOT_FINISHED:
5062 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005063 case CREATE_DISPLAY:
5064 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005065 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005066 case GET_ANIMATION_FRAME_STATS:
5067 case GET_HDR_CAPABILITIES:
5068 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08005069 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005070 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005071 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005072 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005073 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005074 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005075 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07005076 case GET_DISPLAYED_CONTENT_SAMPLE:
5077 case NOTIFY_POWER_HINT: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005078 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5079 IPCThreadState* ipc = IPCThreadState::self();
5080 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5081 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005082 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005083 }
Robert Carr1db73f62016-12-21 12:58:51 -08005084 return OK;
5085 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005086 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005087 IPCThreadState* ipc = IPCThreadState::self();
5088 const int pid = ipc->getCallingPid();
5089 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005090 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5091 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005092 return PERMISSION_DENIED;
5093 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005094 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005095 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005096 // Used by apps to hook Choreographer to SurfaceFlinger.
5097 case CREATE_DISPLAY_EVENT_CONNECTION:
5098 // The following calls are currently used by clients that do not
5099 // request necessary permissions. However, they do not expose any secret
5100 // information, so it is OK to pass them.
5101 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07005102 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005103 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005104 case GET_PHYSICAL_DISPLAY_IDS:
5105 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005106 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005107 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005108 case GET_DISPLAY_CONFIGS:
5109 case GET_DISPLAY_STATS:
5110 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5111 // Calling setTransactionState is safe, because you need to have been
5112 // granted a reference to Client* and Handle* to do anything with it.
5113 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005114 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005115 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005116 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005117 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00005118 case IS_WIDE_COLOR_DISPLAY:
5119 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5120 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005121 return OK;
5122 }
5123 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08005124 case CAPTURE_SCREEN:
5125 case ADD_REGION_SAMPLING_LISTENER:
5126 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005127 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005128 IPCThreadState* ipc = IPCThreadState::self();
5129 const int pid = ipc->getCallingPid();
5130 const int uid = ipc->getCallingUid();
5131 if ((uid != AID_GRAPHICS) &&
5132 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5133 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5134 return PERMISSION_DENIED;
5135 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005136 return OK;
5137 }
5138 // The following codes are deprecated and should never be allowed to access SF.
5139 case CONNECT_DISPLAY_UNUSED:
5140 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5141 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5142 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005143 }
chaviw93df2ea2019-04-30 16:45:12 -07005144 case CAPTURE_SCREEN_BY_ID: {
5145 IPCThreadState* ipc = IPCThreadState::self();
5146 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07005147 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07005148 return OK;
5149 }
5150 return PERMISSION_DENIED;
5151 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005152 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005153
5154 // These codes are used for the IBinder protocol to either interrogate the recipient
5155 // side of the transaction for its canonical interface descriptor or to dump its state.
5156 // We let them pass by default.
5157 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5158 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5159 code == IBinder::SYSPROPS_TRANSACTION) {
5160 return OK;
5161 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005162 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005163 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07005164 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005165 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5166 return OK;
5167 }
5168 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5169 return PERMISSION_DENIED;
5170#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005171}
5172
Ana Krulec13be8ad2018-08-21 02:43:56 +00005173status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5174 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005175 status_t credentialCheck = CheckTransactCodeCredentials(code);
5176 if (credentialCheck != OK) {
5177 return credentialCheck;
5178 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005179
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005180 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5181 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005182 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005183 IPCThreadState* ipc = IPCThreadState::self();
5184 const int uid = ipc->getCallingUid();
5185 if (CC_UNLIKELY(uid != AID_SYSTEM
5186 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005187 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005188 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005189 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005190 return PERMISSION_DENIED;
5191 }
5192 int n;
5193 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005194 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005195 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005196 return NO_ERROR;
5197 case 1002: // SHOW_UPDATES
5198 n = data.readInt32();
5199 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005200 invalidateHwcGeometry();
5201 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005202 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005203 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005204 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005205 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005206 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005207 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005208 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005209 setTransactionFlags(
5210 eTransactionNeeded|
5211 eDisplayTransactionNeeded|
5212 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005213 return NO_ERROR;
5214 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005215 case 1006:{ // send empty update
5216 signalRefresh();
5217 return NO_ERROR;
5218 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005219 case 1008: // toggle use of hw composer
5220 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005221 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07005222 invalidateHwcGeometry();
5223 repaintEverything();
5224 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005225 case 1009: // toggle use of transform hint
5226 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005227 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07005228 invalidateHwcGeometry();
5229 repaintEverything();
5230 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005231 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005232 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005233 reply->writeInt32(0);
5234 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005235 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005236 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005237 return NO_ERROR;
5238 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005239 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005240 if (!display) {
5241 return NAME_NOT_FOUND;
5242 }
5243
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005244 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005245 return NO_ERROR;
5246 }
5247 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005248 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005249 // daltonize
5250 n = data.readInt32();
5251 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005252 case 1:
5253 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5254 break;
5255 case 2:
5256 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5257 break;
5258 case 3:
5259 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5260 break;
5261 default:
5262 mDaltonizer.setType(ColorBlindnessType::None);
5263 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005264 }
5265 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005266 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005267 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005268 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005269 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005270
5271 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005272 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005273 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005274 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005275 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005276 // apply a color matrix
5277 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005278 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005279 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005280 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005281 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005282 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005283 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005284 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005285 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005286 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005287 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005288
5289 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5290 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005291 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005292 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5293 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5294 }
5295
Chia-I Wu28f320b2018-05-03 11:02:56 -07005296 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005297 return NO_ERROR;
5298 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005299 // This is an experimental interface
5300 // Needs to be shifted to proper binder interface when we productize
5301 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005302 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005303 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005304 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005305 return NO_ERROR;
5306 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005307 case 1017: {
5308 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005309 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005310 return NO_ERROR;
5311 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005312 case 1018: { // Modify Choreographer's phase offset
5313 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005314 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005315 return NO_ERROR;
5316 }
5317 case 1019: { // Modify SurfaceFlinger's phase offset
5318 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005319 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005320 return NO_ERROR;
5321 }
Irvel468051e2016-06-13 16:44:44 -07005322 case 1020: { // Layer updates interceptor
5323 n = data.readInt32();
5324 if (n) {
5325 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005326 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005327 }
5328 else{
5329 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005330 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005331 }
5332 return NO_ERROR;
5333 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005334 case 1021: { // Disable HWC virtual displays
5335 n = data.readInt32();
5336 mUseHwcVirtualDisplays = !n;
5337 return NO_ERROR;
5338 }
Romain Guy0147a172017-06-01 13:53:56 -07005339 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005340 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005341 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005342
Chia-I Wu28f320b2018-05-03 11:02:56 -07005343 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005344 return NO_ERROR;
5345 }
Romain Guy54f154a2017-10-24 21:40:32 +01005346 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005347 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005348 invalidateHwcGeometry();
5349 repaintEverything();
5350 return NO_ERROR;
5351 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005352 // Deprecate, use 1030 to check whether the device is color managed.
5353 case 1024: {
5354 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005355 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005356 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005357 n = data.readInt32();
5358 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005359 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005360 Mutex::Autolock lock(mStateLock);
5361 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005362 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005363 reply->writeInt32(NO_ERROR);
5364 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005365 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005366 bool writeFile = false;
5367 {
5368 Mutex::Autolock lock(mStateLock);
5369 mTracingEnabledChanged = true;
5370 writeFile = mTracing.disable();
5371 }
5372
5373 if (writeFile) {
5374 reply->writeInt32(mTracing.writeToFile());
5375 } else {
5376 reply->writeInt32(NO_ERROR);
5377 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005378 }
5379 return NO_ERROR;
5380 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005381 case 1026: { // Get layer tracing status
5382 reply->writeBool(mTracing.isEnabled());
5383 return NO_ERROR;
5384 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005385 // Is a DisplayColorSetting supported?
5386 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005387 const auto display = getDefaultDisplayDevice();
5388 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005389 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005390 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005391
5392 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5393 switch (setting) {
5394 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005395 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005396 break;
5397 case DisplayColorSetting::UNMANAGED:
5398 reply->writeBool(true);
5399 break;
5400 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005401 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005402 break;
5403 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005404 reply->writeBool(
5405 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005406 break;
5407 }
5408 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005409 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005410 // Is VrFlinger active?
5411 case 1028: {
5412 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005413 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005414 return NO_ERROR;
5415 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005416 // Set buffer size for SF tracing (value in KB)
5417 case 1029: {
5418 n = data.readInt32();
5419 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5420 ALOGW("Invalid buffer size: %d KB", n);
5421 reply->writeInt32(BAD_VALUE);
5422 return BAD_VALUE;
5423 }
5424
5425 ALOGD("Updating trace buffer to %d KB", n);
5426 mTracing.setBufferSize(n * 1024);
5427 reply->writeInt32(NO_ERROR);
5428 return NO_ERROR;
5429 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005430 // Is device color managed?
5431 case 1030: {
5432 reply->writeBool(useColorManagement);
5433 return NO_ERROR;
5434 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005435 // Override default composition data space
5436 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5437 // && adb shell stop zygote && adb shell start zygote
5438 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5439 // adb shell stop zygote && adb shell start zygote
5440 case 1031: {
5441 Mutex::Autolock _l(mStateLock);
5442 n = data.readInt32();
5443 if (n) {
5444 n = data.readInt32();
5445 if (n) {
5446 Dataspace dataspace = static_cast<Dataspace>(n);
5447 if (!validateCompositionDataspace(dataspace)) {
5448 return BAD_VALUE;
5449 }
5450 mDefaultCompositionDataspace = dataspace;
5451 }
5452 n = data.readInt32();
5453 if (n) {
5454 Dataspace dataspace = static_cast<Dataspace>(n);
5455 if (!validateCompositionDataspace(dataspace)) {
5456 return BAD_VALUE;
5457 }
5458 mWideColorGamutCompositionDataspace = dataspace;
5459 }
5460 } else {
5461 // restore composition data space.
5462 mDefaultCompositionDataspace = defaultCompositionDataspace;
5463 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5464 }
5465 return NO_ERROR;
5466 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005467 // Set trace flags
5468 case 1033: {
5469 n = data.readUint32();
5470 ALOGD("Updating trace flags to 0x%x", n);
5471 mTracing.setTraceFlags(n);
5472 reply->writeInt32(NO_ERROR);
5473 return NO_ERROR;
5474 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005475 case 1034: {
5476 // TODO(b/129297325): expose this via developer menu option
5477 n = data.readInt32();
5478 if (n && !mRefreshRateOverlay) {
Ady Abrahamfed164b2019-05-10 17:12:54 -07005479 RefreshRateType type;
5480 {
5481 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5482 type = mDesiredActiveConfig.type;
5483 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005484 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abrahamfed164b2019-05-10 17:12:54 -07005485 mRefreshRateOverlay->changeRefreshRate(type);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005486 } else if (!n) {
5487 mRefreshRateOverlay.reset();
5488 }
5489 return NO_ERROR;
5490 }
Ady Abraham34392f72019-04-10 11:29:27 -07005491 case 1035: {
5492 n = data.readInt32();
5493 mDebugDisplayConfigSetByBackdoor = false;
5494 if (n >= 0) {
5495 const auto displayToken = getInternalDisplayToken();
5496 status_t result = setAllowedDisplayConfigs(displayToken, {n});
5497 if (result != NO_ERROR) {
5498 return result;
5499 }
5500 mDebugDisplayConfigSetByBackdoor = true;
5501 }
5502 return NO_ERROR;
5503 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005504 }
5505 }
5506 return err;
5507}
5508
Steven Thomas6d8110b2017-08-31 18:24:21 -07005509void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005510 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005511 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005512}
5513
Ana Krulec7d1d6832018-12-27 11:10:09 -08005514void SurfaceFlinger::repaintEverythingForHWC() {
5515 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07005516 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005517}
5518
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005519// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5520class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005521public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005522 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5523 ~WindowDisconnector() {
5524 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005525 }
5526
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005527private:
5528 ANativeWindow* mWindow;
5529 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005530};
5531
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005532status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005533 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
5534 const Dataspace reqDataspace,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005535 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005536 uint32_t reqWidth, uint32_t reqHeight,
5537 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08005538 ISurfaceComposer::Rotation rotation,
5539 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005540 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005541
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005542 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005543
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005544 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5545
Chia-I Wu20261cb2018-08-23 12:55:44 -07005546 sp<DisplayDevice> display;
5547 {
5548 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005549
Chia-I Wu20261cb2018-08-23 12:55:44 -07005550 display = getDisplayDeviceLocked(displayToken);
5551 if (!display) return BAD_VALUE;
5552
Chia-I Wucb023152018-08-28 12:57:23 -07005553 // set the requested width/height to the logical display viewport size
5554 // by default
5555 if (reqWidth == 0 || reqHeight == 0) {
5556 reqWidth = uint32_t(display->getViewport().width());
5557 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005558 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005559 }
5560
Peiyong Lin0e003c92018-09-17 11:09:51 -07005561 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005562 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005563
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005564 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5565 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005566 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005567 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005568}
5569
chaviw93df2ea2019-04-30 16:45:12 -07005570static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5571 switch (colorMode) {
5572 case ColorMode::DISPLAY_P3:
5573 case ColorMode::BT2100_PQ:
5574 case ColorMode::BT2100_HLG:
5575 case ColorMode::DISPLAY_BT2020:
5576 return Dataspace::DISPLAY_P3;
5577 default:
5578 return Dataspace::V0_SRGB;
5579 }
5580}
5581
5582const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5583 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5584 if (displayToken) {
5585 return getDisplayDeviceLocked(displayToken);
5586 }
5587 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5588 // may not have a displayId.
5589 for (const auto& [token, display] : mDisplays) {
5590 if (display->getLayerStack() == displayOrLayerStack) {
5591 return display;
5592 }
5593 }
5594 return nullptr;
5595}
5596
5597status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5598 sp<GraphicBuffer>* outBuffer) {
5599 sp<DisplayDevice> display;
5600 uint32_t width;
5601 uint32_t height;
5602 ui::Transform::orientation_flags captureOrientation;
5603 {
5604 Mutex::Autolock _l(mStateLock);
5605 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5606 if (!display) {
5607 return BAD_VALUE;
5608 }
5609
5610 width = uint32_t(display->getViewport().width());
5611 height = uint32_t(display->getViewport().height());
5612
5613 captureOrientation = fromSurfaceComposerRotation(
5614 static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
5615 *outDataspace =
5616 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5617 }
5618
5619 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5620 false /* captureSecureLayers */);
5621
5622 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5623 std::placeholders::_1);
5624 bool ignored = false;
5625 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5626 false /* useIdentityTransform */,
5627 ignored /* outCapturedSecureLayers */);
5628}
5629
Robert Carr866455f2019-04-02 16:28:26 -07005630status_t SurfaceFlinger::captureLayers(
5631 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5632 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5633 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5634 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005635 ATRACE_CALL();
5636
5637 class LayerRenderArea : public RenderArea {
5638 public:
Robert Carr578038f2018-03-09 12:25:24 -08005639 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005640 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5641 bool childrenOnly)
5642 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005643 mLayer(layer),
5644 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005645 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005646 mFlinger(flinger),
5647 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005648 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005649 Rect getBounds() const override {
5650 const Layer::State& layerState(mLayer->getDrawingState());
5651 return mLayer->getBufferSize(layerState);
5652 }
Marissa Wall61c58622018-07-18 10:12:20 -07005653 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005654 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005655 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005656 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005657 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005658 }
chaviwa76b2712017-09-20 12:02:26 -07005659 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005660 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005661 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005662 Rect getSourceCrop() const override {
5663 if (mCrop.isEmpty()) {
5664 return getBounds();
5665 } else {
5666 return mCrop;
5667 }
5668 }
Robert Carr578038f2018-03-09 12:25:24 -08005669 class ReparentForDrawing {
5670 public:
5671 const sp<Layer>& oldParent;
5672 const sp<Layer>& newParent;
5673
Vishnu Nair4351ad52019-02-11 14:13:02 -08005674 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5675 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005676 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005677 // Compute and cache the bounds for the new parent layer.
5678 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005679 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005680 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005681 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005682 };
5683
5684 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005685 const Rect sourceCrop = getSourceCrop();
5686 // no need to check rotation because there is none
5687 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5688 sourceCrop.height() != getReqHeight();
5689
Robert Carr578038f2018-03-09 12:25:24 -08005690 if (!mChildrenOnly) {
5691 mTransform = mLayer->getTransform().inverse();
5692 drawLayers();
5693 } else {
5694 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005695 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005696 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
Evan Roskya1f1e152019-01-24 16:17:46 -08005697 bounds.getWidth(), bounds.getHeight(), 0,
5698 LayerMetadata()));
Robert Carr578038f2018-03-09 12:25:24 -08005699
Vishnu Nair4351ad52019-02-11 14:13:02 -08005700 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005701 drawLayers();
5702 }
5703 }
chaviwa76b2712017-09-20 12:02:26 -07005704
chaviwa76b2712017-09-20 12:02:26 -07005705 private:
chaviw7206d492017-11-10 16:16:12 -08005706 const sp<Layer> mLayer;
5707 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005708
5709 // In the "childrenOnly" case we reparent the children to a screenshot
5710 // layer which has no properties set and which does not draw.
5711 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005712 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005713 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005714
5715 SurfaceFlinger* mFlinger;
5716 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005717 };
5718
Robert Carrc0df3122019-04-11 13:18:21 -07005719 int reqWidth = 0;
5720 int reqHeight = 0;
5721 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005722 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005723 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
chaviw7206d492017-11-10 16:16:12 -08005724
Robert Carrc0df3122019-04-11 13:18:21 -07005725 {
5726 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005727
Robert Carrc0df3122019-04-11 13:18:21 -07005728 parent = fromHandle(layerHandleBinder);
5729 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5730 ALOGE("captureLayers called with an invalid or removed parent");
5731 return NAME_NOT_FOUND;
5732 }
5733
5734 const int uid = IPCThreadState::self()->getCallingUid();
5735 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5736 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5737 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5738 return PERMISSION_DENIED;
5739 }
5740
5741 if (sourceCrop.width() <= 0) {
5742 crop.left = 0;
5743 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
5744 }
5745
5746 if (sourceCrop.height() <= 0) {
5747 crop.top = 0;
5748 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
5749 }
5750 reqWidth = crop.width() * frameScale;
5751 reqHeight = crop.height() * frameScale;
5752
5753 for (const auto& handle : excludeHandles) {
5754 sp<Layer> excludeLayer = fromHandle(handle);
5755 if (excludeLayer != nullptr) {
5756 excludeLayers.emplace(excludeLayer);
5757 } else {
5758 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5759 return NAME_NOT_FOUND;
5760 }
5761 }
5762 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005763
Chia-I Wu20261cb2018-08-23 12:55:44 -07005764 // really small crop or frameScale
5765 if (reqWidth <= 0) {
5766 reqWidth = 1;
5767 }
5768 if (reqHeight <= 0) {
5769 reqHeight = 1;
5770 }
5771
Robert Carr866455f2019-04-02 16:28:26 -07005772 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
5773 auto traverseLayers = [parent, childrenOnly,
5774 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005775 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5776 if (!layer->isVisible()) {
5777 return;
Robert Carr578038f2018-03-09 12:25:24 -08005778 } else if (childrenOnly && layer == parent.get()) {
5779 return;
chaviwa76b2712017-09-20 12:02:26 -07005780 }
Robert Carr866455f2019-04-02 16:28:26 -07005781
5782 sp<Layer> p = layer;
5783 while (p != nullptr) {
5784 if (excludeLayers.count(p) != 0) {
5785 return;
5786 }
5787 p = p->getParent();
5788 }
5789
chaviwa76b2712017-09-20 12:02:26 -07005790 visitor(layer);
5791 });
5792 };
Robert Carr108b2c72019-04-02 16:32:58 -07005793
5794 bool outCapturedSecureLayers = false;
5795 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5796 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005797}
5798
5799status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5800 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005801 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005802 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005803 bool useIdentityTransform,
5804 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005805 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005806
Peiyong Lin0e003c92018-09-17 11:09:51 -07005807 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005808 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5809 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005810 *outBuffer =
5811 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5812 static_cast<android_pixel_format>(reqPixelFormat), 1,
5813 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005814
Robert Carr108b2c72019-04-02 16:32:58 -07005815 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5816 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005817}
5818
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005819status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5820 TraverseLayersFunction traverseLayers,
5821 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005822 bool useIdentityTransform,
5823 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005824 // This mutex protects syncFd and captureResult for communication of the return values from the
5825 // main thread back to this Binder thread
5826 std::mutex captureMutex;
5827 std::condition_variable captureCondition;
5828 std::unique_lock<std::mutex> captureLock(captureMutex);
5829 int syncFd = -1;
5830 std::optional<status_t> captureResult;
5831
Robert Carr03480e22018-01-04 16:02:06 -08005832 const int uid = IPCThreadState::self()->getCallingUid();
5833 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5834
Dominik Laskowski8c001672018-05-30 16:52:06 -07005835 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005836 // If there is a refresh pending, bug out early and tell the binder thread to try again
5837 // after the refresh.
5838 if (mRefreshPending) {
5839 ATRACE_NAME("Skipping screenshot for now");
5840 std::unique_lock<std::mutex> captureLock(captureMutex);
5841 captureResult = std::make_optional<status_t>(EAGAIN);
5842 captureCondition.notify_one();
5843 return;
5844 }
5845
5846 status_t result = NO_ERROR;
5847 int fd = -1;
5848 {
5849 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005850 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005851 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005852 useIdentityTransform, forSystem, &fd,
5853 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005854 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005855 }
5856
5857 {
5858 std::unique_lock<std::mutex> captureLock(captureMutex);
5859 syncFd = fd;
5860 captureResult = std::make_optional<status_t>(result);
5861 captureCondition.notify_one();
5862 }
5863 });
5864
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005865 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005866 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005867 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005868 while (*captureResult == EAGAIN) {
5869 captureResult.reset();
5870 result = postMessageAsync(message);
5871 if (result != NO_ERROR) {
5872 return result;
5873 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005874 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005875 }
5876 result = *captureResult;
5877 }
5878
5879 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005880 sync_wait(syncFd, -1);
5881 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005882 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005883
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005884 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005885}
5886
chaviwa76b2712017-09-20 12:02:26 -07005887void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005888 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005889 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5890 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005891 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005892
chaviwa76b2712017-09-20 12:02:26 -07005893 const auto reqWidth = renderArea.getReqWidth();
5894 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005895 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005896 const auto transform = renderArea.getTransform();
5897 const auto sourceCrop = renderArea.getSourceCrop();
Dan Stozac1879002014-05-22 15:59:05 -07005898
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005899 renderengine::DisplaySettings clientCompositionDisplay;
5900 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005901
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005902 // assume that bounds are never offset, and that they are the same as the
5903 // buffer bounds.
5904 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005905 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005906 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005907
5908 // Now take into account the rotation flag. We append a transform that
5909 // rotates the layer stack about the origin, then translate by buffer
5910 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005911 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005912 int displacementX = 0;
5913 int displacementY = 0;
5914 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5915 switch (rotation) {
5916 case ui::Transform::ROT_90:
5917 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005918 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005919 break;
5920 case ui::Transform::ROT_180:
5921 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005922 displacementY = renderArea.getBounds().getWidth();
5923 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005924 break;
5925 case ui::Transform::ROT_270:
5926 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005927 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005928 break;
5929 default:
5930 break;
5931 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005932
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005933 // We need to transform the clipping window into the right spot.
5934 // First, rotate the clipping rectangle by the rotation hint to get the
5935 // right orientation
5936 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5937 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5938 const vec4 rotClipTL = rotMatrix * clipTL;
5939 const vec4 rotClipBR = rotMatrix * clipBR;
5940 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5941 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5942 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5943 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5944
5945 // Now reposition the clipping rectangle with the displacement vector
5946 // computed above.
5947 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005948 clientCompositionDisplay.clip =
5949 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5950 newClipRight + displacementX, newClipBottom + displacementY);
5951
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005952 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005953 clientCompositionDisplay.globalTransform =
5954 clipTransform * clientCompositionDisplay.globalTransform;
5955
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005956 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5957 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005958
chaviw50da5042018-04-09 13:49:37 -07005959 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005960
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005961 renderengine::LayerSettings fillLayer;
5962 fillLayer.source.buffer.buffer = nullptr;
5963 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5964 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5965 fillLayer.alpha = half(alpha);
5966 clientCompositionLayers.push_back(fillLayer);
5967
5968 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005969 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005970 renderengine::LayerSettings layerSettings;
5971 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005972 false, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005973 if (prepared) {
5974 clientCompositionLayers.push_back(layerSettings);
5975 }
chaviwa76b2712017-09-20 12:02:26 -07005976 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005977
5978 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005979 // Use an empty fence for the buffer fence, since we just created the buffer so
5980 // there is no need for synchronization with the GPU.
5981 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005982 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005983 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005984 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005985 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005986
5987 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005988}
5989
chaviwa76b2712017-09-20 12:02:26 -07005990status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5991 TraverseLayersFunction traverseLayers,
5992 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005993 bool useIdentityTransform, bool forSystem,
5994 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005995 ATRACE_CALL();
5996
chaviwa76b2712017-09-20 12:02:26 -07005997 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005998 outCapturedSecureLayers =
5999 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07006000 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08006001
Robert Carr03480e22018-01-04 16:02:06 -08006002 // We allow the system server to take screenshots of secure layers for
6003 // use in situations like the Screen-rotation animation and place
6004 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07006005 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08006006 ALOGW("FB is protected: PERMISSION_DENIED");
6007 return PERMISSION_DENIED;
6008 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006009 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006010 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07006011}
6012
chaviw95ef3c42019-02-14 10:55:09 -08006013void SurfaceFlinger::setInputWindowsFinished() {
6014 Mutex::Autolock _l(mStateLock);
6015
6016 mPendingSyncInputWindows = false;
6017 mTransactionCV.broadcast();
6018}
chaviw5f21a5e2019-02-14 10:00:34 -08006019
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07006020// ---------------------------------------------------------------------------
6021
Dan Stoza412903f2017-04-27 13:42:17 -07006022void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
6023 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006024}
6025
Dan Stoza412903f2017-04-27 13:42:17 -07006026void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
6027 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006028}
6029
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006030void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07006031 const LayerVector::Visitor& visitor) {
6032 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07006033 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07006034 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006035 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07006036 continue;
6037 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08006038 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07006039 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006040 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01006041 return;
6042 }
chaviwa76b2712017-09-20 12:02:26 -07006043 if (!layer->isVisible()) {
6044 return;
6045 }
6046 visitor(layer);
6047 });
6048 }
6049}
6050
Dominik Laskowski22488f62019-03-28 09:53:04 -07006051void SurfaceFlinger::setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
6052 const std::vector<int32_t>& allowedConfigs) {
6053 if (!display->isPrimary()) {
Ady Abraham838de062019-02-04 10:24:03 -08006054 return;
6055 }
6056
6057 ALOGV("Updating allowed configs");
Dominik Laskowski22488f62019-03-28 09:53:04 -07006058 mAllowedDisplayConfigs = DisplayConfigs(allowedConfigs.begin(), allowedConfigs.end());
Ady Abraham838de062019-02-04 10:24:03 -08006059
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006060 // Set the highest allowed config by iterating backwards on available refresh rates
Dominik Laskowski22488f62019-03-28 09:53:04 -07006061 const auto& refreshRates = mRefreshRateConfigs.getRefreshRates();
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006062 for (auto iter = refreshRates.crbegin(); iter != refreshRates.crend(); ++iter) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07006063 if (iter->second && isDisplayConfigAllowed(iter->second->configId)) {
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006064 ALOGV("switching to config %d", iter->second->configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -07006065 setDesiredActiveConfig(
6066 {iter->first, iter->second->configId, Scheduler::ConfigEvent::Changed});
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006067 break;
Ady Abraham97d04232019-03-05 19:48:12 -08006068 }
6069 }
Ady Abraham838de062019-02-04 10:24:03 -08006070}
6071
Dominik Laskowski22488f62019-03-28 09:53:04 -07006072status_t SurfaceFlinger::setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abraham838de062019-02-04 10:24:03 -08006073 const std::vector<int32_t>& allowedConfigs) {
6074 ATRACE_CALL();
6075
Dominik Laskowski22488f62019-03-28 09:53:04 -07006076 if (!displayToken || allowedConfigs.empty()) {
Ady Abraham838de062019-02-04 10:24:03 -08006077 return BAD_VALUE;
6078 }
6079
Ady Abraham34392f72019-04-10 11:29:27 -07006080 if (mDebugDisplayConfigSetByBackdoor) {
6081 // ignore this request as config is overridden by backdoor
6082 return NO_ERROR;
6083 }
6084
Ady Abraham838de062019-02-04 10:24:03 -08006085 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski22488f62019-03-28 09:53:04 -07006086 const auto display = getDisplayDeviceLocked(displayToken);
6087 if (!display) {
6088 ALOGE("Attempt to set allowed display configs for invalid display token %p",
6089 displayToken.get());
6090 } else if (display->isVirtual()) {
6091 ALOGW("Attempt to set allowed display configs for virtual display");
6092 } else {
6093 setAllowedDisplayConfigsInternal(display, allowedConfigs);
6094 }
Ady Abraham838de062019-02-04 10:24:03 -08006095 }));
Dominik Laskowski22488f62019-03-28 09:53:04 -07006096
Ady Abraham838de062019-02-04 10:24:03 -08006097 return NO_ERROR;
6098}
6099
Dominik Laskowski22488f62019-03-28 09:53:04 -07006100status_t SurfaceFlinger::getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006101 std::vector<int32_t>* outAllowedConfigs) {
6102 ATRACE_CALL();
6103
Dominik Laskowski22488f62019-03-28 09:53:04 -07006104 if (!displayToken || !outAllowedConfigs) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006105 return BAD_VALUE;
6106 }
6107
Dominik Laskowski22488f62019-03-28 09:53:04 -07006108 Mutex::Autolock lock(mStateLock);
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006109
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006110 const auto display = getDisplayDeviceLocked(displayToken);
6111 if (!display) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006112 return NAME_NOT_FOUND;
6113 }
6114
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006115 if (display->isPrimary()) {
6116 outAllowedConfigs->assign(mAllowedDisplayConfigs.begin(), mAllowedDisplayConfigs.end());
6117 }
6118
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006119 return NO_ERROR;
6120}
6121
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006122void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006123 mFlinger->setInputWindowsFinished();
6124}
6125
Robert Carrc0df3122019-04-11 13:18:21 -07006126sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6127 BBinder *b = handle->localBinder();
6128 if (b == nullptr) {
6129 return nullptr;
6130 }
6131 auto it = mLayersByLocalBinderToken.find(b);
6132 if (it != mLayersByLocalBinderToken.end()) {
6133 return it->second.promote();
6134 }
6135 return nullptr;
6136}
6137
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006138} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006139
Mathias Agopian3f844832013-08-07 21:24:32 -07006140#if defined(__gl_h_)
6141#error "don't include gl/gl.h in this file"
6142#endif
6143
6144#if defined(__gl2_h_)
6145#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006146#endif