blob: 8ef03fb762487b53b0026cb9a976646f9b7a5498 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Alec Mourie7d1d4a2019-02-05 01:13:46 +000017//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070022#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080023
24#include <algorithm>
25#include <cinttypes>
26#include <cmath>
27#include <cstdint>
28#include <functional>
29#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070030#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080031#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Lloyd Pique70d91362018-10-18 16:02:55 -070040#include <compositionengine/CompositionEngine.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070041#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070042#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080043#include <compositionengine/Layer.h>
44#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070045#include <compositionengine/RenderSurface.h>
Lloyd Pique0b785d82018-12-04 17:25:27 -080046#include <compositionengine/impl/LayerCompositionState.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070047#include <compositionengine/impl/OutputCompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080048#include <compositionengine/impl/OutputLayerCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080049#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070052#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080053#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080054#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080055#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070056#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070057#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070058#include <ui/ColorSpace.h>
59#include <ui/DebugUtils.h>
60#include <ui/DisplayInfo.h>
61#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <ui/GraphicBufferAllocator.h>
63#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070064#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070066#include <utils/String16.h>
67#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070068#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080069#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071
Mathias Agopian921e6ac2012-07-23 23:11:29 -070072#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070073#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074
Robert Carr578038f2018-03-09 12:25:24 -080075#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070076#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070077#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020078#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080079#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020080#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080081#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080082#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070084#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080085#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070086#include "NativeWindowSurface.h"
Ady Abraham03b02dd2019-03-21 15:40:11 -070087#include "RefreshRateOverlay.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070088#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070090#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091
Steven Thomasb02664d2017-07-26 18:48:28 -070092#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070093#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070094#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070095#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070096#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070097#include "Effects/Daltonizer.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -070098#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070099#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700100#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700101#include "Scheduler/EventControlThread.h"
102#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700103#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700104#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700105#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700106#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800107#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700108
Mathias Agopianff2ed702013-09-01 21:36:12 -0700109#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700110
David Sodman7e4ae112018-02-09 15:02:28 -0800111#include "android-base/stringprintf.h"
112
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900113#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800114#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
115#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900116#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900117
chaviw1d044282017-09-27 12:19:28 -0700118#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900119#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700120
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800121namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700122
Jaesoo Lee43518572017-01-23 19:03:16 +0900123using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900124using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900125using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800126
Yiwei Zhang5434a782018-12-05 18:06:32 -0800127using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700128using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700129using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800130using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700131using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700132using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900133
Steven Thomasb02664d2017-07-26 18:48:28 -0700134namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700135
136#pragma clang diagnostic push
137#pragma clang diagnostic error "-Wswitch-enum"
138
139bool isWideColorMode(const ColorMode colorMode) {
140 switch (colorMode) {
141 case ColorMode::DISPLAY_P3:
142 case ColorMode::ADOBE_RGB:
143 case ColorMode::DCI_P3:
144 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700145 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700146 case ColorMode::BT2100_PQ:
147 case ColorMode::BT2100_HLG:
148 return true;
149 case ColorMode::NATIVE:
150 case ColorMode::STANDARD_BT601_625:
151 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
152 case ColorMode::STANDARD_BT601_525:
153 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
154 case ColorMode::STANDARD_BT709:
155 case ColorMode::SRGB:
156 return false;
157 }
158 return false;
159}
160
Peiyong Lin34ea5b92019-03-15 18:40:15 -0700161bool isHdrColorMode(const ColorMode colorMode) {
162 switch (colorMode) {
163 case ColorMode::BT2100_PQ:
164 case ColorMode::BT2100_HLG:
165 return true;
166 case ColorMode::DISPLAY_P3:
167 case ColorMode::ADOBE_RGB:
168 case ColorMode::DCI_P3:
169 case ColorMode::BT2020:
170 case ColorMode::DISPLAY_BT2020:
171 case ColorMode::NATIVE:
172 case ColorMode::STANDARD_BT601_625:
173 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
174 case ColorMode::STANDARD_BT601_525:
175 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
176 case ColorMode::STANDARD_BT709:
177 case ColorMode::SRGB:
178 return false;
179 }
180 return false;
181}
182
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700183ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
184 switch (rotation) {
185 case ISurfaceComposer::eRotateNone:
186 return ui::Transform::ROT_0;
187 case ISurfaceComposer::eRotate90:
188 return ui::Transform::ROT_90;
189 case ISurfaceComposer::eRotate180:
190 return ui::Transform::ROT_180;
191 case ISurfaceComposer::eRotate270:
192 return ui::Transform::ROT_270;
193 }
194 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
195 return ui::Transform::ROT_0;
196}
197
Peiyong Linfca547f2018-07-09 13:03:33 -0700198#pragma clang diagnostic pop
199
Steven Thomasb02664d2017-07-26 18:48:28 -0700200class ConditionalLock {
201public:
202 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
203 if (lock) {
204 mMutex.lock();
205 }
206 }
207 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
208private:
209 Mutex& mMutex;
210 bool mLocked;
211};
Peiyong Linfca547f2018-07-09 13:03:33 -0700212
Peiyong Lin9d846a52018-11-05 13:18:20 -0800213// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
214bool validateCompositionDataspace(Dataspace dataspace) {
215 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
216}
217
Steven Thomasb02664d2017-07-26 18:48:28 -0700218} // namespace anonymous
219
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800220// ---------------------------------------------------------------------------
221
Mathias Agopian99b49842011-06-27 16:05:52 -0700222const String16 sHardwareTest("android.permission.HARDWARE_TEST");
223const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
224const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
225const String16 sDump("android.permission.DUMP");
226
227// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700228int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700229bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800230uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800231bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800232bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800233int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600234bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700235int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700236bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700237bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700238Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
239ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
240Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
241ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700242
Kalle Raitaa099a242017-01-11 11:17:29 -0800243std::string getHwcServiceName() {
244 char value[PROPERTY_VALUE_MAX] = {};
245 property_get("debug.sf.hwc_service_name", value, "default");
246 ALOGI("Using HWComposer service: '%s'", value);
247 return std::string(value);
248}
249
250bool useTrebleTestingOverride() {
251 char value[PROPERTY_VALUE_MAX] = {};
252 property_get("debug.sf.treble_testing_override", value, "false");
253 ALOGI("Treble testing override: '%s'", value);
254 return std::string(value) == "true";
255}
256
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800257std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
258 switch(displayColorSetting) {
259 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700260 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800261 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700262 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800263 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700264 return std::string("Enhanced");
265 default:
266 return std::string("Unknown ") +
267 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800268 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800269}
270
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700271SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800272
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700273SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
274 : mFactory(factory),
275 mPhaseOffsets(mFactory.createPhaseOffsets()),
276 mInterceptor(mFactory.createSurfaceInterceptor(this)),
277 mTimeStats(mFactory.createTimeStats()),
278 mEventQueue(mFactory.createMessageQueue()),
279 mCompositionEngine(mFactory.createCompositionEngine()) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800280
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700281SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800282 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800283
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900284 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800285
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900286 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700287
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900288 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700289
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900290 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800291
Steven Thomas050b2c82017-03-06 11:45:16 -0800292 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900293 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800294
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900295 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800296
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900297 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700298
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900299 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600300
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900301 mDefaultCompositionDataspace =
302 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
303 mWideColorGamutCompositionDataspace =
304 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
305 defaultCompositionDataspace = mDefaultCompositionDataspace;
306 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
307 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
308 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
309 wideColorGamutCompositionPixelFormat =
310 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700311
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900312 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800313
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900314 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
315 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
316 switch (tmpPrimaryDisplayOrientation) {
317 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700318 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800319 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900320 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700321 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800322 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900323 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700324 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800325 break;
326 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700327 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800328 break;
329 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700330 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800331
Sundong Ahn85131bd2019-02-18 15:51:53 +0900332 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800333
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800334 // debugging stuff...
335 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700336
Mathias Agopianb4b17302013-03-20 18:36:41 -0700337 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700338 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700339
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800340 property_get("debug.sf.showupdates", value, "0");
341 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700342
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700343 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000344
345 // DDMS debugging deprecated (b/120782499)
346 property_get("debug.sf.ddms", value, "0");
347 int debugDdms = atoi(value);
348 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700349
350 property_get("debug.sf.disable_backpressure", value, "0");
351 mPropagateBackpressure = !atoi(value);
352 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700353
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800354 property_get("debug.sf.enable_hwc_vds", value, "0");
355 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800356 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800357
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800358 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800359 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800360 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700361
Yiwei Zhang243b3782018-05-15 17:40:04 -0700362 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700363 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
364 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
365
Ana Krulece5a06e02019-03-06 17:09:03 -0800366 mUseSmart90ForVideo = use_smart_90_for_video(false);
Ana Krulecba13ab32019-02-20 14:14:12 -0800367 property_get("debug.sf.use_smart_90_for_video", value, "0");
Ana Krulece5a06e02019-03-06 17:09:03 -0800368
369 int int_value = atoi(value);
370 if (int_value) {
371 mUseSmart90ForVideo = true;
372 }
Ana Krulecba13ab32019-02-20 14:14:12 -0800373
Dan Stozaec460082018-12-17 15:35:09 -0800374 property_get("debug.sf.luma_sampling", value, "1");
375 mLumaSampling = atoi(value);
376
Ana Krulec757f63a2019-01-25 10:46:18 -0800377 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
378 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700379
Romain Guy11d63f42017-07-20 12:47:14 -0700380 // We should be reading 'persist.sys.sf.color_saturation' here
381 // but since /data may be encrypted, we need to wait until after vold
382 // comes online to attempt to read the property. The property is
383 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800384
385 if (useTrebleTestingOverride()) {
386 // Without the override SurfaceFlinger cannot connect to HIDL
387 // services that are not listed in the manifests. Considered
388 // deriving the setting from the set service name, but it
389 // would be brittle if the name that's not 'default' is used
390 // for production purposes later on.
391 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
392 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800393}
394
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800395void SurfaceFlinger::onFirstRef()
396{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800397 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800398}
399
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700400SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800401
Dan Stozac7014012014-02-14 15:03:43 -0800402void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800403{
404 // the window manager died on us. prepare its eulogy.
405
Andy McFadden13a082e2012-08-24 10:16:42 -0700406 // restore initial conditions (default device unblank, etc)
407 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800408
409 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700410 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800411}
412
Robert Carr1db73f62016-12-21 12:58:51 -0800413static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700414 status_t err = client->initCheck();
415 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800416 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800417 }
Robert Carr1db73f62016-12-21 12:58:51 -0800418 return nullptr;
419}
420
421sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
422 return initClient(new Client(this));
423}
424
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700425sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
426 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700427{
428 class DisplayToken : public BBinder {
429 sp<SurfaceFlinger> flinger;
430 virtual ~DisplayToken() {
431 // no more references, this display must be terminated
432 Mutex::Autolock _l(flinger->mStateLock);
433 flinger->mCurrentState.displays.removeItem(this);
434 flinger->setTransactionFlags(eDisplayTransactionNeeded);
435 }
436 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700437 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700438 : flinger(flinger) {
439 }
440 };
441
442 sp<BBinder> token = new DisplayToken(this);
443
444 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700445 // Display ID is assigned when virtual display is allocated by HWC.
446 DisplayDeviceState state;
447 state.isSecure = secure;
448 state.displayName = displayName;
449 mCurrentState.displays.add(token, state);
450 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700451 return token;
452}
453
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700454void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700455 Mutex::Autolock _l(mStateLock);
456
Dominik Laskowski075d3172018-05-24 15:50:06 -0700457 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
458 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700459 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700460 return;
461 }
462
Dominik Laskowski075d3172018-05-24 15:50:06 -0700463 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
464 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700465 ALOGE("destroyDisplay called for non-virtual display");
466 return;
467 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700468 mInterceptor->saveDisplayDeletion(state.sequenceId);
469 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700470 setTransactionFlags(eDisplayTransactionNeeded);
471}
472
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800473std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
474 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700475
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800476 const auto internalDisplayId = getInternalDisplayIdLocked();
477 if (!internalDisplayId) {
478 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700479 }
480
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800481 std::vector<PhysicalDisplayId> displayIds;
482 displayIds.reserve(mPhysicalDisplayTokens.size());
483 displayIds.push_back(internalDisplayId->value);
484
485 for (const auto& [id, token] : mPhysicalDisplayTokens) {
486 if (id != *internalDisplayId) {
487 displayIds.push_back(id.value);
488 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700489 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700490
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800491 return displayIds;
492}
493
494sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
495 Mutex::Autolock lock(mStateLock);
496 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700497}
498
Ady Abraham37965d42018-11-01 13:43:32 -0700499status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
500 if (!outGetColorManagement) {
501 return BAD_VALUE;
502 }
503 *outGetColorManagement = useColorManagement;
504 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700505}
506
Lloyd Pique441d5042018-10-18 16:49:51 -0700507HWComposer& SurfaceFlinger::getHwComposer() const {
508 return mCompositionEngine->getHwComposer();
509}
510
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700511renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
512 return mCompositionEngine->getRenderEngine();
513}
514
Lloyd Pique70d91362018-10-18 16:02:55 -0700515compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
516 return *mCompositionEngine.get();
517}
518
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800519void SurfaceFlinger::bootFinished()
520{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700521 if (mStartPropertySetThread->join() != NO_ERROR) {
522 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800523 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800524 const nsecs_t now = systemTime();
525 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000526 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700527
528 // wait patiently for the window manager death
529 const String16 name("window");
530 sp<IBinder> window(defaultServiceManager()->getService(name));
531 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700532 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700533 }
Robert Carr720e5062018-07-30 17:45:14 -0700534 sp<IBinder> input(defaultServiceManager()->getService(
535 String16("inputflinger")));
536 if (input == nullptr) {
537 ALOGE("Failed to link to input service");
538 } else {
539 mInputFlinger = interface_cast<IInputFlinger>(input);
540 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700541
Steven Thomas050b2c82017-03-06 11:45:16 -0800542 if (mVrFlinger) {
543 mVrFlinger->OnBootFinished();
544 }
545
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700546 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700547 // formerly we would just kill the process, but we now ask it to exit so it
548 // can choose where to stop the animation.
549 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700550
551 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
552 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
553 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700554
Ana Krulecbd6654b2019-02-15 15:18:15 -0800555 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800556 readPersistentProperties();
557 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800558
Ady Abraham97d04232019-03-05 19:48:12 -0800559 // set the refresh rate according to the policy
Alec Mouri0a1cc962019-03-14 12:33:02 -0700560 const auto& performanceRefreshRate =
Dominik Laskowski22488f62019-03-28 09:53:04 -0700561 mRefreshRateConfigs.getRefreshRate(RefreshRateType::PERFORMANCE);
Ady Abraham97d04232019-03-05 19:48:12 -0800562
Dominik Laskowski22488f62019-03-28 09:53:04 -0700563 if (performanceRefreshRate && isDisplayConfigAllowed(performanceRefreshRate->configId)) {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800564 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800565 } else {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800566 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800567 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800568 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800569}
570
Dan Stoza436ccf32018-06-21 12:10:12 -0700571uint32_t SurfaceFlinger::getNewTexture() {
572 {
573 std::lock_guard lock(mTexturePoolMutex);
574 if (!mTexturePool.empty()) {
575 uint32_t name = mTexturePool.back();
576 mTexturePool.pop_back();
577 ATRACE_INT("TexturePoolSize", mTexturePool.size());
578 return name;
579 }
580
581 // The pool was too small, so increase it for the future
582 ++mTexturePoolSize;
583 }
584
585 // The pool was empty, so we need to get a new texture name directly using a
586 // blocking call to the main thread
587 uint32_t name = 0;
588 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
589 return name;
590}
591
Mathias Agopian3f844832013-08-07 21:24:32 -0700592void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700593 std::lock_guard lock(mTexturePoolMutex);
594 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
595 // to actually delete this or not based on mTexturePoolSize
596 mTexturePool.push_back(texture);
597 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700598}
599
Wei Wangf9b05ee2017-07-19 20:59:39 -0700600// Do not call property_set on main thread which will be blocked by init
601// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700602void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700603 ALOGI( "SurfaceFlinger's main thread ready to run. "
604 "Initializing graphics H/W...");
605
Ana Krulec757f63a2019-01-25 10:46:18 -0800606 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900607
Steven Thomasb02664d2017-07-26 18:48:28 -0700608 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700609 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800610 mScheduler =
Ady Abraham09bd3922019-04-08 10:44:56 -0700611 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
612 mRefreshRateConfigs);
Ana Krulecc2870422019-01-29 19:00:58 -0800613 auto resyncCallback =
614 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800615
Ana Krulecc2870422019-01-29 19:00:58 -0800616 mAppConnectionHandle =
617 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
618 resyncCallback,
619 impl::EventThread::InterceptVSyncsCallback());
620 mSfConnectionHandle = mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
621 resyncCallback, [this](nsecs_t timestamp) {
622 mInterceptor->saveVSyncEvent(timestamp);
623 });
624
625 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
626 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
627 mSfConnectionHandle.get());
628
Kevin DuBois413287f2019-02-25 08:46:47 -0800629 mRegionSamplingThread =
630 new RegionSamplingThread(*this, *mScheduler,
631 RegionSamplingThread::EnvironmentTimingTunables());
632
Steven Thomasb02664d2017-07-26 18:48:28 -0700633 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700634 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700635 renderEngineFeature |= (useColorManagement ?
636 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700637 renderEngineFeature |= (useContextPriority ?
638 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin6a043d52019-04-01 17:18:21 -0700639 renderEngineFeature |=
640 (enable_protected_contents(false) ? renderengine::RenderEngine::ENABLE_PROTECTED_CONTEXT
641 : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700642
643 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800644 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700645 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700646 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800647 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700648
649 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
650 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700651 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
652 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800653 // Process any initial hotplug and resulting display changes.
654 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700655 const auto display = getDefaultDisplayDeviceLocked();
656 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700657 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700658 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800659
Steven Thomas050b2c82017-03-06 11:45:16 -0800660 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700661 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700662 // This callback is called from the vr flinger dispatch thread. We
663 // need to call signalTransaction(), which requires holding
664 // mStateLock when we're not on the main thread. Acquiring
665 // mStateLock from the vr flinger dispatch thread might trigger a
666 // deadlock in surface flinger (see b/66916578), so post a message
667 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700668 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700669 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
670 mVrFlingerRequestsDisplay = requestDisplay;
671 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700672 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800673 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700674 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
675 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700676 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700677 .value_or(0),
678 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800679 if (!mVrFlinger) {
680 ALOGE("Failed to start vrflinger");
681 }
682 }
683
Mathias Agopian92a979a2012-08-02 18:32:23 -0700684 // initialize our drawing state
685 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700686
Andy McFadden13a082e2012-08-24 10:16:42 -0700687 // set initial conditions (e.g. unblank default device)
688 initializeDisplays();
689
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700690 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700691
Wei Wangf9b05ee2017-07-19 20:59:39 -0700692 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700693
694 const bool presentFenceReliable =
695 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
696 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700697
698 if (mStartPropertySetThread->Start() != NO_ERROR) {
699 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800700 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800701
Ady Abraham97d04232019-03-05 19:48:12 -0800702 if (mScheduler->isIdleTimerEnabled()) {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800703 mScheduler->setChangeRefreshRateCallback(
704 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
705 Mutex::Autolock lock(mStateLock);
706 setRefreshRateTo(type, event);
707 });
Kevin DuBois36233132019-02-19 14:08:55 -0800708 }
Ady Abraham09bd3922019-04-08 10:44:56 -0700709
Dominik Laskowski22488f62019-03-28 09:53:04 -0700710 mRefreshRateConfigs.populate(getHwComposer().getConfigs(*display->getId()));
711 mRefreshRateStats.setConfigMode(getHwComposer().getActiveConfigIndex(*display->getId()));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800712
Dan Stoza9e56aa02015-11-02 13:00:03 -0800713 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700714}
715
Romain Guy11d63f42017-07-20 12:47:14 -0700716void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700717 Mutex::Autolock _l(mStateLock);
718
Romain Guy11d63f42017-07-20 12:47:14 -0700719 char value[PROPERTY_VALUE_MAX];
720
721 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800722 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700723 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800724 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100725
726 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700727 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800728
729 property_get("persist.sys.sf.color_mode", value, "0");
730 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700731}
732
Mathias Agopiana67e4182012-06-19 17:26:12 -0700733void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800734 // Start boot animation service by setting a property mailbox
735 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700736 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800737 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700738 if (mStartPropertySetThread->join() != NO_ERROR) {
739 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800740 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700741}
742
Mathias Agopian875d8e12013-06-07 15:35:48 -0700743size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700744 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700745}
746
Mathias Agopian875d8e12013-06-07 15:35:48 -0700747size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700748 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700749}
750
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800751// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800752
Jamie Gennis582270d2011-08-17 18:19:00 -0700753bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800754 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800755 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800756 return authenticateSurfaceTextureLocked(bufferProducer);
757}
758
759bool SurfaceFlinger::authenticateSurfaceTextureLocked(
760 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800761 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800762 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800763}
764
Brian Anderson6b376712017-04-04 10:51:39 -0700765status_t SurfaceFlinger::getSupportedFrameTimestamps(
766 std::vector<FrameEvent>* outSupported) const {
767 *outSupported = {
768 FrameEvent::REQUESTED_PRESENT,
769 FrameEvent::ACQUIRE,
770 FrameEvent::LATCH,
771 FrameEvent::FIRST_REFRESH_START,
772 FrameEvent::LAST_REFRESH_START,
773 FrameEvent::GPU_COMPOSITION_DONE,
774 FrameEvent::DEQUEUE_READY,
775 FrameEvent::RELEASE,
776 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700777 ConditionalLock _l(mStateLock,
778 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700779 if (!getHwComposer().hasCapability(
780 HWC2::Capability::PresentFenceIsNotReliable)) {
781 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
782 }
783 return NO_ERROR;
784}
785
Dominik Laskowski22488f62019-03-28 09:53:04 -0700786status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
787 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700788 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700789 return BAD_VALUE;
790 }
791
Dominik Laskowski22488f62019-03-28 09:53:04 -0700792 Mutex::Autolock lock(mStateLock);
793
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800794 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700795 if (!displayId) {
796 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700797 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700798
Mathias Agopian8b736f12012-08-13 17:54:26 -0700799 // TODO: Not sure if display density should handled by SF any longer
800 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700801 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700802 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700803 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800804 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700805 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700806 }
807 return density;
808 }
809 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700810 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700811 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700812 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700813 return getDensityFromProperty("ro.sf.lcd_density"); }
814 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700815
Dan Stoza7f7da322014-05-02 15:26:25 -0700816 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700817
Dominik Laskowski075d3172018-05-24 15:50:06 -0700818 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700819 DisplayInfo info = DisplayInfo();
820
Dan Stoza9e56aa02015-11-02 13:00:03 -0800821 float xdpi = hwConfig->getDpiX();
822 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700823
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700824 info.w = hwConfig->getWidth();
825 info.h = hwConfig->getHeight();
826 // Default display viewport to display width and height
827 info.viewportW = info.w;
828 info.viewportH = info.h;
829
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800830 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700831 // The density of the device is provided by a build property
832 float density = Density::getBuildDensity() / 160.0f;
833 if (density == 0) {
834 // the build doesn't provide a density -- this is wrong!
835 // use xdpi instead
836 ALOGE("ro.sf.lcd_density must be defined as a build property");
837 density = xdpi / 160.0f;
838 }
839 if (Density::getEmuDensity()) {
840 // if "qemu.sf.lcd_density" is specified, it overrides everything
841 xdpi = ydpi = density = Density::getEmuDensity();
842 density /= 160.0f;
843 }
844 info.density = density;
845
846 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700847 const auto display = getDefaultDisplayDeviceLocked();
848 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700849
850 // This is for screenrecord
851 const Rect viewport = display->getViewport();
852 if (viewport.isValid()) {
853 info.viewportW = uint32_t(viewport.getWidth());
854 info.viewportH = uint32_t(viewport.getHeight());
855 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700856 } else {
857 // TODO: where should this value come from?
858 static const int TV_DENSITY = 213;
859 info.density = TV_DENSITY / 160.0f;
860 info.orientation = 0;
861 }
862
Dan Stoza7f7da322014-05-02 15:26:25 -0700863 info.xdpi = xdpi;
864 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800865 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ady Abraham796beb02019-04-11 15:23:07 -0700866 const auto refreshRateType = mRefreshRateConfigs.getRefreshRateType(hwConfig->getId());
867 const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
868 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800869
Andy McFadden91b2ca82014-06-13 14:04:23 -0700870 // This is how far in advance a buffer must be queued for
871 // presentation at a given time. If you want a buffer to appear
872 // on the screen at time N, you must submit the buffer before
873 // (N - presentationDeadline).
874 //
875 // Normally it's one full refresh period (to give SF a chance to
876 // latch the buffer), but this can be reduced by configuring a
877 // DispSync offset. Any additional delays introduced by the hardware
878 // composer or panel must be accounted for here.
879 //
880 // We add an additional 1ms to allow for processing time and
881 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700882 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700883
884 // All non-virtual displays are currently considered secure.
885 info.secure = true;
886
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800887 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700888 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800889 std::swap(info.w, info.h);
890 }
891
Michael Wright28f24d02016-07-12 13:30:53 -0700892 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700893 }
894
Dan Stoza7f7da322014-05-02 15:26:25 -0700895 return NO_ERROR;
896}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700897
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700898status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
899 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700900 return BAD_VALUE;
901 }
902
Ana Krulecc2870422019-01-29 19:00:58 -0800903 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700904 return NO_ERROR;
905}
906
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700907int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
908 const auto display = getDisplayDevice(displayToken);
909 if (!display) {
910 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800911 return BAD_VALUE;
912 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700913
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700914 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700915}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700916
Ady Abraham03b02dd2019-03-21 15:40:11 -0700917void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800918 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800919
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800920 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800921 // config twice. However event generation config might have changed so we need to update it
922 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800923 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700924 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
925 mDesiredActiveConfig = info;
926 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800927
928 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800929 // This will trigger HWC refresh without resetting the idle timer.
930 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700931 // Start receiving vsync samples now, so that we can detect a period
932 // switch.
933 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
934 mPhaseOffsets->setRefreshRateType(info.type);
935 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
936 mVsyncModulator.onRefreshRateChangeInitiated();
937 mVsyncModulator.setPhaseOffsets(early, gl, late);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800938 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800939 mDesiredActiveConfigChanged = true;
940 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700941
942 if (mRefreshRateOverlay) {
943 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
944 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800945}
946
947status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
948 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800949
950 std::vector<int32_t> allowedConfig;
951 allowedConfig.push_back(mode);
952
953 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800954}
955
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800956void SurfaceFlinger::setActiveConfigInternal() {
957 ATRACE_CALL();
958
Dominik Laskowski22488f62019-03-28 09:53:04 -0700959 const auto display = getDefaultDisplayDeviceLocked();
960 if (!display) {
961 return;
962 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800963
Dominik Laskowski22488f62019-03-28 09:53:04 -0700964 std::lock_guard<std::mutex> lock(mActiveConfigLock);
965 mRefreshRateStats.setConfigMode(mUpcomingActiveConfig.configId);
966
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800967 display->setActiveConfig(mUpcomingActiveConfig.configId);
968
Ana Krulecc2870422019-01-29 19:00:58 -0800969 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Alec Mouri754c98a2019-03-18 18:53:42 -0700970 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Alec Mouri1c9e82b2019-03-07 12:24:05 -0800971 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
972 mVsyncModulator.setPhaseOffsets(early, gl, late);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800973 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700974
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800975 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -0800976 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
977 mUpcomingActiveConfig.configId);
978 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800979}
980
Dominik Laskowski22488f62019-03-28 09:53:04 -0700981bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -0800982 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800983 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -0700984 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800985 // fence has not signaled yet. wait for the next invalidate
Ady Abrahame1a5bcb2019-04-17 20:09:26 -0700986 mEventQueue->invalidateForHWC();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800987 return true;
988 }
989
990 // We received the present fence from the HWC, so we assume it successfully updated
991 // the config, hence we update SF.
992 mCheckPendingFence = false;
993 setActiveConfigInternal();
994 }
995
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800996 // Store the local variable to release the lock.
997 ActiveConfigInfo desiredActiveConfig;
998 {
999 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001000 if (!mDesiredActiveConfigChanged) {
1001 return false;
1002 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001003 desiredActiveConfig = mDesiredActiveConfig;
1004 }
1005
Dominik Laskowski22488f62019-03-28 09:53:04 -07001006 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001007 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1008 // display is not valid or we are already in the requested mode
1009 // on both cases there is nothing left to do
1010 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham6398a0a2019-04-18 19:30:44 -07001011 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001012 mDesiredActiveConfigChanged = false;
1013 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
1014 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001015 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001016
Ady Abraham838de062019-02-04 10:24:03 -08001017 // Desired active config was set, it is different than the config currently in use, however
1018 // allowed configs might have change by the time we process the refresh.
1019 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001020 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham838de062019-02-04 10:24:03 -08001021 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Alec Mouriecf2e0f2019-03-26 13:26:17 -07001022 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
Ady Abraham838de062019-02-04 10:24:03 -08001023 mDesiredActiveConfig.configId = display->getActiveConfig();
Ady Abraham6398a0a2019-04-18 19:30:44 -07001024 mDesiredActiveConfigChanged = false;
1025 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ady Abraham838de062019-02-04 10:24:03 -08001026 return false;
1027 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001028 mUpcomingActiveConfig = desiredActiveConfig;
1029 const auto displayId = display->getId();
1030 LOG_ALWAYS_FATAL_IF(!displayId);
1031
1032 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1033 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1034
1035 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -08001036 mCheckPendingFence = true;
Ady Abrahame1a5bcb2019-04-17 20:09:26 -07001037 mEventQueue->invalidateForHWC();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001038 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001039}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001040
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001041status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1042 Vector<ColorMode>* outColorModes) {
1043 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001044 return BAD_VALUE;
1045 }
1046
Peiyong Lina52f0292018-03-14 17:26:31 -07001047 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001048 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001049 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1050
1051 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1052 if (!displayId) {
1053 return NAME_NOT_FOUND;
1054 }
1055
Dominik Laskowski075d3172018-05-24 15:50:06 -07001056 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001057 }
Michael Wright28f24d02016-07-12 13:30:53 -07001058 outColorModes->clear();
1059 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1060
1061 return NO_ERROR;
1062}
1063
Daniel Solomon42d04562019-01-20 21:03:19 -08001064status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1065 ui::DisplayPrimaries &primaries) {
1066 if (!displayToken) {
1067 return BAD_VALUE;
1068 }
1069
1070 // Currently we only support this API for a single internal display.
1071 if (getInternalDisplayToken() != displayToken) {
1072 return BAD_VALUE;
1073 }
1074
1075 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1076 return NO_ERROR;
1077}
1078
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001079ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1080 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001081 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001082 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001083 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001084}
1085
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001086status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001087 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001088 Vector<ColorMode> modes;
1089 getDisplayColorModes(displayToken, &modes);
1090 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1091 if (mode < ColorMode::NATIVE || !exists) {
1092 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1093 decodeColorMode(mode).c_str(), mode, displayToken.get());
1094 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001095 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001096 const auto display = getDisplayDevice(displayToken);
1097 if (!display) {
1098 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1099 decodeColorMode(mode).c_str(), mode, displayToken.get());
1100 } else if (display->isVirtual()) {
1101 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1102 decodeColorMode(mode).c_str(), mode);
1103 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001104 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1105 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001106 }
1107 }));
1108
Michael Wright28f24d02016-07-12 13:30:53 -07001109 return NO_ERROR;
1110}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001111
Svetoslavd85084b2014-03-20 10:28:31 -07001112status_t SurfaceFlinger::clearAnimationFrameStats() {
1113 Mutex::Autolock _l(mStateLock);
1114 mAnimFrameTracker.clearStats();
1115 return NO_ERROR;
1116}
1117
1118status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1119 Mutex::Autolock _l(mStateLock);
1120 mAnimFrameTracker.getStats(outStats);
1121 return NO_ERROR;
1122}
1123
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001124status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1125 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001126 Mutex::Autolock _l(mStateLock);
1127
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001128 const auto display = getDisplayDeviceLocked(displayToken);
1129 if (!display) {
1130 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001131 return BAD_VALUE;
1132 }
1133
Peiyong Linfb069302018-04-25 14:34:31 -07001134 // At this point the DisplayDeivce should already be set up,
1135 // meaning the luminance information is already queried from
1136 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001137 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001138 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1139 capabilities.getDesiredMaxLuminance(),
1140 capabilities.getDesiredMaxAverageLuminance(),
1141 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001142
1143 return NO_ERROR;
1144}
1145
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001146status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1147 ui::PixelFormat* outFormat,
1148 ui::Dataspace* outDataspace,
1149 uint8_t* outComponentMask) const {
1150 if (!outFormat || !outDataspace || !outComponentMask) {
1151 return BAD_VALUE;
1152 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001153 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001154 if (!display || !display->getId()) {
1155 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1156 return BAD_VALUE;
1157 }
1158 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1159 outDataspace, outComponentMask);
1160}
1161
Kevin DuBois74e53772018-11-19 10:52:38 -08001162status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1163 bool enable, uint8_t componentMask,
1164 uint64_t maxFrames) const {
1165 const auto display = getDisplayDevice(displayToken);
1166 if (!display || !display->getId()) {
1167 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1168 return BAD_VALUE;
1169 }
1170
1171 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1172 componentMask, maxFrames);
1173}
1174
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001175status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1176 uint64_t maxFrames, uint64_t timestamp,
1177 DisplayedFrameStats* outStats) const {
1178 const auto display = getDisplayDevice(displayToken);
1179 if (!display || !display->getId()) {
1180 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1181 return BAD_VALUE;
1182 }
1183
1184 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1185 outStats);
1186}
1187
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001188status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1189 if (!outSupported) {
1190 return BAD_VALUE;
1191 }
1192 *outSupported = getRenderEngine().supportsProtectedContent();
1193 return NO_ERROR;
1194}
1195
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001196status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1197 bool* outIsWideColorDisplay) const {
1198 if (!displayToken || !outIsWideColorDisplay) {
1199 return BAD_VALUE;
1200 }
1201 Mutex::Autolock _l(mStateLock);
1202 const auto display = getDisplayDeviceLocked(displayToken);
1203 if (!display) {
1204 return BAD_VALUE;
1205 }
1206 *outIsWideColorDisplay = display->hasWideColorGamut();
1207 return NO_ERROR;
1208}
1209
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001210status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001211 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001212 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001213
Chia-I Wu90f669f2017-10-05 14:24:41 -07001214 if (mInjectVSyncs == enable) {
1215 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001216 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001217
Ana Krulecc2870422019-01-29 19:00:58 -08001218 auto resyncCallback =
1219 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001220
Ady Abraham46e2f3e2019-03-18 16:40:15 -07001221 // TODO(b/128863962): Part of the Injector should be refactored, so that it
Ana Krulec98b5b242018-08-10 15:03:23 -07001222 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001223 if (enable) {
1224 ALOGV("VSync Injections enabled");
1225 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001226 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001227 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001228 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001229 impl::EventThread::InterceptVSyncsCallback(),
1230 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001231 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001232 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001233 } else {
1234 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001235 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1236 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001237 }
1238
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001239 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001240 }));
1241
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001242 return NO_ERROR;
1243}
1244
1245status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001246 Mutex::Autolock _l(mStateLock);
1247
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001248 if (!mInjectVSyncs) {
1249 ALOGE("VSync Injections not enabled");
1250 return BAD_VALUE;
1251 }
1252 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1253 ALOGV("Injecting VSync inside SurfaceFlinger");
1254 mVSyncInjector->onInjectSyncEvent(when);
1255 }
1256 return NO_ERROR;
1257}
1258
Lloyd Pique755e3192018-01-31 16:46:15 -08001259status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1260 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001261 // Try to acquire a lock for 1s, fail gracefully
1262 const status_t err = mStateLock.timedLock(s2ns(1));
1263 const bool locked = (err == NO_ERROR);
1264 if (!locked) {
1265 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1266 return TIMED_OUT;
1267 }
1268
1269 outLayers->clear();
1270 mCurrentState.traverseInZOrder([&](Layer* layer) {
1271 outLayers->push_back(layer->getLayerDebugInfo());
1272 });
1273
1274 mStateLock.unlock();
1275 return NO_ERROR;
1276}
1277
Peiyong Linc6780972018-10-28 15:24:08 -07001278status_t SurfaceFlinger::getCompositionPreference(
1279 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1280 Dataspace* outWideColorGamutDataspace,
1281 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001282 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001283 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001284 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001285 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001286 return NO_ERROR;
1287}
1288
Dan Stozaec460082018-12-17 15:35:09 -08001289status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1290 const sp<IBinder>& stopLayerHandle,
1291 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001292 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001293 return BAD_VALUE;
1294 }
1295 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001296 return NO_ERROR;
1297}
1298
Dan Stozaec460082018-12-17 15:35:09 -08001299status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001300 if (!listener) {
1301 return BAD_VALUE;
1302 }
Dan Stozaec460082018-12-17 15:35:09 -08001303 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001304 return NO_ERROR;
1305}
Dan Gittik57e63c52019-01-18 16:37:54 +00001306
1307status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1308 bool* outSupport) const {
1309 if (!displayToken || !outSupport) {
1310 return BAD_VALUE;
1311 }
1312 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1313 if (!displayId) {
1314 return NAME_NOT_FOUND;
1315 }
1316 *outSupport =
1317 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1318 return NO_ERROR;
1319}
1320
1321status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1322 float brightness) const {
1323 if (!displayToken) {
1324 return BAD_VALUE;
1325 }
1326 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1327 if (!displayId) {
1328 return NAME_NOT_FOUND;
1329 }
1330 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1331}
1332
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001333// ----------------------------------------------------------------------------
1334
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001335sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1336 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulecc2870422019-01-29 19:00:58 -08001337 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001338 Mutex::Autolock lock(mStateLock);
1339 return getVsyncPeriod();
1340 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001341
Ana Krulecc2870422019-01-29 19:00:58 -08001342 const auto& handle =
1343 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001344
Ana Krulecc2870422019-01-29 19:00:58 -08001345 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Mathias Agopianbb641242010-05-18 17:06:55 -07001346}
1347
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001348// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001349
1350void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001351 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001352}
1353
1354void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001355 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001356}
1357
1358void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001359 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001360}
1361
1362void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001363 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001364 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001365}
1366
1367status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001368 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001369 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001370}
1371
1372status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001373 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001374 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001375 if (res == NO_ERROR) {
1376 msg->wait();
1377 }
1378 return res;
1379}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001380
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001381void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001382 do {
1383 waitForEvent();
1384 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001385}
1386
Dominik Laskowski83b88212018-12-11 13:34:06 -08001387nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001388 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001389 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1390 return 0;
1391 }
1392
1393 const auto config = getHwComposer().getActiveConfig(*displayId);
1394 return config ? config->getVsyncPeriod() : 0;
1395}
1396
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001397void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1398 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001399 ATRACE_NAME("SF onVsync");
1400
Steven Thomas3cfac282017-02-06 12:29:30 -08001401 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001402 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001403 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001404 return;
1405 }
1406
Dominik Laskowski075d3172018-05-24 15:50:06 -07001407 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001408 return;
1409 }
1410
Dominik Laskowski075d3172018-05-24 15:50:06 -07001411 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001412 // For now, we don't do anything with external display vsyncs.
1413 return;
1414 }
1415
Alec Mouri754c98a2019-03-18 18:53:42 -07001416 bool periodChanged = false;
1417 mScheduler->addResyncSample(timestamp, &periodChanged);
1418 if (periodChanged) {
1419 mVsyncModulator.onRefreshRateChangeDetected();
1420 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001421}
1422
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001423void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001424 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1425 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001426}
1427
Dominik Laskowski22488f62019-03-28 09:53:04 -07001428bool SurfaceFlinger::isDisplayConfigAllowed(int32_t configId) {
1429 return mAllowedDisplayConfigs.empty() || mAllowedDisplayConfigs.count(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001430}
1431
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001432void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001433 const auto display = getDefaultDisplayDeviceLocked();
1434 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001435 return;
1436 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001437 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001438
Ana Krulec7d1d6832018-12-27 11:10:09 -08001439 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowski22488f62019-03-28 09:53:04 -07001440 const auto& refreshRateConfig = mRefreshRateConfigs.getRefreshRate(refreshRate);
Alec Mouri0a1cc962019-03-14 12:33:02 -07001441 if (!refreshRateConfig) {
1442 ALOGV("Skipping refresh rate change request for unsupported rate.");
Ady Abraham1902d072019-03-01 17:18:59 -08001443 return;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001444 }
Ady Abraham1902d072019-03-01 17:18:59 -08001445
Alec Mouri0a1cc962019-03-14 12:33:02 -07001446 const int desiredConfigId = refreshRateConfig->configId;
1447
Dominik Laskowski22488f62019-03-28 09:53:04 -07001448 if (!isDisplayConfigAllowed(desiredConfigId)) {
Ady Abraham1902d072019-03-01 17:18:59 -08001449 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1450 return;
1451 }
1452
Dominik Laskowski22488f62019-03-28 09:53:04 -07001453 setDesiredActiveConfig({refreshRate, desiredConfigId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001454}
1455
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001456void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001457 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001458 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001459 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001460
Lloyd Piqueba04e622017-12-14 17:11:26 -08001461 // Ignore events that do not have the right sequenceId.
1462 if (sequenceId != getBE().mComposerSequenceId) {
1463 return;
1464 }
1465
Steven Thomasb02664d2017-07-26 18:48:28 -07001466 // Only lock if we're not on the main thread. This function is normally
1467 // called on a hwbinder thread, but for the primary display it's called on
1468 // the main thread with the state lock already held, so don't attempt to
1469 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001470 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001471
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001472 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001473
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001474 if (std::this_thread::get_id() == mMainThreadId) {
1475 // Process all pending hot plug events immediately if we are on the main thread.
1476 processDisplayHotplugEventsLocked();
1477 }
1478
Lloyd Piqueba04e622017-12-14 17:11:26 -08001479 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001480}
1481
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001482void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001483 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001484 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001485 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001486 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001487 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001488}
1489
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001490void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001491 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001492 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001493 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001494 getHwComposer().setVsyncEnabled(*displayId,
1495 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1496 }
Mathias Agopian86303202012-07-24 22:46:10 -07001497}
1498
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001499// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001500void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001501 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001502 // Clear the drawing state so that the logic inside of
1503 // handleTransactionLocked will fire. It will determine the delta between
1504 // mCurrentState and mDrawingState and re-apply all changes when we make the
1505 // transition.
1506 mDrawingState.displays.clear();
1507 mDisplays.clear();
1508}
1509
Steven Thomas050b2c82017-03-06 11:45:16 -08001510void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001511 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001512 if (!mVrFlinger)
1513 return;
1514 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001515 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001516 return;
1517 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001518
Lloyd Pique441d5042018-10-18 16:49:51 -07001519 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001520 ALOGE("Vr flinger is only supported for remote hardware composer"
1521 " service connections. Ignoring request to transition to vr"
1522 " flinger.");
1523 mVrFlingerRequestsDisplay = false;
1524 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001525 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001526
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001527 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001528
Steven Thomas0123ac62018-07-12 11:32:34 -07001529 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001530 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001531
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001532 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001533
1534 // Clear out all the output layers from the composition engine for all
1535 // displays before destroying the hardware composer interface. This ensures
1536 // any HWC layers are destroyed through that interface before it becomes
1537 // invalid.
1538 for (const auto& [token, displayDevice] : mDisplays) {
1539 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1540 compositionengine::Output::OutputLayers());
1541 }
1542
Steven Thomas0123ac62018-07-12 11:32:34 -07001543 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1544 // called below. Clear the reference now so we don't accidentally use it
1545 // later.
1546 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001547
Steven Thomasb02664d2017-07-26 18:48:28 -07001548 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001549 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001550 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001551
Steven Thomasb02664d2017-07-26 18:48:28 -07001552 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001553 // Delete the current instance before creating the new one
1554 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1555 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1556 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1557 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001558
Lloyd Pique441d5042018-10-18 16:49:51 -07001559 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001560 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001561
1562 if (vrFlingerRequestsDisplay) {
1563 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001564 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001565
1566 mVisibleRegionsDirty = true;
1567 invalidateHwcGeometry();
1568
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001569 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001570 display = getDefaultDisplayDeviceLocked();
1571 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001572 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001573
Steven Thomasb02664d2017-07-26 18:48:28 -07001574 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001575 const nsecs_t vsyncPeriod = getVsyncPeriod();
1576 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001577
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001578 // The present fences returned from vr_hwc are not an accurate
1579 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001580 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001581
Steven Thomasb02664d2017-07-26 18:48:28 -07001582 // Use phase of 0 since phase is not known.
1583 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001584 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001585 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001586
Ana Krulecc2870422019-01-29 19:00:58 -08001587 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001588
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001589 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001590 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001591}
1592
Ady Abrahambe0f9482019-04-24 15:41:53 -07001593bool SurfaceFlinger::previousFrameMissed() NO_THREAD_SAFETY_ANALYSIS {
1594 // We are storing the last 2 present fences. If sf's phase offset is to be
1595 // woken up before the actual vsync but targeting the next vsync, we need to check
1596 // fence N-2
1597 const sp<Fence>& fence =
1598 mVsyncModulator.getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
1599 ? mPreviousPresentFences[0]
1600 : mPreviousPresentFences[1];
1601
1602 return fence != Fence::NO_FENCE && (fence->getStatus() == Fence::Status::Unsignaled);
1603}
1604
Dominik Laskowski22488f62019-03-28 09:53:04 -07001605void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001606 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001607 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001608 case MessageQueue::INVALIDATE: {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001609 bool frameMissed = previousFrameMissed();
Alec Mouricc0fc602019-02-26 21:45:19 -08001610 bool hwcFrameMissed = mHadDeviceComposition && frameMissed;
1611 bool gpuFrameMissed = mHadClientComposition && frameMissed;
1612 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
1613 ATRACE_INT("HwcFrameMissed", static_cast<int>(hwcFrameMissed));
1614 ATRACE_INT("GpuFrameMissed", static_cast<int>(gpuFrameMissed));
1615 if (frameMissed) {
1616 mFrameMissedCount++;
1617 mTimeStats->incrementMissedFrames();
1618 }
1619
Alec Mouri40189b02019-03-05 15:07:54 -08001620 if (hwcFrameMissed) {
1621 mHwcFrameMissedCount++;
1622 }
1623
1624 if (gpuFrameMissed) {
1625 mGpuFrameMissedCount++;
1626 }
1627
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001628 if (mUseSmart90ForVideo) {
1629 // This call is made each time SF wakes up and creates a new frame. It is part
1630 // of video detection feature.
Ady Abraham09bd3922019-04-08 10:44:56 -07001631 mScheduler->updateFpsBasedOnContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001632 }
1633
Ady Abrahamb838aed2019-02-12 15:30:16 -08001634 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001635 break;
1636 }
1637
Alec Mourife3dc942019-02-12 14:19:18 -08001638 // For now, only propagate backpressure when missing a hwc frame.
Alec Mourib0f45822019-05-06 11:01:35 -07001639 if (hwcFrameMissed && !gpuFrameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001640 if (mPropagateBackpressure) {
1641 signalLayerUpdate();
1642 break;
1643 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001644 }
Dan Stoza50182882016-07-08 12:02:20 -07001645
Steven Thomas050b2c82017-03-06 11:45:16 -08001646 // Now that we're going to make it to the handleMessageTransaction()
1647 // call below it's safe to call updateVrFlinger(), which will
1648 // potentially trigger a display handoff.
1649 updateVrFlinger();
1650
Dan Stoza6b9454d2014-11-07 16:00:59 -08001651 bool refreshNeeded = handleMessageTransaction();
1652 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001653
1654 updateCursorAsync();
1655 updateInputFlinger();
1656
Dan Stoza58784442014-12-02 16:58:17 -08001657 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001658 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001659 // Signal a refresh if a transaction modified the window state,
1660 // a new buffer was latched, or if HWC has requested a full
1661 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001662 signalRefresh();
1663 }
1664 break;
1665 }
1666 case MessageQueue::REFRESH: {
1667 handleMessageRefresh();
1668 break;
1669 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001670 }
1671}
1672
Dan Stoza6b9454d2014-11-07 16:00:59 -08001673bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001674 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001675 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001676
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001677 bool flushedATransaction = flushTransactionQueues();
1678
1679 bool runHandleTransaction = transactionFlags &&
1680 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1681
1682 if (runHandleTransaction) {
1683 handleTransaction(eTransactionMask);
1684 } else {
1685 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001686 }
1687
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001688 if (transactionFlushNeeded()) {
1689 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001690 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001691
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001692 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001693}
1694
Mathias Agopian4fec8732012-06-29 14:12:52 -07001695void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001696 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001697
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001698 mRefreshPending = false;
1699
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001700 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001701 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001702 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001703 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001704 for (const auto& [token, display] : mDisplays) {
1705 beginFrame(display);
1706 prepareFrame(display);
1707 doDebugFlashRegions(display, repaintEverything);
1708 doComposition(display, repaintEverything);
1709 }
1710
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001711 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001712
1713 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001714 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001715
Dan Stozabfbffeb2016-07-21 14:49:33 -07001716 mHadClientComposition = false;
Alec Mouricc0fc602019-02-26 21:45:19 -08001717 mHadDeviceComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001718 for (const auto& [token, displayDevice] : mDisplays) {
1719 auto display = displayDevice->getCompositionDisplay();
1720 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001721 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001722 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Alec Mouricc0fc602019-02-26 21:45:19 -08001723 mHadDeviceComposition =
1724 mHadDeviceComposition || getHwComposer().hasDeviceComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001725 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001726
Jorim Jaggi90535212018-05-23 23:44:06 +02001727 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001728
David Sodman7e4ae112018-02-09 15:02:28 -08001729 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001730}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001731
David Sodmanfa9b2af2017-12-24 13:28:59 -08001732
1733bool SurfaceFlinger::handleMessageInvalidate() {
1734 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001735 bool refreshNeeded = handlePageFlip();
1736
Vishnu Nair4351ad52019-02-11 14:13:02 -08001737 if (mVisibleRegionsDirty) {
1738 computeLayerBounds();
Nataniel Borges2b796da2019-02-15 13:32:18 -08001739 if (mTracingEnabled) {
1740 mTracing.notify("visibleRegionsDirty");
1741 }
Vishnu Nair4351ad52019-02-11 14:13:02 -08001742 }
1743
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001744 for (auto& layer : mLayersPendingRefresh) {
1745 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001746 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001747 invalidateLayerStack(layer, visibleReg);
1748 }
1749 mLayersPendingRefresh.clear();
1750 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001751}
1752
David Sodman79bba0e2018-08-05 18:07:49 -07001753void SurfaceFlinger::calculateWorkingSet() {
1754 ATRACE_CALL();
1755 ALOGV(__FUNCTION__);
1756
David Sodman79bba0e2018-08-05 18:07:49 -07001757 // build the h/w work list
1758 if (CC_UNLIKELY(mGeometryInvalid)) {
1759 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001760 for (const auto& [token, displayDevice] : mDisplays) {
1761 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001762
Lloyd Piquea83776c2019-01-29 18:42:32 -08001763 uint32_t zOrder = 0;
David Sodman79bba0e2018-08-05 18:07:49 -07001764
Lloyd Piquea83776c2019-01-29 18:42:32 -08001765 for (auto& layer : display->getOutputLayersOrderedByZ()) {
1766 auto& compositionState = layer->editState();
1767 compositionState.forceClientComposition = false;
1768 if (!compositionState.hwc || mDebugDisableHWC || mDebugRegion) {
1769 compositionState.forceClientComposition = true;
David Sodman79bba0e2018-08-05 18:07:49 -07001770 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001771
Lloyd Piquea83776c2019-01-29 18:42:32 -08001772 // The output Z order is set here based on a simple counter.
1773 compositionState.z = zOrder++;
1774
1775 // Update the display independent composition state. This goes
1776 // to the general composition layer state structure.
1777 // TODO: Do this once per compositionengine::CompositionLayer.
1778 layer->getLayerFE().latchCompositionState(layer->getLayer().editState().frontEnd,
1779 true);
1780
1781 // Recalculate the geometry state of the output layer.
1782 layer->updateCompositionState(true);
1783
1784 // Write the updated geometry state to the HWC
1785 layer->writeStateToHWC(true);
David Sodman79bba0e2018-08-05 18:07:49 -07001786 }
1787 }
1788 }
1789
1790 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001791 for (const auto& [token, displayDevice] : mDisplays) {
1792 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001793 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001794 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001795 continue;
1796 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001797 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001798
1799 if (mDrawingState.colorMatrixChanged) {
1800 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001801 }
Peiyong Linc502cb72019-03-01 15:00:23 -08001802 Dataspace targetDataspace = Dataspace::UNKNOWN;
1803 if (useColorManagement) {
1804 ColorMode colorMode;
1805 RenderIntent renderIntent;
1806 pickColorMode(displayDevice, &colorMode, &targetDataspace, &renderIntent);
1807 display->setColorMode(colorMode, targetDataspace, renderIntent);
1808 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001809 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001810 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001811 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001812 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1813 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001814 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001815 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001816 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1817 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001818 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001819 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001820 }
1821
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001822 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001823 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001824 }
1825
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001826 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001827 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001828 layer->setCompositionType(displayDevice,
1829 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001830 continue;
1831 }
1832
Lloyd Pique32cbe282018-10-19 13:09:22 -07001833 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001834 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Peiyong Lin34ea5b92019-03-15 18:40:15 -07001835 displayDevice->getSupportedPerFrameMetadata(),
1836 isHdrColorMode(displayState.colorMode) ? Dataspace::UNKNOWN
1837 : targetDataspace);
David Sodman79bba0e2018-08-05 18:07:49 -07001838 }
1839 }
1840
1841 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001842
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001843 for (const auto& [token, displayDevice] : mDisplays) {
1844 auto display = displayDevice->getCompositionDisplay();
1845 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Lloyd Pique0b785d82018-12-04 17:25:27 -08001846 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1847 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1848 layer->getCompositionType(displayDevice));
David Sodmanba340492018-08-05 21:51:33 -07001849 }
1850 }
David Sodman79bba0e2018-08-05 18:07:49 -07001851}
1852
Lloyd Pique32cbe282018-10-19 13:09:22 -07001853void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1854 bool repaintEverything) {
1855 auto display = displayDevice->getCompositionDisplay();
1856 const auto& displayState = display->getState();
1857
Mathias Agopiancd60f992012-08-16 16:28:27 -07001858 // is debugging enabled
1859 if (CC_LIKELY(!mDebugRegion))
1860 return;
1861
Lloyd Pique32cbe282018-10-19 13:09:22 -07001862 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001863 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001864 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001865 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001866 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001867 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001868 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001869
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001870 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001871 }
1872 }
1873
Lloyd Pique32cbe282018-10-19 13:09:22 -07001874 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001875
1876 if (mDebugRegion > 1) {
1877 usleep(mDebugRegion * 1000);
1878 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001879
Lloyd Pique32cbe282018-10-19 13:09:22 -07001880 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001881}
1882
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001883void SurfaceFlinger::logLayerStats() {
1884 ATRACE_CALL();
1885 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001886 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001887 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001888 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001889 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001890 }
1891 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001892
1893 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001894 }
1895}
1896
David Sodman2b406362017-12-15 13:33:47 -08001897void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001898{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001899 ATRACE_CALL();
1900 ALOGV("preComposition");
1901
David Sodman2b406362017-12-15 13:33:47 -08001902 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1903
Mathias Agopiancd60f992012-08-16 16:28:27 -07001904 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001905 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001906 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001907 needExtraInvalidate = true;
1908 }
Robert Carr2047fae2016-11-28 14:09:09 -08001909 });
1910
Mathias Agopiancd60f992012-08-16 16:28:27 -07001911 if (needExtraInvalidate) {
1912 signalLayerUpdate();
1913 }
1914}
1915
Ana Krulece588e312018-09-18 12:32:24 -07001916void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1917 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001918 // Update queue of past composite+present times and determine the
1919 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001920 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001921 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001922 while (!getBE().mCompositePresentTimes.empty()) {
1923 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001924 // Cached values should have been updated before calling this method,
1925 // which helps avoid duplicate syscalls.
1926 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1927 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1928 break;
1929 }
1930 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001931 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001932 }
1933
1934 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001935 while (getBE().mCompositePresentTimes.size() > 16) {
1936 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001937 }
1938
Ana Krulece588e312018-09-18 12:32:24 -07001939 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001940}
1941
Ana Krulece588e312018-09-18 12:32:24 -07001942void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1943 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001944 // Integer division and modulo round toward 0 not -inf, so we need to
1945 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001946 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1947 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1948 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001949
Ana Krulec757f63a2019-01-25 10:46:18 -08001950 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001951 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001952 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001953 }
1954
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001955 // Snap the latency to a value that removes scheduling jitter from the
1956 // composition and present times, which often have >1ms of jitter.
1957 // Reducing jitter is important if an app attempts to extrapolate
1958 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001959 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001960 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001961 nsecs_t bias = stats.vsyncPeriod / 2;
1962 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1963 nsecs_t snappedCompositeToPresentLatency =
1964 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001965
David Sodman99974d22017-11-28 12:04:33 -08001966 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001967 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1968 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001969 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001970}
1971
David Sodman2b406362017-12-15 13:33:47 -08001972void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001973{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001974 ATRACE_CALL();
1975 ALOGV("postComposition");
1976
Brian Anderson3546a3f2016-07-14 11:51:14 -07001977 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001978 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001979 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001980 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001981 }
1982
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001983 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07001984 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001985
David Sodman73beded2017-11-15 11:56:06 -08001986 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001987 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001988 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001989 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07001990 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
1991 ->getRenderSurface()
1992 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001993 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001994 } else {
1995 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1996 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001997
David Sodman73beded2017-11-15 11:56:06 -08001998 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001999 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2000 mPreviousPresentFences[0] = displayDevice
2001 ? getHwComposer().getPresentFence(*displayDevice->getId())
2002 : Fence::NO_FENCE;
2003 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002004 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002005
Ana Krulece588e312018-09-18 12:32:24 -07002006 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002007 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002008
David Sodman2b406362017-12-15 13:33:47 -08002009 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002010 // when we started doing work for this frame, but that should be okay
2011 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002012 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002013 CompositorTiming compositorTiming;
2014 {
David Sodman99974d22017-11-28 12:04:33 -08002015 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2016 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002017 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002018
Robert Carr2047fae2016-11-28 14:09:09 -08002019 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002020 bool frameLatched =
2021 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2022 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002023 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002024 recordBufferingStats(layer->getName().string(),
2025 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002026 }
Robert Carr2047fae2016-11-28 14:09:09 -08002027 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002028
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002029 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002030 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002031 }
2032
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002033 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002034 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2035 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002036 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002037 }
2038 }
2039
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002040 if (mAnimCompositionPending) {
2041 mAnimCompositionPending = false;
2042
Brian Anderson4e606e32017-03-16 15:34:57 -07002043 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002044 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002045 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002046 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002047 // The HWC doesn't support present fences, so use the refresh
2048 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002049 const nsecs_t presentTime =
2050 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002051 mAnimFrameTracker.setActualPresentTime(presentTime);
2052 }
2053 mAnimFrameTracker.advanceFrame();
2054 }
Dan Stozab90cf072015-03-05 11:05:59 -08002055
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002056 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002057 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002058 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002059 }
2060
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002061 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002062
Lloyd Pique32cbe282018-10-19 13:09:22 -07002063 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2064 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002065 return;
2066 }
2067
2068 nsecs_t currentTime = systemTime();
2069 if (mHasPoweredOff) {
2070 mHasPoweredOff = false;
2071 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002072 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002073 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002074 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2075 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002076 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002077 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002078 }
David Sodman4a36e932017-11-07 14:29:47 -08002079 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002080 }
David Sodman4a36e932017-11-07 14:29:47 -08002081 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002082
2083 {
2084 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002085 if (mTexturePool.size() < mTexturePoolSize) {
2086 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002087 const size_t offset = mTexturePool.size();
2088 mTexturePool.resize(mTexturePoolSize);
2089 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2090 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002091 } else if (mTexturePool.size() > mTexturePoolSize) {
2092 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2093 const size_t offset = mTexturePoolSize;
2094 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2095 mTexturePool.resize(mTexturePoolSize);
2096 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002097 }
2098 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002099
Ady Abrahambe0f9482019-04-24 15:41:53 -07002100 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Walle2ffb422018-10-12 11:33:52 -07002101 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002102
Kevin DuBois413287f2019-02-25 08:46:47 -08002103 if (mLumaSampling && mRegionSamplingThread) {
2104 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002105 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002106
2107 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2108 // side-effect of getTotalSize(), so we check that again here
2109 if (ATRACE_ENABLED()) {
2110 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2111 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002112}
2113
Vishnu Nair4351ad52019-02-11 14:13:02 -08002114void SurfaceFlinger::computeLayerBounds() {
2115 for (const auto& pair : mDisplays) {
2116 const auto& displayDevice = pair.second;
2117 const auto display = displayDevice->getCompositionDisplay();
2118 for (const auto& layer : mDrawingState.layersSortedByZ) {
2119 // only consider the layers on the given layer stack
2120 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002121 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002122 }
2123
2124 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2125 }
2126 }
2127}
2128
Mathias Agopiancd60f992012-08-16 16:28:27 -07002129void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002130 ATRACE_CALL();
2131 ALOGV("rebuildLayerStacks");
2132
Mathias Agopiancd60f992012-08-16 16:28:27 -07002133 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002134 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002135 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002136 mVisibleRegionsDirty = false;
2137 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002138
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002139 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002140 const auto& displayDevice = pair.second;
2141 auto display = displayDevice->getCompositionDisplay();
2142 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002143 Region opaqueRegion;
2144 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002145 compositionengine::Output::OutputLayers layersSortedByZ;
2146 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002147 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002148 const ui::Transform& tr = displayState.transform;
2149 const Rect bounds = displayState.bounds;
2150 if (displayState.isEnabled) {
2151 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002152
Jeff Sharkey76488112017-02-27 14:15:18 -07002153 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002154 auto compositionLayer = layer->getCompositionLayer();
2155 if (compositionLayer == nullptr) {
2156 return;
2157 }
2158
Lloyd Pique32cbe282018-10-19 13:09:22 -07002159 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002160 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2161 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2162
Lloyd Pique07e33212018-12-18 16:33:37 -08002163 bool needsOutputLayer = false;
2164
Lloyd Piqueef36b002019-01-23 17:52:04 -08002165 if (display->belongsInOutput(layer->getLayerStack(),
2166 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002167 Region drawRegion(tr.transform(
2168 layer->visibleNonTransparentRegion));
2169 drawRegion.andSelf(bounds);
2170 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002171 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002172 }
Chia-I Wu83806892017-11-16 10:50:20 -08002173 }
2174
Lloyd Pique07e33212018-12-18 16:33:37 -08002175 if (needsOutputLayer) {
2176 layersSortedByZ.emplace_back(
2177 display->getOrCreateOutputLayer(displayId, compositionLayer,
2178 layerFE));
2179 deprecated_layersSortedByZ.add(layer);
2180
2181 auto& outputLayerState = layersSortedByZ.back()->editState();
2182 outputLayerState.visibleRegion =
2183 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2184 } else if (displayId) {
2185 // For layers that are being removed from a HWC display,
2186 // and that have queued frames, add them to a a list of
2187 // released layers so we can properly set a fence.
2188 bool hasExistingOutputLayer =
2189 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2190 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2191 mLayersWithQueuedFrames.cend(),
2192 layer) != mLayersWithQueuedFrames.cend();
2193
2194 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002195 layersNeedingFences.add(layer);
2196 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002197 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002198 });
2199 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002200
2201 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2202
2203 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002204 displayDevice->setLayersNeedingFences(layersNeedingFences);
2205
2206 Region undefinedRegion{bounds};
2207 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2208
2209 display->editState().undefinedRegion = undefinedRegion;
2210 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002211 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002212 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002213}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002214
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002215// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002216// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002217// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002218// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002219// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002220// The returned HDR data space is one of
2221// - Dataspace::UNKNOWN
2222// - Dataspace::BT2020_HLG
2223// - Dataspace::BT2020_PQ
Peiyong Lin03912882019-04-16 15:34:46 -07002224Dataspace SurfaceFlinger::getBestDataspace(const sp<DisplayDevice>& display,
2225 Dataspace* outHdrDataSpace,
2226 bool* outIsHdrClientComposition) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002227 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002228 *outHdrDataSpace = Dataspace::UNKNOWN;
2229
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002230 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002231 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002232 case Dataspace::V0_SCRGB:
2233 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002234 case Dataspace::BT2020:
2235 case Dataspace::BT2020_ITU:
2236 case Dataspace::BT2020_LINEAR:
2237 case Dataspace::DISPLAY_BT2020:
2238 bestDataSpace = Dataspace::DISPLAY_BT2020;
2239 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002240 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002241 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002242 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002243 case Dataspace::BT2020_PQ:
2244 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002245 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002246 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lin03912882019-04-16 15:34:46 -07002247 *outIsHdrClientComposition = layer->getForceClientComposition(display);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002248 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002249 case Dataspace::BT2020_HLG:
2250 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002251 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002252 // When there's mixed PQ content and HLG content, we set the HDR
2253 // data space to be BT2020_PQ and convert HLG to PQ.
2254 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2255 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002256 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002257 break;
2258 default:
2259 break;
2260 }
Romain Guy54f154a2017-10-24 21:40:32 +01002261 }
2262
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002263 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002264}
2265
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002266// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002267void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2268 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002269 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2270 *outMode = ColorMode::NATIVE;
2271 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002272 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002273 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002274 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002275
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002276 Dataspace hdrDataSpace;
Peiyong Lin03912882019-04-16 15:34:46 -07002277 bool isHdrClientComposition = false;
2278 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace, &isHdrClientComposition);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002279
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002280 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2281
Peiyong Lina3ea5592019-02-10 14:45:00 -08002282 switch (mForceColorMode) {
2283 case ColorMode::SRGB:
2284 bestDataSpace = Dataspace::V0_SRGB;
2285 break;
2286 case ColorMode::DISPLAY_P3:
2287 bestDataSpace = Dataspace::DISPLAY_P3;
2288 break;
2289 default:
2290 break;
2291 }
2292
Peiyong Lindfde5112018-06-05 10:58:41 -07002293 // respect hdrDataSpace only when there is no legacy HDR support
Peiyong Lin03912882019-04-16 15:34:46 -07002294 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
2295 !profile->hasLegacyHdrSupport(hdrDataSpace) && !isHdrClientComposition;
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002296 if (isHdr) {
2297 bestDataSpace = hdrDataSpace;
2298 }
2299
Chia-I Wu0d711262018-05-21 15:19:35 -07002300 RenderIntent intent;
2301 switch (mDisplayColorSetting) {
2302 case DisplayColorSetting::MANAGED:
2303 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002304 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002305 break;
2306 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002307 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002308 break;
2309 default: // vendor display color setting
2310 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2311 break;
2312 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002313
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002314 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002315}
2316
Lloyd Pique32cbe282018-10-19 13:09:22 -07002317void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2318 auto display = displayDevice->getCompositionDisplay();
2319 const auto& displayState = display->getState();
2320
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002321 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002322 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2323 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002324
David Sodmanfa9b2af2017-12-24 13:28:59 -08002325 // If nothing has changed (!dirty), don't recompose.
2326 // If something changed, but we don't currently have any visible layers,
2327 // and didn't when we last did a composition, then skip it this time.
2328 // The second rule does two things:
2329 // - When all layers are removed from a display, we'll emit one black
2330 // frame, then nothing more until we get new layers.
2331 // - When a display is created with a private layer stack, we won't
2332 // emit any black frames until a layer is added to the layer stack.
2333 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002334
Dominik Laskowski075d3172018-05-24 15:50:06 -07002335 const char flagPrefix[] = {'-', '+'};
2336 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002337 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2338 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2339 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2340 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002341
Lloyd Pique31cb2942018-10-19 17:23:03 -07002342 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002343
David Sodmanfa9b2af2017-12-24 13:28:59 -08002344 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002345 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002346 }
2347}
2348
Lloyd Pique32cbe282018-10-19 13:09:22 -07002349void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2350 auto display = displayDevice->getCompositionDisplay();
2351 const auto& displayState = display->getState();
2352
2353 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002354 return;
David Sodman2b406362017-12-15 13:33:47 -08002355 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002356
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002357 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002358 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002359 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002360}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002361
Lloyd Pique32cbe282018-10-19 13:09:22 -07002362void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002363 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002364 ALOGV("doComposition");
2365
Lloyd Pique32cbe282018-10-19 13:09:22 -07002366 auto display = displayDevice->getCompositionDisplay();
2367 const auto& displayState = display->getState();
2368
2369 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002370 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002371 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002372
David Sodmanfa9b2af2017-12-24 13:28:59 -08002373 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002374 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002375
Lloyd Pique32cbe282018-10-19 13:09:22 -07002376 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002377 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002378 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002379 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002380}
2381
David Sodmanfa9b2af2017-12-24 13:28:59 -08002382void SurfaceFlinger::postFrame()
2383{
2384 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002385 const auto display = getDefaultDisplayDeviceLocked();
2386 if (display && getHwComposer().isConnected(*display->getId())) {
2387 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002388 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2389 logFrameStats();
2390 }
2391 }
2392}
2393
Lloyd Pique32cbe282018-10-19 13:09:22 -07002394void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002395 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002396 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002397
Lloyd Pique32cbe282018-10-19 13:09:22 -07002398 auto display = displayDevice->getCompositionDisplay();
2399 const auto& displayState = display->getState();
2400 const auto displayId = display->getId();
2401
Lloyd Pique32cbe282018-10-19 13:09:22 -07002402 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002403 if (displayId) {
2404 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002405 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002406 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002407 for (auto& layer : display->getOutputLayersOrderedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002408 sp<Fence> releaseFence = Fence::NO_FENCE;
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002409 bool usedClientComposition = true;
David Sodman15094112018-10-11 09:39:37 -07002410
Chia-I Wu7b549592017-11-15 09:14:57 -08002411 // The layer buffer from the previous frame (if any) is released
2412 // by HWC only when the release fence from this frame (if any) is
2413 // signaled. Always get the release fence from HWC first.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002414 if (layer->getState().hwc) {
2415 const auto& hwcState = *layer->getState().hwc;
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002416 releaseFence =
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002417 getHwComposer().getLayerReleaseFence(*displayId, hwcState.hwcLayer.get());
2418 usedClientComposition =
2419 hwcState.hwcCompositionType == Hwc2::IComposerClient::Composition::CLIENT;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002420 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002421
2422 // If the layer was client composited in the previous frame, we
2423 // need to merge with the previous client target acquire fence.
2424 // Since we do not track that, always merge with the current
2425 // client target acquire fence when it is available, even though
2426 // this is suboptimal.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002427 if (usedClientComposition) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002428 releaseFence =
2429 Fence::merge("LayerRelease", releaseFence,
2430 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002431 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002432
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002433 layer->getLayerFE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002434 }
Chia-I Wu83806892017-11-16 10:50:20 -08002435
2436 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002437 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002438 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002439 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002440 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002441 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002442 for (auto& layer : displayDevice->getLayersNeedingFences()) {
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002443 layer->getCompositionLayer()->getLayerFE()->onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002444 }
2445 }
2446
Dominik Laskowski075d3172018-05-24 15:50:06 -07002447 if (displayId) {
2448 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002449 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002450 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002451}
2452
Mathias Agopian87baae12012-07-31 12:38:26 -07002453void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002454{
Mathias Agopian841cde52012-03-01 15:44:37 -08002455 ATRACE_CALL();
2456
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002457 // here we keep a copy of the drawing state (that is the state that's
2458 // going to be overwritten by handleTransactionLocked()) outside of
2459 // mStateLock so that the side-effects of the State assignment
2460 // don't happen with mStateLock held (which can cause deadlocks).
2461 State drawingState(mDrawingState);
2462
Mathias Agopianca4d3602011-05-19 15:38:14 -07002463 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002464 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002465
Mathias Agopianca4d3602011-05-19 15:38:14 -07002466 // Here we're guaranteed that some transaction flags are set
2467 // so we can call handleTransactionLocked() unconditionally.
2468 // We call getTransactionFlags(), which will also clear the flags,
2469 // with mStateLock held to guarantee that mCurrentState won't change
2470 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002471
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002472 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002473 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002474 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002475
Mathias Agopianca4d3602011-05-19 15:38:14 -07002476 mDebugInTransaction = 0;
2477 invalidateHwcGeometry();
2478 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002479}
2480
Lloyd Piqueba04e622017-12-14 17:11:26 -08002481void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2482 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002483 const std::optional<DisplayIdentificationInfo> info =
2484 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002485
Dominik Laskowski075d3172018-05-24 15:50:06 -07002486 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002487 continue;
2488 }
2489
Lloyd Piqueba04e622017-12-14 17:11:26 -08002490 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002491 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002492 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002493 mPhysicalDisplayTokens[info->id] = new BBinder();
2494 DisplayDeviceState state;
2495 state.displayId = info->id;
2496 state.isSecure = true; // All physical displays are currently considered secure.
2497 state.displayName = info->name;
2498 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2499 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002500 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002501 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002502 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002503
Dominik Laskowski075d3172018-05-24 15:50:06 -07002504 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2505 if (index >= 0) {
2506 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2507 mInterceptor->saveDisplayDeletion(state.sequenceId);
2508 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002509 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002510 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002511 }
2512
2513 processDisplayChangesLocked();
2514 }
2515
2516 mPendingHotplugEvents.clear();
2517}
2518
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002519void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002520 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2521 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002522}
2523
Lloyd Pique99d3da52018-01-22 17:48:03 -08002524sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002525 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002526 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002527 const sp<IGraphicBufferProducer>& producer) {
2528 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002529 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002530 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002531 creationArgs.isSecure = state.isSecure;
2532 creationArgs.displaySurface = dispSurface;
2533 creationArgs.hasWideColorGamut = false;
2534 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002535
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002536 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002537 creationArgs.isPrimary = isInternalDisplay;
2538
2539 if (useColorManagement && displayId) {
2540 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002541 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002542 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002543 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002544 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002545
Dominik Laskowski7e045462018-05-30 13:02:02 -07002546 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002547 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002548 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002549 }
tangrobin6753a022018-08-10 10:58:54 +08002550 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002551
Dominik Laskowski075d3172018-05-24 15:50:06 -07002552 if (displayId) {
2553 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002554 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002555 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002556 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002557
Lloyd Pique90c115d2018-09-18 21:39:42 -07002558 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002559 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002560 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002561
Lloyd Pique99d3da52018-01-22 17:48:03 -08002562 // Make sure that composition can never be stalled by a virtual display
2563 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002564 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002565 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002566 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2567 }
2568
Dominik Laskowski075d3172018-05-24 15:50:06 -07002569 creationArgs.displayInstallOrientation =
2570 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002571
Lloyd Pique99d3da52018-01-22 17:48:03 -08002572 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002573 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002574
Lloyd Pique90c115d2018-09-18 21:39:42 -07002575 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002576
2577 if (maxFrameBufferAcquiredBuffers >= 3) {
2578 nativeWindowSurface->preallocateBuffers();
2579 }
2580
2581 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002582 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002583 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002584 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002585 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002586 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002587 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2588 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002589 if (!state.isVirtual()) {
2590 LOG_ALWAYS_FATAL_IF(!displayId);
2591 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002592 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002593
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002594 display->setLayerStack(state.layerStack);
2595 display->setProjection(state.orientation, state.viewport, state.frame);
2596 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002597
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002598 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002599}
2600
Lloyd Pique347200f2017-12-14 17:00:15 -08002601void SurfaceFlinger::processDisplayChangesLocked() {
2602 // here we take advantage of Vector's copy-on-write semantics to
2603 // improve performance by skipping the transaction entirely when
2604 // know that the lists are identical
2605 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2606 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2607 if (!curr.isIdenticalTo(draw)) {
2608 mVisibleRegionsDirty = true;
2609 const size_t cc = curr.size();
2610 size_t dc = draw.size();
2611
2612 // find the displays that were removed
2613 // (ie: in drawing state but not in current state)
2614 // also handle displays that changed
2615 // (ie: displays that are in both lists)
2616 for (size_t i = 0; i < dc;) {
2617 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2618 if (j < 0) {
2619 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002620 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002621 // Save display ID before disconnecting.
2622 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002623 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002624
2625 if (!display->isVirtual()) {
2626 LOG_ALWAYS_FATAL_IF(!displayId);
2627 dispatchDisplayHotplugEvent(displayId->value, false);
2628 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002629 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002630
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002631 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002632 } else {
2633 // this display is in both lists. see if something changed.
2634 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002635 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002636 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2637 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2638 if (state_binder != draw_binder) {
2639 // changing the surface is like destroying and
2640 // recreating the DisplayDevice, so we just remove it
2641 // from the drawing state, so that it get re-added
2642 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002643 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002644 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002645 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002646 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002647 mDrawingState.displays.removeItemsAt(i);
2648 dc--;
2649 // at this point we must loop to the next item
2650 continue;
2651 }
2652
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002653 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002654 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002655 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002656 }
2657 if ((state.orientation != draw[i].orientation) ||
2658 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002659 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002660 }
2661 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002662 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002663 }
2664 }
2665 }
2666 ++i;
2667 }
2668
2669 // find displays that were added
2670 // (ie: in current state but not in drawing state)
2671 for (size_t i = 0; i < cc; i++) {
2672 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2673 const DisplayDeviceState& state(curr[i]);
2674
Lloyd Pique542307f2018-10-19 13:24:08 -07002675 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002676 sp<IGraphicBufferProducer> producer;
2677 sp<IGraphicBufferProducer> bqProducer;
2678 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002679 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002680
Dominik Laskowski075d3172018-05-24 15:50:06 -07002681 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002682 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002683 // Virtual displays without a surface are dormant:
2684 // they have external state (layer stack, projection,
2685 // etc.) but no internal state (i.e. a DisplayDevice).
2686 if (state.surface != nullptr) {
2687 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002688 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002689 int width = 0;
2690 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2691 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2692 int height = 0;
2693 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2694 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2695 int intFormat = 0;
2696 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2697 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002698 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002699
Dominik Laskowski075d3172018-05-24 15:50:06 -07002700 displayId =
2701 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002702 }
2703
2704 // TODO: Plumb requested format back up to consumer
2705
2706 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002707 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002708 bqProducer, bqConsumer,
2709 state.displayName);
2710
2711 dispSurface = vds;
2712 producer = vds;
2713 }
2714 } else {
2715 ALOGE_IF(state.surface != nullptr,
2716 "adding a supported display, but rendering "
2717 "surface is provided (%p), ignoring it",
2718 state.surface.get());
2719
Dominik Laskowski075d3172018-05-24 15:50:06 -07002720 displayId = state.displayId;
2721 LOG_ALWAYS_FATAL_IF(!displayId);
2722 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002723 producer = bqProducer;
2724 }
2725
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002726 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002727 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002728 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002729 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002730 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002731 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002732 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002733 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002734 }
2735 }
2736 }
2737 }
2738 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002739
2740 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002741}
2742
Mathias Agopian87baae12012-07-31 12:38:26 -07002743void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002744{
Dan Stoza7dde5992015-05-22 09:51:44 -07002745 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002746 mCurrentState.traverseInZOrder([](Layer* layer) {
2747 layer->notifyAvailableFrames();
2748 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002749
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002750 /*
2751 * Traversal of the children
2752 * (perform the transaction for each of them if needed)
2753 */
2754
Marissa Wall06255332019-03-27 13:48:27 -07002755 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002756 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002757 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002758 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002759
2760 const uint32_t flags = layer->doTransaction(0);
2761 if (flags & Layer::eVisibleRegion)
2762 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002763
2764 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002765 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002766 }
Robert Carr2047fae2016-11-28 14:09:09 -08002767 });
Marissa Wall06255332019-03-27 13:48:27 -07002768 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002769 }
2770
2771 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002772 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002773 */
2774
Mathias Agopiane57f2922012-08-09 16:29:12 -07002775 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002776 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002777 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002778 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002779
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002780 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002781 // The transform hint might have changed for some layers
2782 // (either because a display has changed, or because a layer
2783 // as changed).
2784 //
2785 // Walk through all the layers in currentLayers,
2786 // and update their transform hint.
2787 //
2788 // If a layer is visible only on a single display, then that
2789 // display is used to calculate the hint, otherwise we use the
2790 // default display.
2791 //
2792 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2793 // the hint is set before we acquire a buffer from the surface texture.
2794 //
2795 // NOTE: layer transactions have taken place already, so we use their
2796 // drawing state. However, SurfaceFlinger's own transaction has not
2797 // happened yet, so we must use the current state layer list
2798 // (soon to become the drawing state list).
2799 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002800 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002801 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002802 bool first = true;
2803 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002804 // NOTE: we rely on the fact that layers are sorted by
2805 // layerStack first (so we don't have to traverse the list
2806 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002807 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002808 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002809 currentlayerStack = layerStack;
2810 // figure out if this layerstack is mirrored
2811 // (more than one display) if so, pick the default display,
2812 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002813 hintDisplay = nullptr;
2814 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002815 if (display->getCompositionDisplay()
2816 ->belongsInOutput(layer->getLayerStack(),
2817 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002818 if (hintDisplay) {
2819 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002820 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002821 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002822 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002823 }
2824 }
2825 }
2826 }
Chet Haase91d25932013-04-11 15:24:55 -07002827
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002828 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002829 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2830 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002831
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002832 // could be null when this layer is using a layerStack
2833 // that is not visible on any display. Also can occur at
2834 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002835 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002836 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002837
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002838 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002839 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002840 if (hintDisplay) {
2841 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002842 }
Robert Carr2047fae2016-11-28 14:09:09 -08002843
2844 first = false;
2845 });
Mathias Agopian84300952012-11-21 16:02:13 -08002846 }
2847
2848
Mathias Agopian3559b072012-08-15 13:46:03 -07002849 /*
2850 * Perform our own transaction if needed
2851 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002852
2853 if (mLayersAdded) {
2854 mLayersAdded = false;
2855 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002856 mVisibleRegionsDirty = true;
2857 }
2858
2859 // some layers might have been removed, so
2860 // we need to update the regions they're exposing.
2861 if (mLayersRemoved) {
2862 mLayersRemoved = false;
2863 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002864 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002865 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002866 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002867 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002868 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002869 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002870 }
Robert Carr2047fae2016-11-28 14:09:09 -08002871 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002872 }
2873
Vishnu Nairec0ab382019-02-13 15:32:56 -08002874 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002875 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002876}
2877
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002878void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002879 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002880 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002881 return;
2882 }
2883
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002884 if (mVisibleRegionsDirty || mInputInfoChanged) {
2885 mInputInfoChanged = false;
2886 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002887 } else if (mInputWindowCommands.syncInputWindows) {
2888 // If the caller requested to sync input windows, but there are no
2889 // changes to input windows, notify immediately.
2890 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002891 }
2892
2893 executeInputWindowCommands();
2894}
2895
2896void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002897 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002898
2899 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2900 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002901 // When calculating the screen bounds we ignore the transparent region since it may
2902 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002903 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002904 }
2905 });
chaviw291d88a2019-02-14 10:33:58 -08002906
2907 mInputFlinger->setInputWindows(inputHandles,
2908 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2909 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002910}
2911
Vishnu Nairec0ab382019-02-13 15:32:56 -08002912void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002913 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002914 mPendingInputWindowCommands.clear();
2915}
2916
chaviwfbe5d9c2018-12-26 12:23:37 -08002917void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08002918 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2919 if (transferTouchFocusCommand.fromToken != nullptr &&
2920 transferTouchFocusCommand.toToken != nullptr &&
2921 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2922 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2923 transferTouchFocusCommand.toToken);
2924 }
2925 }
2926
2927 mInputWindowCommands.clear();
2928}
2929
Riley Andrews03414a12014-07-01 14:22:59 -07002930void SurfaceFlinger::updateCursorAsync()
2931{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002932 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002933 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002934 continue;
2935 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002936
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002937 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2938 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002939 }
2940 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002941}
2942
chaviw61626f22018-11-15 16:26:27 -08002943void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2944 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08002945 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08002946 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08002947 }
2948 layer->releasePendingBuffer(systemTime());
2949}
2950
Mathias Agopian4fec8732012-06-29 14:12:52 -07002951void SurfaceFlinger::commitTransaction()
2952{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002953 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002954 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002955 for (const auto& l : mLayersPendingRemoval) {
2956 recordBufferingStats(l->getName().string(),
2957 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002958
Lloyd Pique07e33212018-12-18 16:33:37 -08002959 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07002960 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08002961 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07002962 }
chaviw74d90ad2019-04-26 14:45:26 -07002963
2964 // If the layer has been removed and has no parent, then it will not be reachable
2965 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2966 // ensure we can copy its current to drawing state.
2967 if (!l->getParent()) {
2968 mOffscreenLayers.emplace(l.get());
2969 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002970 }
2971 mLayersPendingRemoval.clear();
2972 }
2973
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002974 // If this transaction is part of a window animation then the next frame
2975 // we composite should be considered an animation as well.
2976 mAnimCompositionPending = mAnimTransactionPending;
2977
Nataniel Borges2b796da2019-02-15 13:32:18 -08002978 withTracingLock([&]() {
2979 mDrawingState = mCurrentState;
2980 // clear the "changed" flags in current state
2981 mCurrentState.colorMatrixChanged = false;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002982
chaviw74d90ad2019-04-26 14:45:26 -07002983 mDrawingState.traverseInZOrder([&](Layer* layer) {
2984 layer->commitChildList();
2985
2986 // If the layer can be reached when traversing mDrawingState, then the layer is no
2987 // longer offscreen. Remove the layer from the offscreenLayer set.
2988 if (mOffscreenLayers.count(layer)) {
2989 mOffscreenLayers.erase(layer);
2990 }
2991 });
2992
2993 commitOffscreenLayers();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002994 });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002995
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002996 mTransactionPending = false;
2997 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002998 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002999}
3000
Nataniel Borges2b796da2019-02-15 13:32:18 -08003001void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
3002 if (mTracingEnabledChanged) {
3003 mTracingEnabled = mTracing.isEnabled();
3004 mTracingEnabledChanged = false;
3005 }
3006
3007 // Synchronize with Tracing thread
3008 std::unique_lock<std::mutex> lock;
3009 if (mTracingEnabled) {
3010 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
3011 }
3012
3013 lockedOperation();
3014
3015 // Synchronize with Tracing thread
3016 if (mTracingEnabled) {
3017 lock.unlock();
3018 }
3019}
3020
chaviw74d90ad2019-04-26 14:45:26 -07003021void SurfaceFlinger::commitOffscreenLayers() {
3022 for (Layer* offscreenLayer : mOffscreenLayers) {
3023 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
3024 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3025 if (!trFlags) return;
3026
3027 layer->doTransaction(0);
3028 layer->commitChildList();
3029 });
3030 }
3031}
3032
Lloyd Pique32cbe282018-10-19 13:09:22 -07003033void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003034 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003035 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003036 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003037
Lloyd Pique32cbe282018-10-19 13:09:22 -07003038 auto display = displayDevice->getCompositionDisplay();
3039
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003040 Region aboveOpaqueLayers;
3041 Region aboveCoveredLayers;
3042 Region dirty;
3043
Mathias Agopian87baae12012-07-31 12:38:26 -07003044 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003045
Robert Carr2047fae2016-11-28 14:09:09 -08003046 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003047 // start with the whole surface at its current location
3048 const Layer::State& s(layer->getDrawingState());
3049
Jesse Hall01e29052013-02-19 16:13:35 -08003050 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003051 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003052 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003053 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003054
Mathias Agopianab028732010-03-16 16:41:46 -07003055 /*
3056 * opaqueRegion: area of a surface that is fully opaque.
3057 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003058 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003059
3060 /*
3061 * visibleRegion: area of a surface that is visible on screen
3062 * and not fully transparent. This is essentially the layer's
3063 * footprint minus the opaque regions above it.
3064 * Areas covered by a translucent surface are considered visible.
3065 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003066 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003067
3068 /*
3069 * coveredRegion: area of a surface that is covered by all
3070 * visible regions above it (which includes the translucent areas).
3071 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003072 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003073
Jesse Halla8026d22012-09-25 13:25:04 -07003074 /*
3075 * transparentRegion: area of a surface that is hinted to be completely
3076 * transparent. This is only used to tell when the layer has no visible
3077 * non-transparent regions and can be removed from the layer list. It
3078 * does not affect the visibleRegion of this layer or any layers
3079 * beneath it. The hint may not be correct if apps don't respect the
3080 * SurfaceView restrictions (which, sadly, some don't).
3081 */
3082 Region transparentRegion;
3083
Mathias Agopianab028732010-03-16 16:41:46 -07003084
3085 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003086 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003087 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003088 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003089
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003090 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003091 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003092 if (!visibleRegion.isEmpty()) {
3093 // Remove the transparent area from the visible region
3094 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003095 if (tr.preserveRects()) {
3096 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003097 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003098 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003099 // transformation too complex, can't do the
3100 // transparent region optimization.
3101 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003102 }
Mathias Agopianab028732010-03-16 16:41:46 -07003103 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003104
Mathias Agopianab028732010-03-16 16:41:46 -07003105 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003106 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003107 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003108 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003109 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003110 // the opaque region is the layer's footprint
3111 opaqueRegion = visibleRegion;
3112 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003113 }
3114 }
3115
Robert Carre5f4f692018-01-12 13:12:28 -08003116 if (visibleRegion.isEmpty()) {
3117 layer->clearVisibilityRegions();
3118 return;
3119 }
3120
Mathias Agopianab028732010-03-16 16:41:46 -07003121 // Clip the covered region to the visible region
3122 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3123
3124 // Update aboveCoveredLayers for next (lower) layer
3125 aboveCoveredLayers.orSelf(visibleRegion);
3126
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003127 // subtract the opaque region covered by the layers above us
3128 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003129
3130 // compute this layer's dirty region
3131 if (layer->contentDirty) {
3132 // we need to invalidate the whole region
3133 dirty = visibleRegion;
3134 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003135 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003136 layer->contentDirty = false;
3137 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003138 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003139 * the exposed region consists of two components:
3140 * 1) what's VISIBLE now and was COVERED before
3141 * 2) what's EXPOSED now less what was EXPOSED before
3142 *
3143 * note that (1) is conservative, we start with the whole
3144 * visible region but only keep what used to be covered by
3145 * something -- which mean it may have been exposed.
3146 *
3147 * (2) handles areas that were not covered by anything but got
3148 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003149 */
Mathias Agopianab028732010-03-16 16:41:46 -07003150 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003151 const Region oldVisibleRegion = layer->visibleRegion;
3152 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003153 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3154 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003155 }
3156 dirty.subtractSelf(aboveOpaqueLayers);
3157
3158 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003159 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003160
Mathias Agopianab028732010-03-16 16:41:46 -07003161 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003162 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003163
Jesse Halla8026d22012-09-25 13:25:04 -07003164 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003165 layer->setVisibleRegion(visibleRegion);
3166 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003167 layer->setVisibleNonTransparentRegion(
3168 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003169 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003170
Mathias Agopian87baae12012-07-31 12:38:26 -07003171 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003172}
3173
Chia-I Wuab0c3192017-08-01 11:29:00 -07003174void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003175 for (const auto& [token, displayDevice] : mDisplays) {
3176 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003177 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003178 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003179 }
3180 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003181}
3182
Dan Stoza6b9454d2014-11-07 16:00:59 -08003183bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003184{
Ady Abraham09bd3922019-04-08 10:44:56 -07003185 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003186 ALOGV("handlePageFlip");
3187
Brian Andersond6927fb2016-07-23 23:37:30 -07003188 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003189
Mathias Agopian4fec8732012-06-29 14:12:52 -07003190 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003191 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003192 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003193
3194 // Store the set of layers that need updates. This set must not change as
3195 // buffers are being latched, as this could result in a deadlock.
3196 // Example: Two producers share the same command stream and:
3197 // 1.) Layer 0 is latched
3198 // 2.) Layer 0 gets a new frame
3199 // 2.) Layer 1 gets a new frame
3200 // 3.) Layer 1 is latched.
3201 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3202 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003203 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003204 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003205 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003206 nsecs_t expectedPresentTime;
Ana Krulecc2870422019-01-29 19:00:58 -08003207 expectedPresentTime = mScheduler->expectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003208 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003209 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003210 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003211 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003212 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003213 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003214 } else {
3215 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003216 }
Robert Carr2047fae2016-11-28 14:09:09 -08003217 });
3218
Lloyd Piquef2c79392018-12-20 16:23:33 -08003219 if (!mLayersWithQueuedFrames.empty()) {
3220 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3221 // writes to Layer current state. See also b/119481871
3222 Mutex::Autolock lock(mStateLock);
3223
3224 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003225 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003226 mLayersPendingRefresh.push_back(layer);
3227 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003228 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003229 if (layer->isBufferLatched()) {
3230 newDataLatched = true;
3231 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003232 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003233 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003234
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003235 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003236
3237 // If we will need to wake up at some time in the future to deal with a
3238 // queued frame that shouldn't be displayed during this vsync period, wake
3239 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003240 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003241 signalLayerUpdate();
3242 }
3243
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003244 // enter boot animation on first buffer latch
3245 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3246 ALOGI("Enter boot animation");
3247 mBootStage = BootStage::BOOTANIMATION;
3248 }
3249
Dan Stoza6b9454d2014-11-07 16:00:59 -08003250 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003251 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003252}
3253
Mathias Agopianad456f92011-01-13 17:53:01 -08003254void SurfaceFlinger::invalidateHwcGeometry()
3255{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003256 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003257}
3258
Lloyd Pique32cbe282018-10-19 13:09:22 -07003259void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003260 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003261 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003262 // We only need to actually compose the display if:
3263 // 1) It is being handled by hardware composer, which may need this to
3264 // keep its virtual display state machine in sync, or
3265 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003266 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003267 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003268 return;
3269 }
3270
Dan Stoza9e56aa02015-11-02 13:00:03 -08003271 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003272 base::unique_fd readyFence;
3273 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003274
3275 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003276 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003277}
3278
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003279bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3280 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003281 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003282 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003283
Lloyd Pique32cbe282018-10-19 13:09:22 -07003284 auto display = displayDevice->getCompositionDisplay();
3285 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003286 const auto displayId = display->getId();
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003287 auto& renderEngine = getRenderEngine();
Peiyong Lin548d4fa2019-04-02 18:14:44 -07003288 const bool supportProtectedContent = renderEngine.supportsProtectedContent();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003289
3290 const Region bounds(displayState.bounds);
3291 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003292 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003293 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003294
Chia-I Wu8e50e692018-05-04 10:12:37 -07003295 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003296
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003297 renderengine::DisplaySettings clientCompositionDisplay;
3298 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3299 sp<GraphicBuffer> buf;
Alec Mouri6338c9d2019-02-07 16:57:51 -08003300 base::unique_fd fd;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003301
Dan Stoza9e56aa02015-11-02 13:00:03 -08003302 if (hasClientComposition) {
3303 ALOGV("hasClientComposition");
3304
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003305 if (displayDevice->isPrimary() && supportProtectedContent) {
3306 bool needsProtected = false;
3307 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3308 // If the layer is a protected layer, mark protected context is needed.
3309 if (layer->isProtected()) {
3310 needsProtected = true;
3311 break;
3312 }
3313 }
Peiyong Lin52010312019-05-02 14:22:16 -07003314 if (needsProtected != renderEngine.isProtected()) {
3315 renderEngine.useProtectedContext(needsProtected);
3316 }
3317 if (needsProtected != display->getRenderSurface()->isProtected() &&
3318 needsProtected == renderEngine.isProtected()) {
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003319 display->getRenderSurface()->setProtected(needsProtected);
3320 }
3321 }
3322
Alec Mouri6338c9d2019-02-07 16:57:51 -08003323 buf = display->getRenderSurface()->dequeueBuffer(&fd);
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003324
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003325 if (buf == nullptr) {
3326 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3327 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003328 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003329 return false;
3330 }
3331
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003332 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3333 clientCompositionDisplay.clip = displayState.scissor;
3334 const ui::Transform& displayTransform = displayState.transform;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07003335 clientCompositionDisplay.globalTransform = displayTransform.asMatrix4();
Peiyong Linb1925962019-04-01 16:37:10 -07003336 clientCompositionDisplay.orientation = displayState.orientation;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003337
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003338 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003339 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003340 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003341 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003342 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003343 clientCompositionDisplay.outputDataspace = outputDataspace;
3344 clientCompositionDisplay.maxLuminance =
3345 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003346
Lloyd Pique441d5042018-10-18 16:49:51 -07003347 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003348 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003349 getHwComposer()
3350 .hasDisplayCapability(displayId,
3351 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003352
Peiyong Lind3788632018-09-18 16:01:31 -07003353 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003354 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3355 if (applyColorMatrix) {
Alec Mouric7e8ce82019-04-02 12:28:05 -07003356 clientCompositionDisplay.colorTransform = displayState.colorTransformMat;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003357 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003358 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003359
Mathias Agopian85d751c2012-08-29 16:59:24 -07003360 /*
3361 * and then, render the layers targeted at the framebuffer
3362 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003363
Dan Stoza9e56aa02015-11-02 13:00:03 -08003364 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003365 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003366 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003367 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003368 const Region viewportRegion(displayState.viewport);
3369 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003370 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003371 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003372 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003373 switch (layer->getCompositionType(displayDevice)) {
3374 case Hwc2::IComposerClient::Composition::CURSOR:
3375 case Hwc2::IComposerClient::Composition::DEVICE:
3376 case Hwc2::IComposerClient::Composition::SIDEBAND:
3377 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003378 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003379 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003380 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003381 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003382 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003383 // never clear the very first layer since we're
3384 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003385 renderengine::LayerSettings layerSettings;
3386 Region dummyRegion;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003387 bool prepared =
3388 layer->prepareClientLayer(renderArea, clip, dummyRegion,
3389 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003390
3391 if (prepared) {
3392 layerSettings.source.buffer.buffer = nullptr;
3393 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3394 layerSettings.alpha = half(0.0);
3395 layerSettings.disableBlending = true;
3396 clientCompositionLayers.push_back(layerSettings);
3397 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003398 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003399 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003400 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003401 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003402 renderengine::LayerSettings layerSettings;
3403 bool prepared =
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003404 layer->prepareClientLayer(renderArea, clip, clearRegion,
3405 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003406 if (prepared) {
3407 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003408 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003409 break;
3410 }
3411 default:
3412 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003413 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003414 } else {
3415 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003416 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003417 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003418 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003419
Alec Mouri820c7402019-01-23 13:02:39 -08003420 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003421 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003422 clientCompositionDisplay.clearRegion = clearRegion;
Peiyong Lin74ca2f42019-01-14 19:36:57 -08003423
3424 // We boost GPU frequency here because there will be color spaces conversion
3425 // and it's expensive. We boost the GPU frequency so that GPU composition can
3426 // finish in time. We must reset GPU frequency afterwards, because high frequency
3427 // consumes extra battery.
3428 const bool expensiveRenderingExpected =
3429 clientCompositionDisplay.outputDataspace == Dataspace::DISPLAY_P3;
3430 if (expensiveRenderingExpected && displayId) {
3431 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, true);
3432 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003433 if (!debugRegion.isEmpty()) {
3434 Region::const_iterator it = debugRegion.begin();
3435 Region::const_iterator end = debugRegion.end();
3436 while (it != end) {
3437 const Rect& rect = *it++;
3438 renderengine::LayerSettings layerSettings;
3439 layerSettings.source.buffer.buffer = nullptr;
3440 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3441 layerSettings.geometry.boundaries = rect.toFloatRect();
3442 layerSettings.alpha = half(1.0);
3443 clientCompositionLayers.push_back(layerSettings);
3444 }
3445 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003446 renderEngine.drawLayers(clientCompositionDisplay, clientCompositionLayers,
Alec Mourife0d72b2019-03-21 14:05:56 -07003447 buf->getNativeBuffer(), /*useFramebufferCache=*/true, std::move(fd),
3448 readyFence);
Peiyong Lin8ec87f82019-04-05 11:30:51 -07003449 } else if (displayId) {
3450 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, false);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003451 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003452 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003453}
3454
Chia-I Wu28e3a252018-09-07 12:05:02 -07003455void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003456 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003457 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003458}
3459
Robert Carrc0df3122019-04-11 13:18:21 -07003460status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3461 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3462 const sp<IBinder>& parentHandle,
3463 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003464 // add this layer to the current state list
3465 {
3466 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003467 sp<Layer> parent;
3468 if (parentHandle != nullptr) {
3469 parent = fromHandle(parentHandle);
3470 if (parent == nullptr) {
3471 return NAME_NOT_FOUND;
3472 }
3473 } else {
3474 parent = parentLayer;
3475 }
3476
Robert Carr1f0a16a2016-10-24 16:27:39 -07003477 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003478 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3479 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003480 return NO_MEMORY;
3481 }
Robert Carrc0df3122019-04-11 13:18:21 -07003482
3483 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3484
Robert Carrb89ea9d2018-12-10 13:01:14 -08003485 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003486 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003487 } else if (parent == nullptr) {
3488 lbc->onRemovedFromCurrentState();
3489 } else if (parent->isRemovedFromCurrentState()) {
3490 parent->addChild(lbc);
3491 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003492 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003493 parent->addChild(lbc);
3494 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003495
Yiwei Zhang243b3782018-05-15 17:40:04 -07003496 if (gbc != nullptr) {
3497 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3498 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3499 mMaxGraphicBufferProducerListSize,
3500 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3501 mGraphicBufferProducerList.size(),
3502 mMaxGraphicBufferProducerListSize, mNumLayers);
3503 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003504 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003505 }
3506
Mathias Agopian96f08192010-06-02 23:28:45 -07003507 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003508 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003509
Dan Stoza7d89d062015-04-30 13:29:25 -07003510 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003511}
3512
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003513uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003514 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003515}
3516
Mathias Agopian3f844832013-08-07 21:24:32 -07003517uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003518 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003519}
3520
Mathias Agopian3f844832013-08-07 21:24:32 -07003521uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003522 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003523}
3524
3525uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003526 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003527 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003528 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003529 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003530 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003531 }
3532 return old;
3533}
3534
Marissa Wall713b63f2018-10-17 15:42:43 -07003535bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003536 // to prevent onHandleDestroyed from being called while the lock is held,
3537 // we must keep a copy of the transactions (specifically the composer
3538 // states) around outside the scope of the lock
3539 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003540 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003541 {
3542 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003543
Valerie Haufce31b82019-04-30 16:41:14 -07003544 auto it = mTransactionQueues.begin();
3545 while (it != mTransactionQueues.end()) {
3546 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003547
Valerie Haufce31b82019-04-30 16:41:14 -07003548 while (!transactionQueue.empty()) {
3549 const auto& transaction = transactionQueue.front();
3550 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
3551 transaction.states)) {
3552 setTransactionFlags(eTransactionFlushNeeded);
3553 break;
3554 }
3555 transactions.push_back(transaction);
3556 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3557 mPendingInputWindowCommands, transaction.desiredPresentTime,
3558 transaction.buffer, transaction.callback,
3559 transaction.postTime, transaction.privileged,
3560 /*isMainThread*/ true);
3561 transactionQueue.pop();
3562 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003563 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003564
Valerie Haufce31b82019-04-30 16:41:14 -07003565 if (transactionQueue.empty()) {
3566 it = mTransactionQueues.erase(it);
3567 mTransactionCV.broadcast();
3568 } else {
3569 std::next(it, 1);
3570 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003571 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003572 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003573 return flushedATransaction;
3574}
3575
3576bool SurfaceFlinger::transactionFlushNeeded() {
3577 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003578}
3579
chaviwca27f252018-02-06 16:46:39 -08003580bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3581 for (const ComposerState& state : states) {
3582 // Here we need to check that the interface we're given is indeed
3583 // one of our own. A malicious client could give us a nullptr
3584 // IInterface, or one of its own or even one of our own but a
3585 // different type. All these situations would cause us to crash.
3586 if (state.client == nullptr) {
3587 return true;
3588 }
3589
3590 sp<IBinder> binder = IInterface::asBinder(state.client);
3591 if (binder == nullptr) {
3592 return true;
3593 }
3594
3595 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3596 return true;
3597 }
3598 }
3599 return false;
3600}
3601
Marissa Wall17b4e452018-12-26 16:32:34 -08003602bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3603 const Vector<ComposerState>& states) {
Ana Krulecc2870422019-01-29 19:00:58 -08003604 nsecs_t expectedPresentTime = mScheduler->expectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003605 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3606 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3607 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3608 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3609 return false;
3610 }
3611
Marissa Wall713b63f2018-10-17 15:42:43 -07003612 for (const ComposerState& state : states) {
3613 const layer_state_t& s = state.state;
3614 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3615 continue;
3616 }
3617 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003618 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003619 }
3620 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003621 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003622}
3623
3624void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3625 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003626 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003627 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003628 int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003629 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003630 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003631 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003632
Valerie Haubc6ddb12019-03-08 11:10:15 -08003633 const int64_t postTime = systemTime();
3634
Robert Carr14167e02019-02-13 13:50:55 -08003635 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3636
Mathias Agopian698c0872011-06-28 19:09:31 -07003637 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003638
chaviwca27f252018-02-06 16:46:39 -08003639 if (containsAnyInvalidClientState(states)) {
3640 return;
3641 }
3642
Marissa Wall713b63f2018-10-17 15:42:43 -07003643 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003644 auto itr = mTransactionQueues.find(applyToken);
3645 // if this is an animation frame, wait until prior animation frame has
3646 // been applied by SF
3647 if (flags & eAnimation) {
3648 while (itr != mTransactionQueues.end()) {
3649 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3650 if (CC_UNLIKELY(err != NO_ERROR)) {
3651 ALOGW_IF(err == TIMED_OUT,
3652 "setTransactionState timed out "
3653 "waiting for animation frame to apply");
3654 break;
3655 }
3656 itr = mTransactionQueues.find(applyToken);
3657 }
3658 }
3659 if (itr != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003660 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003661 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003662 uncacheBuffer, listenerCallbacks, postTime,
3663 privileged);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003664 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003665 return;
3666 }
3667
Valerie Haubc6ddb12019-03-08 11:10:15 -08003668 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003669 uncacheBuffer, listenerCallbacks, postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003670}
3671
3672void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003673 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003674 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003675 const int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003676 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003677 const std::vector<ListenerCallbacks>& listenerCallbacks,
Marissa Wall78b72202019-03-15 14:58:34 -07003678 const int64_t postTime, bool privileged,
3679 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003680 uint32_t transactionFlags = 0;
3681
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003682 if (flags & eAnimation) {
3683 // For window updates that are part of an animation we must wait for
3684 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003685 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003686 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003687 if (CC_UNLIKELY(err != NO_ERROR)) {
3688 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003689 // caller after a few seconds.
3690 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3691 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003692 mAnimTransactionPending = false;
3693 break;
3694 }
3695 }
3696 }
3697
chaviwca27f252018-02-06 16:46:39 -08003698 for (const DisplayState& display : displays) {
3699 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003700 }
3701
Marissa Walld600d572019-03-26 15:38:50 -07003702 // In case the client has sent a Transaction that should receive callbacks but without any
3703 // SurfaceControls that should be included in the callback, send the listener and callbackIds
3704 // to the callback thread so it can send an empty callback
3705 if (!listenerCallbacks.empty()) {
3706 mTransactionCompletedThread.run();
3707 }
3708 for (const auto& [listener, callbackIds] : listenerCallbacks) {
3709 mTransactionCompletedThread.addCallback(listener, callbackIds);
3710 }
3711
Marissa Walle2ffb422018-10-12 11:33:52 -07003712 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003713 for (const ComposerState& state : states) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07003714 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, listenerCallbacks,
3715 postTime, privileged);
3716 }
3717
Marissa Walle2ffb422018-10-12 11:33:52 -07003718 // If the state doesn't require a traversal and there are callbacks, send them now
Marissa Wallb0022cc2019-04-16 14:19:55 -07003719 if (!(clientStateFlags & eTraversalNeeded) && !listenerCallbacks.empty()) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003720 mTransactionCompletedThread.sendCallbacks();
3721 }
3722 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003723
chaviw273171b2018-12-26 11:46:30 -08003724 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3725
Marissa Wall947d34e2019-03-29 14:03:53 -07003726 if (uncacheBuffer.isValid()) {
3727 ClientCache::getInstance().erase(uncacheBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003728 }
3729
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003730 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3731 // anyway. This can be used as a flush mechanism for previous async transactions.
3732 // Empty animation transaction can be used to simulate back-pressure, so also force a
3733 // transaction for empty animation transactions.
3734 if (transactionFlags == 0 &&
3735 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003736 transactionFlags = eTransactionNeeded;
3737 }
3738
Marissa Wall06255332019-03-27 13:48:27 -07003739 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3740 // so we don't have to wake up again next frame to preform an uneeded traversal.
3741 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3742 transactionFlags = transactionFlags & (~eTraversalNeeded);
3743 mTraversalNeededMainThread = true;
3744 }
3745
Mathias Agopian386aa982011-11-07 21:58:03 -08003746 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003747 if (mInterceptor->isEnabled()) {
3748 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003749 }
Irvel468051e2016-06-13 16:44:44 -07003750
Mathias Agopian386aa982011-11-07 21:58:03 -08003751 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003752 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3753 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003754 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003755
3756 // if this is a synchronous transaction, wait for it to take effect
3757 // before returning.
3758 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003759 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003760 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003761 if (flags & eAnimation) {
3762 mAnimTransactionPending = true;
3763 }
chaviw4fe36852019-04-15 16:25:49 -07003764 if (mPendingInputWindowCommands.syncInputWindows) {
3765 mPendingSyncInputWindows = true;
3766 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003767
3768 // applyTransactionState can be called by either the main SF thread or by
3769 // another process through setTransactionState. While a given process may wish
3770 // to wait on synchronous transactions, the main SF thread should never
3771 // be blocked. Therefore, we only wait if isMainThread is false.
3772 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003773 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3774 if (CC_UNLIKELY(err != NO_ERROR)) {
3775 // just in case something goes wrong in SF, return to the
3776 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003777 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3778 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003779 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003780 break;
3781 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003782 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003783 }
3784}
3785
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003786uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3787 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3788 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003789
Mathias Agopiane57f2922012-08-09 16:29:12 -07003790 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003791 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3792
3793 const uint32_t what = s.what;
3794 if (what & DisplayState::eSurfaceChanged) {
3795 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3796 state.surface = s.surface;
3797 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003798 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003799 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003800 if (what & DisplayState::eLayerStackChanged) {
3801 if (state.layerStack != s.layerStack) {
3802 state.layerStack = s.layerStack;
3803 flags |= eDisplayTransactionNeeded;
3804 }
3805 }
3806 if (what & DisplayState::eDisplayProjectionChanged) {
3807 if (state.orientation != s.orientation) {
3808 state.orientation = s.orientation;
3809 flags |= eDisplayTransactionNeeded;
3810 }
3811 if (state.frame != s.frame) {
3812 state.frame = s.frame;
3813 flags |= eDisplayTransactionNeeded;
3814 }
3815 if (state.viewport != s.viewport) {
3816 state.viewport = s.viewport;
3817 flags |= eDisplayTransactionNeeded;
3818 }
3819 }
3820 if (what & DisplayState::eDisplaySizeChanged) {
3821 if (state.width != s.width) {
3822 state.width = s.width;
3823 flags |= eDisplayTransactionNeeded;
3824 }
3825 if (state.height != s.height) {
3826 state.height = s.height;
3827 flags |= eDisplayTransactionNeeded;
3828 }
3829 }
3830
Mathias Agopiane57f2922012-08-09 16:29:12 -07003831 return flags;
3832}
3833
Robert Carr14167e02019-02-13 13:50:55 -08003834bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003835 IPCThreadState* ipc = IPCThreadState::self();
3836 const int pid = ipc->getCallingPid();
3837 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003838 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003839 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003840 return false;
3841 }
3842 return true;
3843}
3844
Marissa Wall3dad52d2019-03-22 14:03:19 -07003845uint32_t SurfaceFlinger::setClientStateLocked(
3846 const ComposerState& composerState, int64_t desiredPresentTime,
3847 const std::vector<ListenerCallbacks>& listenerCallbacks, int64_t postTime,
3848 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003849 const layer_state_t& s = composerState.state;
3850 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3851
Mathias Agopian13127d82013-03-05 17:47:11 -08003852 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003853 if (layer == nullptr) {
3854 return 0;
3855 }
3856
chaviw8b3871a2017-11-01 17:41:01 -07003857 uint32_t flags = 0;
3858
Garfield Tan8a3083e2018-12-03 13:21:07 -08003859 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003860 bool geometryAppliesWithResize =
3861 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003862
3863 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3864 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003865 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003866 layer->pushPendingState();
3867 }
3868
chaviw8b3871a2017-11-01 17:41:01 -07003869 if (what & layer_state_t::ePositionChanged) {
3870 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3871 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003872 }
chaviw8b3871a2017-11-01 17:41:01 -07003873 }
3874 if (what & layer_state_t::eLayerChanged) {
3875 // NOTE: index needs to be calculated before we update the state
3876 const auto& p = layer->getParent();
3877 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003878 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003879 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003880 mCurrentState.layersSortedByZ.removeAt(idx);
3881 mCurrentState.layersSortedByZ.add(layer);
3882 // we need traversal (state changed)
3883 // AND transaction (list changed)
3884 flags |= eTransactionNeeded|eTraversalNeeded;
3885 }
chaviw8b3871a2017-11-01 17:41:01 -07003886 } else {
3887 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003888 flags |= eTransactionNeeded|eTraversalNeeded;
3889 }
3890 }
chaviw8b3871a2017-11-01 17:41:01 -07003891 }
3892 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003893 // NOTE: index needs to be calculated before we update the state
3894 const auto& p = layer->getParent();
3895 if (p == nullptr) {
3896 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3897 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3898 mCurrentState.layersSortedByZ.removeAt(idx);
3899 mCurrentState.layersSortedByZ.add(layer);
3900 // we need traversal (state changed)
3901 // AND transaction (list changed)
3902 flags |= eTransactionNeeded|eTraversalNeeded;
3903 }
3904 } else {
3905 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3906 flags |= eTransactionNeeded|eTraversalNeeded;
3907 }
chaviw8b3871a2017-11-01 17:41:01 -07003908 }
3909 }
3910 if (what & layer_state_t::eSizeChanged) {
3911 if (layer->setSize(s.w, s.h)) {
3912 flags |= eTraversalNeeded;
3913 }
3914 }
3915 if (what & layer_state_t::eAlphaChanged) {
3916 if (layer->setAlpha(s.alpha))
3917 flags |= eTraversalNeeded;
3918 }
3919 if (what & layer_state_t::eColorChanged) {
3920 if (layer->setColor(s.color))
3921 flags |= eTraversalNeeded;
3922 }
Peiyong Lind3788632018-09-18 16:01:31 -07003923 if (what & layer_state_t::eColorTransformChanged) {
3924 if (layer->setColorTransform(s.colorTransform)) {
3925 flags |= eTraversalNeeded;
3926 }
3927 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003928 if (what & layer_state_t::eBackgroundColorChanged) {
3929 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3930 flags |= eTraversalNeeded;
3931 }
3932 }
chaviw8b3871a2017-11-01 17:41:01 -07003933 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003934 // TODO: b/109894387
3935 //
3936 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3937 // rotation. To see the problem observe that if we have a square parent, and a child
3938 // of the same size, then we rotate the child 45 degrees around it's center, the child
3939 // must now be cropped to a non rectangular 8 sided region.
3940 //
3941 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3942 // private API, and the WindowManager only uses rotation in one case, which is on a top
3943 // level layer in which cropping is not an issue.
3944 //
3945 // However given that abuse of rotation matrices could lead to surfaces extending outside
3946 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3947 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3948 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003949 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003950 flags |= eTraversalNeeded;
3951 }
3952 if (what & layer_state_t::eTransparentRegionChanged) {
3953 if (layer->setTransparentRegionHint(s.transparentRegion))
3954 flags |= eTraversalNeeded;
3955 }
3956 if (what & layer_state_t::eFlagsChanged) {
3957 if (layer->setFlags(s.flags, s.mask))
3958 flags |= eTraversalNeeded;
3959 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003960 if (what & layer_state_t::eCropChanged_legacy) {
3961 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003962 flags |= eTraversalNeeded;
3963 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003964 if (what & layer_state_t::eCornerRadiusChanged) {
3965 if (layer->setCornerRadius(s.cornerRadius))
3966 flags |= eTraversalNeeded;
3967 }
chaviw8b3871a2017-11-01 17:41:01 -07003968 if (what & layer_state_t::eLayerStackChanged) {
3969 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3970 // We only allow setting layer stacks for top level layers,
3971 // everything else inherits layer stack from its parent.
3972 if (layer->hasParent()) {
3973 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3974 layer->getName().string());
3975 } else if (idx < 0) {
3976 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3977 "that also does not appear in the top level layer list. Something"
3978 " has gone wrong.", layer->getName().string());
3979 } else if (layer->setLayerStack(s.layerStack)) {
3980 mCurrentState.layersSortedByZ.removeAt(idx);
3981 mCurrentState.layersSortedByZ.add(layer);
3982 // we need traversal (state changed)
3983 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003984 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003985 }
3986 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003987 if (what & layer_state_t::eDeferTransaction_legacy) {
3988 if (s.barrierHandle_legacy != nullptr) {
3989 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3990 } else if (s.barrierGbp_legacy != nullptr) {
3991 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003992 if (authenticateSurfaceTextureLocked(gbp)) {
3993 const auto& otherLayer =
3994 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003995 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003996 } else {
3997 ALOGE("Attempt to defer transaction to to an"
3998 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003999 }
4000 }
chaviw8b3871a2017-11-01 17:41:01 -07004001 // We don't trigger a traversal here because if no other state is
4002 // changed, we don't want this to cause any more work
4003 }
4004 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08004005 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07004006 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08004007 if (!hadParent) {
4008 mCurrentState.layersSortedByZ.remove(layer);
4009 }
chaviw8b3871a2017-11-01 17:41:01 -07004010 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08004011 }
chaviw8b3871a2017-11-01 17:41:01 -07004012 }
4013 if (what & layer_state_t::eReparentChildren) {
4014 if (layer->reparentChildren(s.reparentHandle)) {
4015 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07004016 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004017 }
chaviw8b3871a2017-11-01 17:41:01 -07004018 if (what & layer_state_t::eDetachChildren) {
4019 layer->detachChildren();
4020 }
4021 if (what & layer_state_t::eOverrideScalingModeChanged) {
4022 layer->setOverrideScalingMode(s.overrideScalingMode);
4023 // We don't trigger a traversal here because if no other state is
4024 // changed, we don't want this to cause any more work
4025 }
Marissa Wall61c58622018-07-18 10:12:20 -07004026 if (what & layer_state_t::eTransformChanged) {
4027 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4028 }
4029 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4030 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4031 flags |= eTraversalNeeded;
4032 }
4033 if (what & layer_state_t::eCropChanged) {
4034 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4035 }
Marissa Wall861616d2018-10-22 12:52:23 -07004036 if (what & layer_state_t::eFrameChanged) {
4037 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
4038 }
Marissa Wall61c58622018-07-18 10:12:20 -07004039 if (what & layer_state_t::eAcquireFenceChanged) {
4040 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4041 }
4042 if (what & layer_state_t::eDataspaceChanged) {
4043 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4044 }
4045 if (what & layer_state_t::eHdrMetadataChanged) {
4046 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4047 }
4048 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4049 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4050 }
4051 if (what & layer_state_t::eApiChanged) {
4052 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4053 }
4054 if (what & layer_state_t::eSidebandStreamChanged) {
4055 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4056 }
Robert Carr720e5062018-07-30 17:45:14 -07004057 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08004058 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004059 layer->setInputInfo(s.inputInfo);
4060 flags |= eTraversalNeeded;
4061 } else {
4062 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4063 }
Robert Carr720e5062018-07-30 17:45:14 -07004064 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004065 if (what & layer_state_t::eMetadataChanged) {
4066 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4067 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004068 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4069 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4070 flags |= eTraversalNeeded;
4071 }
4072 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004073 std::vector<sp<CallbackHandle>> callbackHandles;
Marissa Wall3dad52d2019-03-22 14:03:19 -07004074 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!listenerCallbacks.empty())) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07004075 for (const auto& [listener, callbackIds] : listenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07004076 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4077 }
4078 }
Marissa Wall78b72202019-03-15 14:58:34 -07004079 bool bufferChanged = what & layer_state_t::eBufferChanged;
4080 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
4081 sp<GraphicBuffer> buffer;
4082 if (bufferChanged && cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004083 ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004084 buffer = s.buffer;
4085 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004086 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004087 } else if (bufferChanged) {
4088 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08004089 }
Marissa Wall78b72202019-03-15 14:58:34 -07004090 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004091 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08004092 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08004093 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004094 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004095 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4096 // Do not put anything that updates layer state or modifies flags after
4097 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004098 return flags;
4099}
4100
chaviw273171b2018-12-26 11:46:30 -08004101uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4102 uint32_t flags = 0;
4103 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4104 flags |= eTraversalNeeded;
4105 }
4106
chaviwa911b102019-02-14 10:18:33 -08004107 if (inputWindowCommands.syncInputWindows) {
4108 flags |= eTraversalNeeded;
4109 }
4110
Vishnu Nairec0ab382019-02-13 15:32:56 -08004111 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004112 return flags;
4113}
4114
Marissa Wall2d814fb2019-04-09 18:52:57 +00004115status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4116 uint32_t h, PixelFormat format, uint32_t flags,
4117 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07004118 sp<IGraphicBufferProducer>* gbp,
4119 const sp<IBinder>& parentHandle,
4120 const sp<Layer>& parentLayer) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004121 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004122 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004123 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004124 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004125 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004126
Robert Carrc0df3122019-04-11 13:18:21 -07004127 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4128 "Expected only one of parentLayer or parentHandle to be non-null. "
4129 "Programmer error?");
4130
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004131 status_t result = NO_ERROR;
4132
4133 sp<Layer> layer;
4134
Cody Northropbc755282017-03-31 12:00:08 -06004135 String8 uniqueName = getUniqueLayerName(name);
4136
Evan Roskya1f1e152019-01-24 16:17:46 -08004137 bool primaryDisplayOnly = false;
4138
4139 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4140 // TODO b/64227542
4141 if (metadata.has(METADATA_WINDOW_TYPE)) {
4142 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4143 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07004144 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08004145 primaryDisplayOnly = true;
4146 }
4147 }
4148
Mathias Agopian3165cc22012-08-08 19:42:09 -07004149 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004150 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Evan Roskya1f1e152019-01-24 16:17:46 -08004151 result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata),
4152 format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004153
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004154 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004155 case ISurfaceComposerClient::eFXSurfaceBufferState:
Evan Roskya1f1e152019-01-24 16:17:46 -08004156 result = createBufferStateLayer(client, uniqueName, w, h, flags, std::move(metadata),
4157 handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07004158 break;
chaviw13fdc492017-06-27 12:40:18 -07004159 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004160 // check if buffer size is set for color layer.
4161 if (w > 0 || h > 0) {
4162 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4163 int(w), int(h));
4164 return BAD_VALUE;
4165 }
4166
Evan Roskya1f1e152019-01-24 16:17:46 -08004167 result = createColorLayer(client, uniqueName, w, h, flags, std::move(metadata), handle,
4168 &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004169 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004170 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004171 // check if buffer size is set for container layer.
4172 if (w > 0 || h > 0) {
4173 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4174 int(w), int(h));
4175 return BAD_VALUE;
4176 }
Evan Roskya1f1e152019-01-24 16:17:46 -08004177 result = createContainerLayer(client, uniqueName, w, h, flags, std::move(metadata),
4178 handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004179 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004180 default:
4181 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004182 break;
4183 }
4184
Dan Stoza7d89d062015-04-30 13:29:25 -07004185 if (result != NO_ERROR) {
4186 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004187 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004188
Evan Roskya1f1e152019-01-24 16:17:46 -08004189 if (primaryDisplayOnly) {
4190 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07004191 }
4192
Robert Carrb89ea9d2018-12-10 13:01:14 -08004193 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07004194 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
4195 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004196 if (result != NO_ERROR) {
4197 return result;
4198 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004199 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004200
4201 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004202 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004203}
4204
Cody Northropbc755282017-03-31 12:00:08 -06004205String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4206{
4207 bool matchFound = true;
4208 uint32_t dupeCounter = 0;
4209
4210 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4211 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4212
Dan Stoza436ccf32018-06-21 12:10:12 -07004213 // Grab the state lock since we're accessing mCurrentState
4214 Mutex::Autolock lock(mStateLock);
4215
Cody Northropbc755282017-03-31 12:00:08 -06004216 // Loop over layers until we're sure there is no matching name
4217 while (matchFound) {
4218 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004219 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004220 if (layer->getName() == uniqueName) {
4221 matchFound = true;
4222 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4223 }
4224 });
4225 }
4226
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004227 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4228 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004229
4230 return uniqueName;
4231}
4232
Marissa Wallfd668622018-05-10 10:21:13 -07004233status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4234 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004235 LayerMetadata metadata, PixelFormat& format,
4236 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004237 sp<IGraphicBufferProducer>* gbp,
4238 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004239 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004240 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004241 case PIXEL_FORMAT_TRANSPARENT:
4242 case PIXEL_FORMAT_TRANSLUCENT:
4243 format = PIXEL_FORMAT_RGBA_8888;
4244 break;
4245 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004246 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004247 break;
4248 }
4249
Evan Roskya1f1e152019-01-24 16:17:46 -08004250 sp<BufferQueueLayer> layer = getFactory().createBufferQueueLayer(
4251 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wallfd668622018-05-10 10:21:13 -07004252 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004253 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004254 *handle = layer->getHandle();
4255 *gbp = layer->getProducer();
4256 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004257 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004258
Marissa Wallfd668622018-05-10 10:21:13 -07004259 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004260 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004261}
4262
Marissa Wall61c58622018-07-18 10:12:20 -07004263status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4264 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004265 LayerMetadata metadata, sp<IBinder>* handle,
4266 sp<Layer>* outLayer) {
4267 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(
4268 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wall61c58622018-07-18 10:12:20 -07004269 *handle = layer->getHandle();
4270 *outLayer = layer;
4271
4272 return NO_ERROR;
4273}
4274
Evan Roskya1f1e152019-01-24 16:17:46 -08004275status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, uint32_t w,
4276 uint32_t h, uint32_t flags, LayerMetadata metadata,
4277 sp<IBinder>* handle, sp<Layer>* outLayer) {
4278 *outLayer = getFactory().createColorLayer(
4279 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004280 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004281 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004282}
4283
Evan Roskya1f1e152019-01-24 16:17:46 -08004284status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name,
4285 uint32_t w, uint32_t h, uint32_t flags,
4286 LayerMetadata metadata, sp<IBinder>* handle,
4287 sp<Layer>* outLayer) {
4288 *outLayer = getFactory().createContainerLayer(
4289 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004290 *handle = (*outLayer)->getHandle();
4291 return NO_ERROR;
4292}
4293
4294
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004295void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004296 mLayersPendingRemoval.add(layer);
4297 mLayersRemoved = true;
4298 setTransactionFlags(eTransactionNeeded);
4299}
4300
Robert Carr695d5282018-12-18 15:27:58 -08004301void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004302{
Robert Carr2e102c92018-10-23 12:11:15 -07004303 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004304 // If a layer has a parent, we allow it to out-live it's handle
4305 // with the idea that the parent holds a reference and will eventually
4306 // be cleaned up. However no one cleans up the top-level so we do so
4307 // here.
4308 if (layer->getParent() == nullptr) {
4309 mCurrentState.layersSortedByZ.remove(layer);
4310 }
4311 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004312
4313 auto it = mLayersByLocalBinderToken.begin();
4314 while (it != mLayersByLocalBinderToken.end()) {
4315 if (it->second == layer) {
4316 it = mLayersByLocalBinderToken.erase(it);
4317 } else {
4318 it++;
4319 }
4320 }
4321
Robert Carr695d5282018-12-18 15:27:58 -08004322 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004323}
4324
Mathias Agopianb60314a2012-04-10 22:09:54 -07004325// ---------------------------------------------------------------------------
4326
Andy McFadden13a082e2012-08-24 10:16:42 -07004327void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004328 const auto display = getDefaultDisplayDeviceLocked();
4329 if (!display) return;
4330
4331 const sp<IBinder> token = display->getDisplayToken().promote();
4332 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004333
Jesse Hall01e29052013-02-19 16:13:35 -08004334 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004335 Vector<ComposerState> state;
4336 Vector<DisplayState> displays;
4337 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004338 d.what = DisplayState::eDisplayProjectionChanged |
4339 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004340 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004341 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004342 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004343 d.frame.makeInvalid();
4344 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004345 d.width = 0;
4346 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004347 displays.add(d);
Marissa Wall3dad52d2019-03-22 14:03:19 -07004348 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004349
Dominik Laskowskie9774092018-12-11 10:04:24 -08004350 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004351
Dominik Laskowski83b88212018-12-11 13:34:06 -08004352 const nsecs_t vsyncPeriod = getVsyncPeriod();
4353 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004354
Brian Andersond0010582017-03-07 13:20:31 -08004355 // Use phase of 0 since phase is not known.
4356 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004357 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004358 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004359}
4360
4361void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004362 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004363 postMessageAsync(
4364 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004365}
4366
Dominik Laskowskie9774092018-12-11 10:04:24 -08004367void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004368 if (display->isVirtual()) {
4369 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004370 return;
4371 }
4372
Dominik Laskowski075d3172018-05-24 15:50:06 -07004373 const auto displayId = display->getId();
4374 LOG_ALWAYS_FATAL_IF(!displayId);
4375
Dominik Laskowski34157762018-10-31 13:07:19 -07004376 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004377
4378 int currentMode = display->getPowerMode();
4379 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004380 return;
4381 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004382
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004383 display->setPowerMode(mode);
4384
Lloyd Pique4dccc412018-01-22 17:21:36 -08004385 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004386 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004387 }
4388
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004389 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004390 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004391 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004392 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004393 mScheduler->onScreenAcquired(mAppConnectionHandle);
4394 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004395 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004396
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004397 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004398 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004399 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004400
4401 struct sched_param param = {0};
4402 param.sched_priority = 1;
4403 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4404 ALOGW("Couldn't set SCHED_FIFO on display on");
4405 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004406 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004407 // Turn off the display
4408 struct sched_param param = {0};
4409 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4410 ALOGW("Couldn't set SCHED_OTHER on display off");
4411 }
4412
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004413 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004414 mScheduler->disableHardwareVsync(true);
4415 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004416 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004417
Dominik Laskowski075d3172018-05-24 15:50:06 -07004418 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004419 mVisibleRegionsDirty = true;
4420 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004421 } else if (mode == HWC_POWER_MODE_DOZE ||
4422 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004423 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004424 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004425 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004426 mScheduler->onScreenAcquired(mAppConnectionHandle);
4427 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004428 }
4429 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4430 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004431 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004432 mScheduler->disableHardwareVsync(true);
4433 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004434 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004435 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004436 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004437 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004438 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004439 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004440
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004441 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004442 mTimeStats->setPowerMode(mode);
Dominik Laskowski22488f62019-03-28 09:53:04 -07004443 mRefreshRateStats.setPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004444 }
4445
Dominik Laskowski34157762018-10-31 13:07:19 -07004446 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004447}
4448
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004449void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004450 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004451 const auto display = getDisplayDevice(displayToken);
4452 if (!display) {
4453 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4454 displayToken.get());
4455 } else if (display->isVirtual()) {
4456 ALOGW("Attempt to set power mode %d for virtual display", mode);
4457 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004458 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004459 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004460 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004461}
4462
4463// ---------------------------------------------------------------------------
4464
Dominik Laskowskic2867142019-01-21 11:33:38 -08004465status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4466 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004467 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004468
Mathias Agopianbd115332013-04-18 16:41:04 -07004469 IPCThreadState* ipc = IPCThreadState::self();
4470 const int pid = ipc->getCallingPid();
4471 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004472
Mathias Agopianbd115332013-04-18 16:41:04 -07004473 if ((uid != AID_SHELL) &&
4474 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004475 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4476 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004477 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004478 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004479 // (this would indicate SF is stuck, but we want to be able to
4480 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004481 status_t err = mStateLock.timedLock(s2ns(1));
4482 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004483 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004484 StringAppendF(&result,
4485 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4486 "(no locks held)\n",
4487 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004488 }
4489
Dominik Laskowskic2867142019-01-21 11:33:38 -08004490 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004491
Dominik Laskowskic2867142019-01-21 11:33:38 -08004492 static const std::unordered_map<std::string, Dumper> dumpers = {
4493 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4494 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4495 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004496 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004497 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004498 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004499 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4500 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004501 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4502 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4503 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4504 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4505 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4506 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004507 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004508 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4509 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004510
Dominik Laskowskic2867142019-01-21 11:33:38 -08004511 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004512
Dominik Laskowskic2867142019-01-21 11:33:38 -08004513 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4514 (it->second)(args, asProto, result);
4515 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004516 if (asProto) {
4517 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4518 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4519 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004520 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004521 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004522 }
4523
Mathias Agopian9795c422009-08-26 16:36:26 -07004524 if (locked) {
4525 mStateLock.unlock();
4526 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004527 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004528 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004529 return NO_ERROR;
4530}
4531
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004532status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4533 if (asProto && mTracing.isEnabled()) {
4534 mTracing.writeToFileAsync();
4535 }
4536
4537 return doDump(fd, DumpArgs(), asProto);
4538}
4539
Dominik Laskowskic2867142019-01-21 11:33:38 -08004540void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004541 mCurrentState.traverseInZOrder(
4542 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004543}
4544
Dominik Laskowskic2867142019-01-21 11:33:38 -08004545void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004546 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004547
Dominik Laskowskic2867142019-01-21 11:33:38 -08004548 if (args.size() > 1) {
4549 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004550 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004551 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004552 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004553 }
Robert Carr2047fae2016-11-28 14:09:09 -08004554 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004555 } else {
4556 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004557 }
4558}
4559
Dominik Laskowskic2867142019-01-21 11:33:38 -08004560void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004561 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004562 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004563 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004564 }
Robert Carr2047fae2016-11-28 14:09:09 -08004565 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004566
Svetoslavd85084b2014-03-20 10:28:31 -07004567 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004568}
4569
Dominik Laskowskic2867142019-01-21 11:33:38 -08004570void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4571 mTimeStats->parseArgs(asProto, args, result);
4572}
4573
Jamie Gennis6547ff42013-07-16 20:12:42 -07004574// This should only be called from the main thread. Otherwise it would need
4575// the lock and should use mCurrentState rather than mDrawingState.
4576void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004577 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004578 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004579 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004580
4581 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4582}
4583
Yiwei Zhang5434a782018-12-05 18:06:32 -08004584void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004585 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004586
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004587 if (isLayerTripleBufferingDisabled())
4588 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004589
Yiwei Zhang5434a782018-12-05 18:06:32 -08004590 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4591 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4592 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4593 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4594 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4595 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004596 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004597}
4598
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004599void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004600 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004601 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004602 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004603 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004604
Ady Abraham97d04232019-03-05 19:48:12 -08004605 StringAppendF(&result, "Scheduler enabled.");
Ana Krulecba13ab32019-02-20 14:14:12 -08004606 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4607 mUseSmart90ForVideo ? "on" : "off");
Ana Krulecc2870422019-01-29 19:00:58 -08004608 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004609}
4610
Yiwei Zhang5434a782018-12-05 18:06:32 -08004611void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4612 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004613 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4614 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004615 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004616 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004617 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004618 }
David Sodman4a36e932017-11-07 14:29:47 -08004619 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004620 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004621 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004622 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4623 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004624}
4625
Dan Stozae77c7662016-05-13 11:37:28 -07004626void SurfaceFlinger::recordBufferingStats(const char* layerName,
4627 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004628 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4629 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004630 for (const auto& segment : history) {
4631 if (!segment.usedThirdBuffer) {
4632 stats.twoBufferTime += segment.totalTime;
4633 }
4634 if (segment.occupancyAverage < 1.0f) {
4635 stats.doubleBufferedTime += segment.totalTime;
4636 } else if (segment.occupancyAverage < 2.0f) {
4637 stats.tripleBufferedTime += segment.totalTime;
4638 }
4639 ++stats.numSegments;
4640 stats.totalTime += segment.totalTime;
4641 }
4642}
4643
Yiwei Zhang5434a782018-12-05 18:06:32 -08004644void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4645 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004646
4647 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4648 const size_t count = currentLayers.size();
4649 for (size_t i=0 ; i<count ; i++) {
4650 currentLayers[i]->dumpFrameEvents(result);
4651 }
4652}
4653
Yiwei Zhang5434a782018-12-05 18:06:32 -08004654void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004655 result.append("Buffering stats:\n");
4656 result.append(" [Layer name] <Active time> <Two buffer> "
4657 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004658 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004659 typedef std::tuple<std::string, float, float, float> BufferTuple;
4660 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004661 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004662 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004663 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004664 if (stats.numSegments == 0) {
4665 continue;
4666 }
4667 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4668 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4669 stats.totalTime;
4670 float doubleBufferRatio = static_cast<float>(
4671 stats.doubleBufferedTime) / stats.totalTime;
4672 float tripleBufferRatio = static_cast<float>(
4673 stats.tripleBufferedTime) / stats.totalTime;
4674 sorted.insert({activeTime, {name, twoBufferRatio,
4675 doubleBufferRatio, tripleBufferRatio}});
4676 }
4677 for (const auto& sortedPair : sorted) {
4678 float activeTime = sortedPair.first;
4679 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004680 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4681 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004682 }
4683 result.append("\n");
4684}
4685
Yiwei Zhang5434a782018-12-05 18:06:32 -08004686void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004687 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004688 const auto displayId = display->getId();
4689 if (!displayId) {
4690 continue;
4691 }
4692 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004693 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004694 continue;
4695 }
4696
Yiwei Zhang5434a782018-12-05 18:06:32 -08004697 StringAppendF(&result,
4698 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4699 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004700 uint8_t port;
4701 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004702 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004703 result.append("no identification data\n");
4704 continue;
4705 }
4706
4707 if (!isEdid(data)) {
4708 result.append("unknown identification data: ");
4709 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004710 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004711 }
4712 result.append("\n");
4713 continue;
4714 }
4715
4716 const auto edid = parseEdid(data);
4717 if (!edid) {
4718 result.append("invalid EDID: ");
4719 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004720 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004721 }
4722 result.append("\n");
4723 continue;
4724 }
4725
Yiwei Zhang5434a782018-12-05 18:06:32 -08004726 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004727 result.append(edid->displayName.data(), edid->displayName.length());
4728 result.append("\"\n");
4729 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004730}
4731
Yiwei Zhang5434a782018-12-05 18:06:32 -08004732void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4733 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4734 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4735 StringAppendF(&result, "DisplayColorSetting: %s\n",
4736 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004737
4738 // TODO: print out if wide-color mode is active or not
4739
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004740 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004741 const auto displayId = display->getId();
4742 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004743 continue;
4744 }
4745
Yiwei Zhang5434a782018-12-05 18:06:32 -08004746 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004747 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004748 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004749 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004750 }
4751
Lloyd Pique32cbe282018-10-19 13:09:22 -07004752 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004753 StringAppendF(&result, " Current color mode: %s (%d)\n",
4754 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004755 }
4756 result.append("\n");
4757}
4758
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004759LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet,
4760 uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004761 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004762 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4763 const State& state = useDrawing ? mDrawingState : mCurrentState;
4764 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004765 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004766 layer->writeToProto(layerProto, stateSet, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004767 });
4768
4769 return layersProto;
4770}
4771
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004772LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4773 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004774 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004775
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004776 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004777 resolution->set_w(displayDevice->getWidth());
4778 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004779
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004780 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004781 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004782
Lloyd Pique32cbe282018-10-19 13:09:22 -07004783 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4784 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4785 layersProto.set_global_transform(displayState.orientation);
4786
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004787 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004788 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004789 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004790 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004791 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004792 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004793 }
4794 });
4795
4796 return layersProto;
4797}
4798
Dominik Laskowskic2867142019-01-21 11:33:38 -08004799void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4800 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004801 Colorizer colorizer(colorize);
4802
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004803 // figure out if we're stuck somewhere
4804 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004805 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004806 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4807
4808 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004809 * Dump library configuration.
4810 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004811
4812 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004813 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004814 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004815 appendSfConfigString(result);
4816 appendUiConfigString(result);
4817 appendGuiConfigString(result);
4818 result.append("\n");
4819
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004820 result.append("\nDisplay identification data:\n");
4821 dumpDisplayIdentificationData(result);
4822
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004823 result.append("\nWide-Color information:\n");
4824 dumpWideColorInfo(result);
4825
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004826 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004827 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004828 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004829 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004830 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004831
Andy McFadden41d67d72014-04-25 16:58:34 -07004832 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004833 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004834 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004835 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004836 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004837
Dan Stozab90cf072015-03-05 11:05:59 -08004838 dumpStaticScreenStats(result);
4839 result.append("\n");
4840
Alec Mouri40189b02019-03-05 15:07:54 -08004841 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4842 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4843 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004844
Dan Stozae77c7662016-05-13 11:37:28 -07004845 dumpBufferingStats(result);
4846
Andy McFadden4803b742012-09-24 19:07:20 -07004847 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004848 * Dump the visible layer list
4849 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004850 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004851 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4852 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4853 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004854 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004855
Chia-I Wu2f884132018-09-13 15:17:58 -07004856 {
4857 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4858 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004859 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004860 result.append("\n");
4861 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004862
Lloyd Pique207def92019-02-28 16:09:52 -08004863 {
4864 StringAppendF(&result, "Composition layers\n");
4865 mDrawingState.traverseInZOrder([&](Layer* layer) {
4866 auto compositionLayer = layer->getCompositionLayer();
4867 if (compositionLayer) compositionLayer->dump(result);
4868 });
4869 }
4870
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004871 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004872 * Dump Display state
4873 */
4874
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004875 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004876 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004877 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004878 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004879 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004880 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004881 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004882
4883 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004884 * Dump SurfaceFlinger global state
4885 */
4886
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004887 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004888 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004889 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004890
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004891 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004892
Dominik Laskowski075d3172018-05-24 15:50:06 -07004893 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004894 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4895 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004896 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4897 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004898 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004899 StringAppendF(&result,
4900 " transaction-flags : %08x\n"
4901 " gpu_to_cpu_unsupported : %d\n",
4902 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004903
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004904 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004905 displayId && getHwComposer().isConnected(*displayId)) {
4906 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004907 StringAppendF(&result,
4908 " refresh-rate : %f fps\n"
4909 " x-dpi : %f\n"
4910 " y-dpi : %f\n",
4911 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4912 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004913 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004914
Yiwei Zhang5434a782018-12-05 18:06:32 -08004915 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004916
Dan Stozae22aec72016-08-01 13:20:59 -07004917 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004918 * Tracing state
4919 */
4920 mTracing.dump(result);
4921 result.append("\n");
4922
4923 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004924 * HWC layer minidump
4925 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004926 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004927 const auto displayId = display->getId();
4928 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004929 continue;
4930 }
4931
Yiwei Zhang5434a782018-12-05 18:06:32 -08004932 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004933 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004934 const sp<DisplayDevice> displayDevice = display;
4935 mCurrentState.traverseInZOrder(
4936 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004937 result.append("\n");
4938 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004939
4940 /*
4941 * Dump HWComposer state
4942 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004943 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004944 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004945 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004946 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004947 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004948 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004949
4950 /*
4951 * Dump gralloc state
4952 */
4953 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4954 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004955
4956 /*
4957 * Dump VrFlinger state if in use.
4958 */
4959 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4960 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004961 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004962 result.append("\n");
4963 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004964
4965 /**
4966 * Scheduler dump state.
4967 */
Ana Krulecc2870422019-01-29 19:00:58 -08004968 result.append("\nScheduler state:\n");
4969 result.append(mScheduler->doDump() + "\n");
Ana Krulecfefd6ae2019-02-13 17:53:08 -08004970 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
Dominik Laskowski22488f62019-03-28 09:53:04 -07004971 result.append(mRefreshRateStats.doDump() + "\n");
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004972
4973 result.append(mTimeStats->miniDump());
4974 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004975}
4976
Dominik Laskowski075d3172018-05-24 15:50:06 -07004977const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004978 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004979 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004980 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004981 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004982 }
4983 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004984
Dominik Laskowski34157762018-10-31 13:07:19 -07004985 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004986 static const Vector<sp<Layer>> empty;
4987 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004988}
4989
Chia-I Wu28f320b2018-05-03 11:02:56 -07004990void SurfaceFlinger::updateColorMatrixLocked() {
4991 mat4 colorMatrix;
4992 if (mGlobalSaturationFactor != 1.0f) {
4993 // Rec.709 luma coefficients
4994 float3 luminance{0.213f, 0.715f, 0.072f};
4995 luminance *= 1.0f - mGlobalSaturationFactor;
4996 mat4 saturationMatrix = mat4(
4997 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4998 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4999 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
5000 vec4{0.0f, 0.0f, 0.0f, 1.0f}
5001 );
5002 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
5003 } else {
5004 colorMatrix = mClientColorMatrix * mDaltonizer();
5005 }
5006
5007 if (mCurrentState.colorMatrix != colorMatrix) {
5008 mCurrentState.colorMatrix = colorMatrix;
5009 mCurrentState.colorMatrixChanged = true;
5010 setTransactionFlags(eTransactionNeeded);
5011 }
5012}
5013
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005014status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005015#pragma clang diagnostic push
5016#pragma clang diagnostic error "-Wswitch-enum"
5017 switch (static_cast<ISurfaceComposerTag>(code)) {
5018 // These methods should at minimum make sure that the client requested
5019 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005020 case BOOT_FINISHED:
5021 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005022 case CREATE_DISPLAY:
5023 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005024 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005025 case GET_ANIMATION_FRAME_STATS:
5026 case GET_HDR_CAPABILITIES:
5027 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08005028 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005029 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005030 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005031 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005032 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005033 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005034 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
5035 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005036 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5037 IPCThreadState* ipc = IPCThreadState::self();
5038 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5039 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005040 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005041 }
Robert Carr1db73f62016-12-21 12:58:51 -08005042 return OK;
5043 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005044 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005045 IPCThreadState* ipc = IPCThreadState::self();
5046 const int pid = ipc->getCallingPid();
5047 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005048 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5049 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005050 return PERMISSION_DENIED;
5051 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005052 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005053 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005054 // Used by apps to hook Choreographer to SurfaceFlinger.
5055 case CREATE_DISPLAY_EVENT_CONNECTION:
5056 // The following calls are currently used by clients that do not
5057 // request necessary permissions. However, they do not expose any secret
5058 // information, so it is OK to pass them.
5059 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07005060 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005061 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005062 case GET_PHYSICAL_DISPLAY_IDS:
5063 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005064 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005065 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005066 case GET_DISPLAY_CONFIGS:
5067 case GET_DISPLAY_STATS:
5068 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5069 // Calling setTransactionState is safe, because you need to have been
5070 // granted a reference to Client* and Handle* to do anything with it.
5071 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005072 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005073 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005074 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005075 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00005076 case IS_WIDE_COLOR_DISPLAY:
5077 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5078 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005079 return OK;
5080 }
5081 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08005082 case CAPTURE_SCREEN:
5083 case ADD_REGION_SAMPLING_LISTENER:
5084 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005085 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005086 IPCThreadState* ipc = IPCThreadState::self();
5087 const int pid = ipc->getCallingPid();
5088 const int uid = ipc->getCallingUid();
5089 if ((uid != AID_GRAPHICS) &&
5090 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5091 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5092 return PERMISSION_DENIED;
5093 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005094 return OK;
5095 }
5096 // The following codes are deprecated and should never be allowed to access SF.
5097 case CONNECT_DISPLAY_UNUSED:
5098 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5099 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5100 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005101 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005102 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005103
5104 // These codes are used for the IBinder protocol to either interrogate the recipient
5105 // side of the transaction for its canonical interface descriptor or to dump its state.
5106 // We let them pass by default.
5107 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5108 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5109 code == IBinder::SYSPROPS_TRANSACTION) {
5110 return OK;
5111 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005112 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005113 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07005114 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005115 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5116 return OK;
5117 }
5118 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5119 return PERMISSION_DENIED;
5120#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005121}
5122
Ana Krulec13be8ad2018-08-21 02:43:56 +00005123status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5124 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005125 status_t credentialCheck = CheckTransactCodeCredentials(code);
5126 if (credentialCheck != OK) {
5127 return credentialCheck;
5128 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005129
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005130 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5131 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005132 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005133 IPCThreadState* ipc = IPCThreadState::self();
5134 const int uid = ipc->getCallingUid();
5135 if (CC_UNLIKELY(uid != AID_SYSTEM
5136 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005137 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005138 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005139 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005140 return PERMISSION_DENIED;
5141 }
5142 int n;
5143 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005144 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005145 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005146 return NO_ERROR;
5147 case 1002: // SHOW_UPDATES
5148 n = data.readInt32();
5149 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005150 invalidateHwcGeometry();
5151 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005152 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005153 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005154 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005155 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005156 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005157 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005158 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005159 setTransactionFlags(
5160 eTransactionNeeded|
5161 eDisplayTransactionNeeded|
5162 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005163 return NO_ERROR;
5164 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005165 case 1006:{ // send empty update
5166 signalRefresh();
5167 return NO_ERROR;
5168 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005169 case 1008: // toggle use of hw composer
5170 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005171 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07005172 invalidateHwcGeometry();
5173 repaintEverything();
5174 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005175 case 1009: // toggle use of transform hint
5176 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005177 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07005178 invalidateHwcGeometry();
5179 repaintEverything();
5180 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005181 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005182 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005183 reply->writeInt32(0);
5184 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005185 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005186 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005187 return NO_ERROR;
5188 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005189 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005190 if (!display) {
5191 return NAME_NOT_FOUND;
5192 }
5193
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005194 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005195 return NO_ERROR;
5196 }
5197 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005198 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005199 // daltonize
5200 n = data.readInt32();
5201 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005202 case 1:
5203 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5204 break;
5205 case 2:
5206 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5207 break;
5208 case 3:
5209 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5210 break;
5211 default:
5212 mDaltonizer.setType(ColorBlindnessType::None);
5213 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005214 }
5215 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005216 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005217 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005218 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005219 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005220
5221 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005222 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005223 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005224 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005225 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005226 // apply a color matrix
5227 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005228 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005229 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005230 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005231 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005232 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005233 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005234 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005235 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005236 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005237 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005238
5239 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5240 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005241 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005242 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5243 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5244 }
5245
Chia-I Wu28f320b2018-05-03 11:02:56 -07005246 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005247 return NO_ERROR;
5248 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005249 // This is an experimental interface
5250 // Needs to be shifted to proper binder interface when we productize
5251 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005252 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005253 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005254 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005255 return NO_ERROR;
5256 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005257 case 1017: {
5258 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005259 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005260 return NO_ERROR;
5261 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005262 case 1018: { // Modify Choreographer's phase offset
5263 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005264 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005265 return NO_ERROR;
5266 }
5267 case 1019: { // Modify SurfaceFlinger's phase offset
5268 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005269 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005270 return NO_ERROR;
5271 }
Irvel468051e2016-06-13 16:44:44 -07005272 case 1020: { // Layer updates interceptor
5273 n = data.readInt32();
5274 if (n) {
5275 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005276 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005277 }
5278 else{
5279 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005280 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005281 }
5282 return NO_ERROR;
5283 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005284 case 1021: { // Disable HWC virtual displays
5285 n = data.readInt32();
5286 mUseHwcVirtualDisplays = !n;
5287 return NO_ERROR;
5288 }
Romain Guy0147a172017-06-01 13:53:56 -07005289 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005290 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005291 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005292
Chia-I Wu28f320b2018-05-03 11:02:56 -07005293 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005294 return NO_ERROR;
5295 }
Romain Guy54f154a2017-10-24 21:40:32 +01005296 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005297 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005298 invalidateHwcGeometry();
5299 repaintEverything();
5300 return NO_ERROR;
5301 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005302 // Deprecate, use 1030 to check whether the device is color managed.
5303 case 1024: {
5304 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005305 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005306 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005307 n = data.readInt32();
5308 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005309 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005310 Mutex::Autolock lock(mStateLock);
5311 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005312 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005313 reply->writeInt32(NO_ERROR);
5314 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005315 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005316 bool writeFile = false;
5317 {
5318 Mutex::Autolock lock(mStateLock);
5319 mTracingEnabledChanged = true;
5320 writeFile = mTracing.disable();
5321 }
5322
5323 if (writeFile) {
5324 reply->writeInt32(mTracing.writeToFile());
5325 } else {
5326 reply->writeInt32(NO_ERROR);
5327 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005328 }
5329 return NO_ERROR;
5330 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005331 case 1026: { // Get layer tracing status
5332 reply->writeBool(mTracing.isEnabled());
5333 return NO_ERROR;
5334 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005335 // Is a DisplayColorSetting supported?
5336 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005337 const auto display = getDefaultDisplayDevice();
5338 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005339 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005340 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005341
5342 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5343 switch (setting) {
5344 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005345 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005346 break;
5347 case DisplayColorSetting::UNMANAGED:
5348 reply->writeBool(true);
5349 break;
5350 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005351 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005352 break;
5353 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005354 reply->writeBool(
5355 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005356 break;
5357 }
5358 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005359 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005360 // Is VrFlinger active?
5361 case 1028: {
5362 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005363 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005364 return NO_ERROR;
5365 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005366 // Set buffer size for SF tracing (value in KB)
5367 case 1029: {
5368 n = data.readInt32();
5369 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5370 ALOGW("Invalid buffer size: %d KB", n);
5371 reply->writeInt32(BAD_VALUE);
5372 return BAD_VALUE;
5373 }
5374
5375 ALOGD("Updating trace buffer to %d KB", n);
5376 mTracing.setBufferSize(n * 1024);
5377 reply->writeInt32(NO_ERROR);
5378 return NO_ERROR;
5379 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005380 // Is device color managed?
5381 case 1030: {
5382 reply->writeBool(useColorManagement);
5383 return NO_ERROR;
5384 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005385 // Override default composition data space
5386 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5387 // && adb shell stop zygote && adb shell start zygote
5388 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5389 // adb shell stop zygote && adb shell start zygote
5390 case 1031: {
5391 Mutex::Autolock _l(mStateLock);
5392 n = data.readInt32();
5393 if (n) {
5394 n = data.readInt32();
5395 if (n) {
5396 Dataspace dataspace = static_cast<Dataspace>(n);
5397 if (!validateCompositionDataspace(dataspace)) {
5398 return BAD_VALUE;
5399 }
5400 mDefaultCompositionDataspace = dataspace;
5401 }
5402 n = data.readInt32();
5403 if (n) {
5404 Dataspace dataspace = static_cast<Dataspace>(n);
5405 if (!validateCompositionDataspace(dataspace)) {
5406 return BAD_VALUE;
5407 }
5408 mWideColorGamutCompositionDataspace = dataspace;
5409 }
5410 } else {
5411 // restore composition data space.
5412 mDefaultCompositionDataspace = defaultCompositionDataspace;
5413 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5414 }
5415 return NO_ERROR;
5416 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005417 // Set trace flags
5418 case 1033: {
5419 n = data.readUint32();
5420 ALOGD("Updating trace flags to 0x%x", n);
5421 mTracing.setTraceFlags(n);
5422 reply->writeInt32(NO_ERROR);
5423 return NO_ERROR;
5424 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005425 case 1034: {
5426 // TODO(b/129297325): expose this via developer menu option
5427 n = data.readInt32();
5428 if (n && !mRefreshRateOverlay) {
5429 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5430 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
5431 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
5432 } else if (!n) {
5433 mRefreshRateOverlay.reset();
5434 }
5435 return NO_ERROR;
5436 }
Ady Abraham34392f72019-04-10 11:29:27 -07005437 case 1035: {
5438 n = data.readInt32();
5439 mDebugDisplayConfigSetByBackdoor = false;
5440 if (n >= 0) {
5441 const auto displayToken = getInternalDisplayToken();
5442 status_t result = setAllowedDisplayConfigs(displayToken, {n});
5443 if (result != NO_ERROR) {
5444 return result;
5445 }
5446 mDebugDisplayConfigSetByBackdoor = true;
5447 }
5448 return NO_ERROR;
5449 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005450 }
5451 }
5452 return err;
5453}
5454
Steven Thomas6d8110b2017-08-31 18:24:21 -07005455void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005456 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005457 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005458}
5459
Ana Krulec7d1d6832018-12-27 11:10:09 -08005460void SurfaceFlinger::repaintEverythingForHWC() {
5461 mRepaintEverything = true;
5462 mEventQueue->invalidateForHWC();
5463}
5464
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005465// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5466class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005467public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005468 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5469 ~WindowDisconnector() {
5470 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005471 }
5472
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005473private:
5474 ANativeWindow* mWindow;
5475 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005476};
5477
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005478status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005479 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
5480 const Dataspace reqDataspace,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005481 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005482 uint32_t reqWidth, uint32_t reqHeight,
5483 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08005484 ISurfaceComposer::Rotation rotation,
5485 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005486 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005487
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005488 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005489
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005490 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5491
Chia-I Wu20261cb2018-08-23 12:55:44 -07005492 sp<DisplayDevice> display;
5493 {
5494 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005495
Chia-I Wu20261cb2018-08-23 12:55:44 -07005496 display = getDisplayDeviceLocked(displayToken);
5497 if (!display) return BAD_VALUE;
5498
Chia-I Wucb023152018-08-28 12:57:23 -07005499 // set the requested width/height to the logical display viewport size
5500 // by default
5501 if (reqWidth == 0 || reqHeight == 0) {
5502 reqWidth = uint32_t(display->getViewport().width());
5503 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005504 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005505 }
5506
Peiyong Lin0e003c92018-09-17 11:09:51 -07005507 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005508 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005509
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005510 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5511 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005512 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005513 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005514}
5515
Robert Carr866455f2019-04-02 16:28:26 -07005516status_t SurfaceFlinger::captureLayers(
5517 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5518 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5519 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5520 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005521 ATRACE_CALL();
5522
5523 class LayerRenderArea : public RenderArea {
5524 public:
Robert Carr578038f2018-03-09 12:25:24 -08005525 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005526 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5527 bool childrenOnly)
5528 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005529 mLayer(layer),
5530 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005531 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005532 mFlinger(flinger),
5533 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005534 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005535 Rect getBounds() const override {
5536 const Layer::State& layerState(mLayer->getDrawingState());
5537 return mLayer->getBufferSize(layerState);
5538 }
Marissa Wall61c58622018-07-18 10:12:20 -07005539 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005540 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005541 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005542 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005543 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005544 }
chaviwa76b2712017-09-20 12:02:26 -07005545 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005546 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005547 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005548 Rect getSourceCrop() const override {
5549 if (mCrop.isEmpty()) {
5550 return getBounds();
5551 } else {
5552 return mCrop;
5553 }
5554 }
Robert Carr578038f2018-03-09 12:25:24 -08005555 class ReparentForDrawing {
5556 public:
5557 const sp<Layer>& oldParent;
5558 const sp<Layer>& newParent;
5559
Vishnu Nair4351ad52019-02-11 14:13:02 -08005560 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5561 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005562 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005563 // Compute and cache the bounds for the new parent layer.
5564 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005565 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005566 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005567 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005568 };
5569
5570 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005571 const Rect sourceCrop = getSourceCrop();
5572 // no need to check rotation because there is none
5573 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5574 sourceCrop.height() != getReqHeight();
5575
Robert Carr578038f2018-03-09 12:25:24 -08005576 if (!mChildrenOnly) {
5577 mTransform = mLayer->getTransform().inverse();
5578 drawLayers();
5579 } else {
5580 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005581 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005582 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
Evan Roskya1f1e152019-01-24 16:17:46 -08005583 bounds.getWidth(), bounds.getHeight(), 0,
5584 LayerMetadata()));
Robert Carr578038f2018-03-09 12:25:24 -08005585
Vishnu Nair4351ad52019-02-11 14:13:02 -08005586 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005587 drawLayers();
5588 }
5589 }
chaviwa76b2712017-09-20 12:02:26 -07005590
chaviwa76b2712017-09-20 12:02:26 -07005591 private:
chaviw7206d492017-11-10 16:16:12 -08005592 const sp<Layer> mLayer;
5593 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005594
5595 // In the "childrenOnly" case we reparent the children to a screenshot
5596 // layer which has no properties set and which does not draw.
5597 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005598 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005599 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005600
5601 SurfaceFlinger* mFlinger;
5602 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005603 };
5604
Robert Carrc0df3122019-04-11 13:18:21 -07005605 int reqWidth = 0;
5606 int reqHeight = 0;
5607 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005608 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005609 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
chaviw7206d492017-11-10 16:16:12 -08005610
Robert Carrc0df3122019-04-11 13:18:21 -07005611 {
5612 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005613
Robert Carrc0df3122019-04-11 13:18:21 -07005614 parent = fromHandle(layerHandleBinder);
5615 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5616 ALOGE("captureLayers called with an invalid or removed parent");
5617 return NAME_NOT_FOUND;
5618 }
5619
5620 const int uid = IPCThreadState::self()->getCallingUid();
5621 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5622 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5623 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5624 return PERMISSION_DENIED;
5625 }
5626
5627 if (sourceCrop.width() <= 0) {
5628 crop.left = 0;
5629 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
5630 }
5631
5632 if (sourceCrop.height() <= 0) {
5633 crop.top = 0;
5634 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
5635 }
5636 reqWidth = crop.width() * frameScale;
5637 reqHeight = crop.height() * frameScale;
5638
5639 for (const auto& handle : excludeHandles) {
5640 sp<Layer> excludeLayer = fromHandle(handle);
5641 if (excludeLayer != nullptr) {
5642 excludeLayers.emplace(excludeLayer);
5643 } else {
5644 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5645 return NAME_NOT_FOUND;
5646 }
5647 }
5648 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005649
Chia-I Wu20261cb2018-08-23 12:55:44 -07005650 // really small crop or frameScale
5651 if (reqWidth <= 0) {
5652 reqWidth = 1;
5653 }
5654 if (reqHeight <= 0) {
5655 reqHeight = 1;
5656 }
5657
Robert Carr866455f2019-04-02 16:28:26 -07005658 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
5659 auto traverseLayers = [parent, childrenOnly,
5660 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005661 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5662 if (!layer->isVisible()) {
5663 return;
Robert Carr578038f2018-03-09 12:25:24 -08005664 } else if (childrenOnly && layer == parent.get()) {
5665 return;
chaviwa76b2712017-09-20 12:02:26 -07005666 }
Robert Carr866455f2019-04-02 16:28:26 -07005667
5668 sp<Layer> p = layer;
5669 while (p != nullptr) {
5670 if (excludeLayers.count(p) != 0) {
5671 return;
5672 }
5673 p = p->getParent();
5674 }
5675
chaviwa76b2712017-09-20 12:02:26 -07005676 visitor(layer);
5677 });
5678 };
Robert Carr108b2c72019-04-02 16:32:58 -07005679
5680 bool outCapturedSecureLayers = false;
5681 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5682 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005683}
5684
5685status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5686 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005687 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005688 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005689 bool useIdentityTransform,
5690 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005691 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005692
Peiyong Lin0e003c92018-09-17 11:09:51 -07005693 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005694 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5695 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005696 *outBuffer =
5697 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5698 static_cast<android_pixel_format>(reqPixelFormat), 1,
5699 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005700
Robert Carr108b2c72019-04-02 16:32:58 -07005701 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5702 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005703}
5704
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005705status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5706 TraverseLayersFunction traverseLayers,
5707 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005708 bool useIdentityTransform,
5709 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005710 // This mutex protects syncFd and captureResult for communication of the return values from the
5711 // main thread back to this Binder thread
5712 std::mutex captureMutex;
5713 std::condition_variable captureCondition;
5714 std::unique_lock<std::mutex> captureLock(captureMutex);
5715 int syncFd = -1;
5716 std::optional<status_t> captureResult;
5717
Robert Carr03480e22018-01-04 16:02:06 -08005718 const int uid = IPCThreadState::self()->getCallingUid();
5719 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5720
Dominik Laskowski8c001672018-05-30 16:52:06 -07005721 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005722 // If there is a refresh pending, bug out early and tell the binder thread to try again
5723 // after the refresh.
5724 if (mRefreshPending) {
5725 ATRACE_NAME("Skipping screenshot for now");
5726 std::unique_lock<std::mutex> captureLock(captureMutex);
5727 captureResult = std::make_optional<status_t>(EAGAIN);
5728 captureCondition.notify_one();
5729 return;
5730 }
5731
5732 status_t result = NO_ERROR;
5733 int fd = -1;
5734 {
5735 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005736 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005737 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005738 useIdentityTransform, forSystem, &fd,
5739 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005740 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005741 }
5742
5743 {
5744 std::unique_lock<std::mutex> captureLock(captureMutex);
5745 syncFd = fd;
5746 captureResult = std::make_optional<status_t>(result);
5747 captureCondition.notify_one();
5748 }
5749 });
5750
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005751 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005752 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005753 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005754 while (*captureResult == EAGAIN) {
5755 captureResult.reset();
5756 result = postMessageAsync(message);
5757 if (result != NO_ERROR) {
5758 return result;
5759 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005760 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005761 }
5762 result = *captureResult;
5763 }
5764
5765 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005766 sync_wait(syncFd, -1);
5767 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005768 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005769
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005770 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005771}
5772
chaviwa76b2712017-09-20 12:02:26 -07005773void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005774 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005775 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5776 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005777 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005778
chaviwa76b2712017-09-20 12:02:26 -07005779 const auto reqWidth = renderArea.getReqWidth();
5780 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005781 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005782 const auto transform = renderArea.getTransform();
5783 const auto sourceCrop = renderArea.getSourceCrop();
Dan Stozac1879002014-05-22 15:59:05 -07005784
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005785 renderengine::DisplaySettings clientCompositionDisplay;
5786 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005787
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005788 // assume that bounds are never offset, and that they are the same as the
5789 // buffer bounds.
5790 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005791 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005792 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005793
5794 // Now take into account the rotation flag. We append a transform that
5795 // rotates the layer stack about the origin, then translate by buffer
5796 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005797 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005798 int displacementX = 0;
5799 int displacementY = 0;
5800 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5801 switch (rotation) {
5802 case ui::Transform::ROT_90:
5803 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005804 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005805 break;
5806 case ui::Transform::ROT_180:
5807 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005808 displacementY = renderArea.getBounds().getWidth();
5809 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005810 break;
5811 case ui::Transform::ROT_270:
5812 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005813 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005814 break;
5815 default:
5816 break;
5817 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005818
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005819 // We need to transform the clipping window into the right spot.
5820 // First, rotate the clipping rectangle by the rotation hint to get the
5821 // right orientation
5822 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5823 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5824 const vec4 rotClipTL = rotMatrix * clipTL;
5825 const vec4 rotClipBR = rotMatrix * clipBR;
5826 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5827 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5828 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5829 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5830
5831 // Now reposition the clipping rectangle with the displacement vector
5832 // computed above.
5833 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005834 clientCompositionDisplay.clip =
5835 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5836 newClipRight + displacementX, newClipBottom + displacementY);
5837
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005838 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005839 clientCompositionDisplay.globalTransform =
5840 clipTransform * clientCompositionDisplay.globalTransform;
5841
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005842 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5843 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005844
chaviw50da5042018-04-09 13:49:37 -07005845 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005846
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005847 renderengine::LayerSettings fillLayer;
5848 fillLayer.source.buffer.buffer = nullptr;
5849 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5850 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5851 fillLayer.alpha = half(alpha);
5852 clientCompositionLayers.push_back(fillLayer);
5853
5854 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005855 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005856 renderengine::LayerSettings layerSettings;
5857 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005858 false, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005859 if (prepared) {
5860 clientCompositionLayers.push_back(layerSettings);
5861 }
chaviwa76b2712017-09-20 12:02:26 -07005862 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005863
5864 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005865 // Use an empty fence for the buffer fence, since we just created the buffer so
5866 // there is no need for synchronization with the GPU.
5867 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005868 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005869 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005870 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005871 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005872
5873 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005874}
5875
chaviwa76b2712017-09-20 12:02:26 -07005876status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5877 TraverseLayersFunction traverseLayers,
5878 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005879 bool useIdentityTransform, bool forSystem,
5880 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005881 ATRACE_CALL();
5882
chaviwa76b2712017-09-20 12:02:26 -07005883 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005884 outCapturedSecureLayers =
5885 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005886 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005887
Robert Carr03480e22018-01-04 16:02:06 -08005888 // We allow the system server to take screenshots of secure layers for
5889 // use in situations like the Screen-rotation animation and place
5890 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005891 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005892 ALOGW("FB is protected: PERMISSION_DENIED");
5893 return PERMISSION_DENIED;
5894 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005895 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005896 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005897}
5898
chaviw95ef3c42019-02-14 10:55:09 -08005899void SurfaceFlinger::setInputWindowsFinished() {
5900 Mutex::Autolock _l(mStateLock);
5901
5902 mPendingSyncInputWindows = false;
5903 mTransactionCV.broadcast();
5904}
chaviw5f21a5e2019-02-14 10:00:34 -08005905
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005906// ---------------------------------------------------------------------------
5907
Dan Stoza412903f2017-04-27 13:42:17 -07005908void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5909 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005910}
5911
Dan Stoza412903f2017-04-27 13:42:17 -07005912void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5913 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005914}
5915
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005916void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005917 const LayerVector::Visitor& visitor) {
5918 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005919 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005920 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005921 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005922 continue;
5923 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005924 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005925 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005926 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005927 return;
5928 }
chaviwa76b2712017-09-20 12:02:26 -07005929 if (!layer->isVisible()) {
5930 return;
5931 }
5932 visitor(layer);
5933 });
5934 }
5935}
5936
Dominik Laskowski22488f62019-03-28 09:53:04 -07005937void SurfaceFlinger::setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
5938 const std::vector<int32_t>& allowedConfigs) {
5939 if (!display->isPrimary()) {
Ady Abraham838de062019-02-04 10:24:03 -08005940 return;
5941 }
5942
5943 ALOGV("Updating allowed configs");
Dominik Laskowski22488f62019-03-28 09:53:04 -07005944 mAllowedDisplayConfigs = DisplayConfigs(allowedConfigs.begin(), allowedConfigs.end());
Ady Abraham838de062019-02-04 10:24:03 -08005945
Ady Abrahamde3b67b2019-03-25 16:38:10 -07005946 // Set the highest allowed config by iterating backwards on available refresh rates
Dominik Laskowski22488f62019-03-28 09:53:04 -07005947 const auto& refreshRates = mRefreshRateConfigs.getRefreshRates();
Ady Abrahamde3b67b2019-03-25 16:38:10 -07005948 for (auto iter = refreshRates.crbegin(); iter != refreshRates.crend(); ++iter) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07005949 if (iter->second && isDisplayConfigAllowed(iter->second->configId)) {
Ady Abrahamde3b67b2019-03-25 16:38:10 -07005950 ALOGV("switching to config %d", iter->second->configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -07005951 setDesiredActiveConfig(
5952 {iter->first, iter->second->configId, Scheduler::ConfigEvent::Changed});
Ady Abrahamde3b67b2019-03-25 16:38:10 -07005953 break;
Ady Abraham97d04232019-03-05 19:48:12 -08005954 }
5955 }
Ady Abraham838de062019-02-04 10:24:03 -08005956}
5957
Dominik Laskowski22488f62019-03-28 09:53:04 -07005958status_t SurfaceFlinger::setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abraham838de062019-02-04 10:24:03 -08005959 const std::vector<int32_t>& allowedConfigs) {
5960 ATRACE_CALL();
5961
Dominik Laskowski22488f62019-03-28 09:53:04 -07005962 if (!displayToken || allowedConfigs.empty()) {
Ady Abraham838de062019-02-04 10:24:03 -08005963 return BAD_VALUE;
5964 }
5965
Ady Abraham34392f72019-04-10 11:29:27 -07005966 if (mDebugDisplayConfigSetByBackdoor) {
5967 // ignore this request as config is overridden by backdoor
5968 return NO_ERROR;
5969 }
5970
Ady Abraham838de062019-02-04 10:24:03 -08005971 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski22488f62019-03-28 09:53:04 -07005972 const auto display = getDisplayDeviceLocked(displayToken);
5973 if (!display) {
5974 ALOGE("Attempt to set allowed display configs for invalid display token %p",
5975 displayToken.get());
5976 } else if (display->isVirtual()) {
5977 ALOGW("Attempt to set allowed display configs for virtual display");
5978 } else {
5979 setAllowedDisplayConfigsInternal(display, allowedConfigs);
5980 }
Ady Abraham838de062019-02-04 10:24:03 -08005981 }));
Dominik Laskowski22488f62019-03-28 09:53:04 -07005982
Ady Abraham838de062019-02-04 10:24:03 -08005983 return NO_ERROR;
5984}
5985
Dominik Laskowski22488f62019-03-28 09:53:04 -07005986status_t SurfaceFlinger::getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005987 std::vector<int32_t>* outAllowedConfigs) {
5988 ATRACE_CALL();
5989
Dominik Laskowski22488f62019-03-28 09:53:04 -07005990 if (!displayToken || !outAllowedConfigs) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005991 return BAD_VALUE;
5992 }
5993
Dominik Laskowski22488f62019-03-28 09:53:04 -07005994 Mutex::Autolock lock(mStateLock);
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005995
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005996 const auto display = getDisplayDeviceLocked(displayToken);
5997 if (!display) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005998 return NAME_NOT_FOUND;
5999 }
6000
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006001 if (display->isPrimary()) {
6002 outAllowedConfigs->assign(mAllowedDisplayConfigs.begin(), mAllowedDisplayConfigs.end());
6003 }
6004
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006005 return NO_ERROR;
6006}
6007
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006008void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006009 mFlinger->setInputWindowsFinished();
6010}
6011
Robert Carrc0df3122019-04-11 13:18:21 -07006012sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6013 BBinder *b = handle->localBinder();
6014 if (b == nullptr) {
6015 return nullptr;
6016 }
6017 auto it = mLayersByLocalBinderToken.find(b);
6018 if (it != mLayersByLocalBinderToken.end()) {
6019 return it->second.promote();
6020 }
6021 return nullptr;
6022}
6023
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006024} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006025
Mathias Agopian3f844832013-08-07 21:24:32 -07006026#if defined(__gl_h_)
6027#error "don't include gl/gl.h in this file"
6028#endif
6029
6030#if defined(__gl2_h_)
6031#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006032#endif