blob: bc134cb158856f918bc80b5047a6e186432206c6 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Alec Mourie7d1d4a2019-02-05 01:13:46 +000017//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070022#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080023
24#include <algorithm>
25#include <cinttypes>
26#include <cmath>
27#include <cstdint>
28#include <functional>
29#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070030#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080031#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Lloyd Pique70d91362018-10-18 16:02:55 -070040#include <compositionengine/CompositionEngine.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070041#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070042#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080043#include <compositionengine/Layer.h>
44#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070045#include <compositionengine/RenderSurface.h>
Lloyd Pique0b785d82018-12-04 17:25:27 -080046#include <compositionengine/impl/LayerCompositionState.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070047#include <compositionengine/impl/OutputCompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080048#include <compositionengine/impl/OutputLayerCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080049#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070052#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080053#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080054#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080055#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070056#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070057#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070058#include <ui/ColorSpace.h>
59#include <ui/DebugUtils.h>
60#include <ui/DisplayInfo.h>
61#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <ui/GraphicBufferAllocator.h>
63#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070064#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070066#include <utils/String16.h>
67#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070068#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080069#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071
Mathias Agopian921e6ac2012-07-23 23:11:29 -070072#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070073#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074
Robert Carr578038f2018-03-09 12:25:24 -080075#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070076#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070077#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020078#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080079#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020080#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080081#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080082#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070084#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080085#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070086#include "NativeWindowSurface.h"
Ady Abraham03b02dd2019-03-21 15:40:11 -070087#include "RefreshRateOverlay.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070088#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070090#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091
Steven Thomasb02664d2017-07-26 18:48:28 -070092#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070093#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070094#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070095#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070096#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070097#include "Effects/Daltonizer.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -070098#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070099#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700100#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700101#include "Scheduler/EventControlThread.h"
102#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700103#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700104#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700105#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700106#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800107#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700108
Mathias Agopianff2ed702013-09-01 21:36:12 -0700109#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700110
David Sodman7e4ae112018-02-09 15:02:28 -0800111#include "android-base/stringprintf.h"
112
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900113#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800114#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
115#include <android/hardware/configstore/1.1/types.h>
Ady Abraham8532d012019-05-08 14:50:56 -0700116#include <android/hardware/power/1.0/IPower.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900117#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900118
chaviw1d044282017-09-27 12:19:28 -0700119#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900120#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700121
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800122namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700123
Jaesoo Lee43518572017-01-23 19:03:16 +0900124using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900125using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900126using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800127
Ady Abraham8532d012019-05-08 14:50:56 -0700128using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800129using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700130using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700131using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800132using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700133using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700134using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900135
Steven Thomasb02664d2017-07-26 18:48:28 -0700136namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700137
138#pragma clang diagnostic push
139#pragma clang diagnostic error "-Wswitch-enum"
140
141bool isWideColorMode(const ColorMode colorMode) {
142 switch (colorMode) {
143 case ColorMode::DISPLAY_P3:
144 case ColorMode::ADOBE_RGB:
145 case ColorMode::DCI_P3:
146 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700147 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700148 case ColorMode::BT2100_PQ:
149 case ColorMode::BT2100_HLG:
150 return true;
151 case ColorMode::NATIVE:
152 case ColorMode::STANDARD_BT601_625:
153 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
154 case ColorMode::STANDARD_BT601_525:
155 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
156 case ColorMode::STANDARD_BT709:
157 case ColorMode::SRGB:
158 return false;
159 }
160 return false;
161}
162
Peiyong Lin34ea5b92019-03-15 18:40:15 -0700163bool isHdrColorMode(const ColorMode colorMode) {
164 switch (colorMode) {
165 case ColorMode::BT2100_PQ:
166 case ColorMode::BT2100_HLG:
167 return true;
168 case ColorMode::DISPLAY_P3:
169 case ColorMode::ADOBE_RGB:
170 case ColorMode::DCI_P3:
171 case ColorMode::BT2020:
172 case ColorMode::DISPLAY_BT2020:
173 case ColorMode::NATIVE:
174 case ColorMode::STANDARD_BT601_625:
175 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
176 case ColorMode::STANDARD_BT601_525:
177 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
178 case ColorMode::STANDARD_BT709:
179 case ColorMode::SRGB:
180 return false;
181 }
182 return false;
183}
184
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700185ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
186 switch (rotation) {
187 case ISurfaceComposer::eRotateNone:
188 return ui::Transform::ROT_0;
189 case ISurfaceComposer::eRotate90:
190 return ui::Transform::ROT_90;
191 case ISurfaceComposer::eRotate180:
192 return ui::Transform::ROT_180;
193 case ISurfaceComposer::eRotate270:
194 return ui::Transform::ROT_270;
195 }
196 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
197 return ui::Transform::ROT_0;
198}
199
Peiyong Linfca547f2018-07-09 13:03:33 -0700200#pragma clang diagnostic pop
201
Steven Thomasb02664d2017-07-26 18:48:28 -0700202class ConditionalLock {
203public:
204 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
205 if (lock) {
206 mMutex.lock();
207 }
208 }
209 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
210private:
211 Mutex& mMutex;
212 bool mLocked;
213};
Peiyong Linfca547f2018-07-09 13:03:33 -0700214
Peiyong Lin9d846a52018-11-05 13:18:20 -0800215// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
216bool validateCompositionDataspace(Dataspace dataspace) {
217 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
218}
219
Steven Thomasb02664d2017-07-26 18:48:28 -0700220} // namespace anonymous
221
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800222// ---------------------------------------------------------------------------
223
Mathias Agopian99b49842011-06-27 16:05:52 -0700224const String16 sHardwareTest("android.permission.HARDWARE_TEST");
225const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
226const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
227const String16 sDump("android.permission.DUMP");
228
229// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700230int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700231bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800232uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800233bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800234bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800235int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600236bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700237int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700238bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700239bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700240Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
241ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
242Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
243ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700244
Kalle Raitaa099a242017-01-11 11:17:29 -0800245std::string getHwcServiceName() {
246 char value[PROPERTY_VALUE_MAX] = {};
247 property_get("debug.sf.hwc_service_name", value, "default");
248 ALOGI("Using HWComposer service: '%s'", value);
249 return std::string(value);
250}
251
252bool useTrebleTestingOverride() {
253 char value[PROPERTY_VALUE_MAX] = {};
254 property_get("debug.sf.treble_testing_override", value, "false");
255 ALOGI("Treble testing override: '%s'", value);
256 return std::string(value) == "true";
257}
258
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800259std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
260 switch(displayColorSetting) {
261 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700262 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800263 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700264 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800265 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700266 return std::string("Enhanced");
267 default:
268 return std::string("Unknown ") +
269 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800270 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800271}
272
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700273SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800274
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700275SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
276 : mFactory(factory),
277 mPhaseOffsets(mFactory.createPhaseOffsets()),
278 mInterceptor(mFactory.createSurfaceInterceptor(this)),
279 mTimeStats(mFactory.createTimeStats()),
280 mEventQueue(mFactory.createMessageQueue()),
281 mCompositionEngine(mFactory.createCompositionEngine()) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800282
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700283SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800284 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800285
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900286 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800287
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900288 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700289
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900290 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700291
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900292 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800293
Steven Thomas050b2c82017-03-06 11:45:16 -0800294 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900295 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800296
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900297 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800298
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900299 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700300
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900301 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600302
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900303 mDefaultCompositionDataspace =
304 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700305 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
306 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900307 defaultCompositionDataspace = mDefaultCompositionDataspace;
308 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
309 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
310 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
311 wideColorGamutCompositionPixelFormat =
312 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700313
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900314 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800315
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900316 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
317 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
318 switch (tmpPrimaryDisplayOrientation) {
319 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700320 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800321 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900322 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700323 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800324 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900325 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700326 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800327 break;
328 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700329 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800330 break;
331 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700332 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800333
Sundong Ahn85131bd2019-02-18 15:51:53 +0900334 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800335
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800336 // debugging stuff...
337 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700338
Mathias Agopianb4b17302013-03-20 18:36:41 -0700339 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700340 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700341
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800342 property_get("debug.sf.showupdates", value, "0");
343 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700344
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700345 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000346
347 // DDMS debugging deprecated (b/120782499)
348 property_get("debug.sf.ddms", value, "0");
349 int debugDdms = atoi(value);
350 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700351
352 property_get("debug.sf.disable_backpressure", value, "0");
353 mPropagateBackpressure = !atoi(value);
354 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700355
Ady Abrahamadb9a992019-09-19 21:21:55 +0000356 property_get("debug.sf.enable_gl_backpressure", value, "0");
357 mPropagateBackpressureClientComposition = atoi(value);
358 ALOGI_IF(mPropagateBackpressureClientComposition,
359 "Enabling backpressure propagation for Client Composition");
360
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800361 property_get("debug.sf.enable_hwc_vds", value, "0");
362 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800363 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800364
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800365 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800366 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800367 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700368
Yiwei Zhang243b3782018-05-15 17:40:04 -0700369 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700370 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
371 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
372
Ana Krulece5a06e02019-03-06 17:09:03 -0800373 mUseSmart90ForVideo = use_smart_90_for_video(false);
Ana Krulecba13ab32019-02-20 14:14:12 -0800374 property_get("debug.sf.use_smart_90_for_video", value, "0");
Ana Krulece5a06e02019-03-06 17:09:03 -0800375
376 int int_value = atoi(value);
377 if (int_value) {
378 mUseSmart90ForVideo = true;
379 }
Ana Krulecba13ab32019-02-20 14:14:12 -0800380
Dan Stozaec460082018-12-17 15:35:09 -0800381 property_get("debug.sf.luma_sampling", value, "1");
382 mLumaSampling = atoi(value);
383
Ana Krulec757f63a2019-01-25 10:46:18 -0800384 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
385 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700386
Romain Guy11d63f42017-07-20 12:47:14 -0700387 // We should be reading 'persist.sys.sf.color_saturation' here
388 // but since /data may be encrypted, we need to wait until after vold
389 // comes online to attempt to read the property. The property is
390 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800391
392 if (useTrebleTestingOverride()) {
393 // Without the override SurfaceFlinger cannot connect to HIDL
394 // services that are not listed in the manifests. Considered
395 // deriving the setting from the set service name, but it
396 // would be brittle if the name that's not 'default' is used
397 // for production purposes later on.
398 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
399 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800400}
401
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800402void SurfaceFlinger::onFirstRef()
403{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800404 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800405}
406
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700407SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800408
Dan Stozac7014012014-02-14 15:03:43 -0800409void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800410{
411 // the window manager died on us. prepare its eulogy.
412
Andy McFadden13a082e2012-08-24 10:16:42 -0700413 // restore initial conditions (default device unblank, etc)
414 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800415
416 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700417 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800418}
419
Robert Carr1db73f62016-12-21 12:58:51 -0800420static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700421 status_t err = client->initCheck();
422 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800423 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800424 }
Robert Carr1db73f62016-12-21 12:58:51 -0800425 return nullptr;
426}
427
428sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
429 return initClient(new Client(this));
430}
431
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700432sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
433 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700434{
435 class DisplayToken : public BBinder {
436 sp<SurfaceFlinger> flinger;
437 virtual ~DisplayToken() {
438 // no more references, this display must be terminated
439 Mutex::Autolock _l(flinger->mStateLock);
440 flinger->mCurrentState.displays.removeItem(this);
441 flinger->setTransactionFlags(eDisplayTransactionNeeded);
442 }
443 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700444 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700445 : flinger(flinger) {
446 }
447 };
448
449 sp<BBinder> token = new DisplayToken(this);
450
451 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700452 // Display ID is assigned when virtual display is allocated by HWC.
453 DisplayDeviceState state;
454 state.isSecure = secure;
455 state.displayName = displayName;
456 mCurrentState.displays.add(token, state);
457 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700458 return token;
459}
460
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700461void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700462 Mutex::Autolock _l(mStateLock);
463
Dominik Laskowski075d3172018-05-24 15:50:06 -0700464 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
465 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700466 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700467 return;
468 }
469
Dominik Laskowski075d3172018-05-24 15:50:06 -0700470 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
471 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700472 ALOGE("destroyDisplay called for non-virtual display");
473 return;
474 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700475 mInterceptor->saveDisplayDeletion(state.sequenceId);
476 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700477 setTransactionFlags(eDisplayTransactionNeeded);
478}
479
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800480std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
481 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700482
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800483 const auto internalDisplayId = getInternalDisplayIdLocked();
484 if (!internalDisplayId) {
485 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700486 }
487
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800488 std::vector<PhysicalDisplayId> displayIds;
489 displayIds.reserve(mPhysicalDisplayTokens.size());
490 displayIds.push_back(internalDisplayId->value);
491
492 for (const auto& [id, token] : mPhysicalDisplayTokens) {
493 if (id != *internalDisplayId) {
494 displayIds.push_back(id.value);
495 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700496 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700497
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800498 return displayIds;
499}
500
501sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
502 Mutex::Autolock lock(mStateLock);
503 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700504}
505
Ady Abraham37965d42018-11-01 13:43:32 -0700506status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
507 if (!outGetColorManagement) {
508 return BAD_VALUE;
509 }
510 *outGetColorManagement = useColorManagement;
511 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700512}
513
Lloyd Pique441d5042018-10-18 16:49:51 -0700514HWComposer& SurfaceFlinger::getHwComposer() const {
515 return mCompositionEngine->getHwComposer();
516}
517
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700518renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
519 return mCompositionEngine->getRenderEngine();
520}
521
Lloyd Pique70d91362018-10-18 16:02:55 -0700522compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
523 return *mCompositionEngine.get();
524}
525
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800526void SurfaceFlinger::bootFinished()
527{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700528 if (mStartPropertySetThread->join() != NO_ERROR) {
529 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800530 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800531 const nsecs_t now = systemTime();
532 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000533 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700534
535 // wait patiently for the window manager death
536 const String16 name("window");
537 sp<IBinder> window(defaultServiceManager()->getService(name));
538 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700539 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700540 }
541
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
Denis Hsu58fbf9f2020-06-17 10:17:30 +0800555 sp<IBinder> input(defaultServiceManager()->getService(String16("inputflinger")));
556
557 postMessageAsync(new LambdaMessage([=]() NO_THREAD_SAFETY_ANALYSIS {
558 if (input == nullptr) {
559 ALOGE("Failed to link to input service");
560 } else {
561 mInputFlinger = interface_cast<IInputFlinger>(input);
562 }
563
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800564 readPersistentProperties();
565 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800566
Ady Abraham97d04232019-03-05 19:48:12 -0800567 // set the refresh rate according to the policy
Alec Mouri0a1cc962019-03-14 12:33:02 -0700568 const auto& performanceRefreshRate =
Dominik Laskowski22488f62019-03-28 09:53:04 -0700569 mRefreshRateConfigs.getRefreshRate(RefreshRateType::PERFORMANCE);
Ady Abraham97d04232019-03-05 19:48:12 -0800570
Dominik Laskowski22488f62019-03-28 09:53:04 -0700571 if (performanceRefreshRate && isDisplayConfigAllowed(performanceRefreshRate->configId)) {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800572 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800573 } else {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800574 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800575 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800576 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800577}
578
Dan Stoza436ccf32018-06-21 12:10:12 -0700579uint32_t SurfaceFlinger::getNewTexture() {
580 {
581 std::lock_guard lock(mTexturePoolMutex);
582 if (!mTexturePool.empty()) {
583 uint32_t name = mTexturePool.back();
584 mTexturePool.pop_back();
585 ATRACE_INT("TexturePoolSize", mTexturePool.size());
586 return name;
587 }
588
589 // The pool was too small, so increase it for the future
590 ++mTexturePoolSize;
591 }
592
593 // The pool was empty, so we need to get a new texture name directly using a
594 // blocking call to the main thread
595 uint32_t name = 0;
596 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
597 return name;
598}
599
Mathias Agopian3f844832013-08-07 21:24:32 -0700600void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700601 std::lock_guard lock(mTexturePoolMutex);
602 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
603 // to actually delete this or not based on mTexturePoolSize
604 mTexturePool.push_back(texture);
605 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700606}
607
Wei Wangf9b05ee2017-07-19 20:59:39 -0700608// Do not call property_set on main thread which will be blocked by init
609// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700610void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700611 ALOGI( "SurfaceFlinger's main thread ready to run. "
612 "Initializing graphics H/W...");
613
Ana Krulec757f63a2019-01-25 10:46:18 -0800614 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900615
Steven Thomasb02664d2017-07-26 18:48:28 -0700616 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700617 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800618 mScheduler =
Ady Abraham09bd3922019-04-08 10:44:56 -0700619 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
620 mRefreshRateConfigs);
Ana Krulecc2870422019-01-29 19:00:58 -0800621 auto resyncCallback =
622 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800623
Ana Krulecc2870422019-01-29 19:00:58 -0800624 mAppConnectionHandle =
625 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
626 resyncCallback,
627 impl::EventThread::InterceptVSyncsCallback());
628 mSfConnectionHandle = mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
629 resyncCallback, [this](nsecs_t timestamp) {
630 mInterceptor->saveVSyncEvent(timestamp);
631 });
632
633 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
634 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
635 mSfConnectionHandle.get());
636
Kevin DuBois413287f2019-02-25 08:46:47 -0800637 mRegionSamplingThread =
638 new RegionSamplingThread(*this, *mScheduler,
639 RegionSamplingThread::EnvironmentTimingTunables());
640
Steven Thomasb02664d2017-07-26 18:48:28 -0700641 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700642 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700643 renderEngineFeature |= (useColorManagement ?
644 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700645 renderEngineFeature |= (useContextPriority ?
646 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin6a043d52019-04-01 17:18:21 -0700647 renderEngineFeature |=
648 (enable_protected_contents(false) ? renderengine::RenderEngine::ENABLE_PROTECTED_CONTEXT
649 : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700650
651 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800652 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700653 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700654 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800655 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700656
657 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
658 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700659 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
660 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800661 // Process any initial hotplug and resulting display changes.
662 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700663 const auto display = getDefaultDisplayDeviceLocked();
664 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700665 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700666 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800667
Steven Thomas050b2c82017-03-06 11:45:16 -0800668 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700669 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700670 // This callback is called from the vr flinger dispatch thread. We
671 // need to call signalTransaction(), which requires holding
672 // mStateLock when we're not on the main thread. Acquiring
673 // mStateLock from the vr flinger dispatch thread might trigger a
674 // deadlock in surface flinger (see b/66916578), so post a message
675 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700676 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700677 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
678 mVrFlingerRequestsDisplay = requestDisplay;
679 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700680 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800681 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700682 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
683 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700684 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700685 .value_or(0),
686 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800687 if (!mVrFlinger) {
688 ALOGE("Failed to start vrflinger");
689 }
690 }
691
Mathias Agopian92a979a2012-08-02 18:32:23 -0700692 // initialize our drawing state
693 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700694
Andy McFadden13a082e2012-08-24 10:16:42 -0700695 // set initial conditions (e.g. unblank default device)
696 initializeDisplays();
697
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700698 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700699
Wei Wangf9b05ee2017-07-19 20:59:39 -0700700 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700701
702 const bool presentFenceReliable =
703 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
704 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700705
706 if (mStartPropertySetThread->Start() != NO_ERROR) {
707 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800708 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800709
Alec Mouri93bc83d2019-04-17 14:47:43 -0700710 mScheduler->setChangeRefreshRateCallback(
711 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
712 Mutex::Autolock lock(mStateLock);
713 setRefreshRateTo(type, event);
714 });
Alec Mouridc28b372019-04-18 21:17:13 -0700715 mScheduler->setGetVsyncPeriodCallback([this] {
716 Mutex::Autolock lock(mStateLock);
717 return getVsyncPeriod();
718 });
Ady Abraham09bd3922019-04-08 10:44:56 -0700719
Dominik Laskowski22488f62019-03-28 09:53:04 -0700720 mRefreshRateConfigs.populate(getHwComposer().getConfigs(*display->getId()));
721 mRefreshRateStats.setConfigMode(getHwComposer().getActiveConfigIndex(*display->getId()));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800722
Dan Stoza9e56aa02015-11-02 13:00:03 -0800723 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700724}
725
Romain Guy11d63f42017-07-20 12:47:14 -0700726void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700727 Mutex::Autolock _l(mStateLock);
728
Romain Guy11d63f42017-07-20 12:47:14 -0700729 char value[PROPERTY_VALUE_MAX];
730
731 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800732 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700733 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800734 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100735
736 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700737 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800738
739 property_get("persist.sys.sf.color_mode", value, "0");
740 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700741}
742
Mathias Agopiana67e4182012-06-19 17:26:12 -0700743void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800744 // Start boot animation service by setting a property mailbox
745 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700746 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800747 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700748 if (mStartPropertySetThread->join() != NO_ERROR) {
749 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800750 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700751}
752
Mathias Agopian875d8e12013-06-07 15:35:48 -0700753size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700754 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700755}
756
Mathias Agopian875d8e12013-06-07 15:35:48 -0700757size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700758 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700759}
760
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800761// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800762
Jamie Gennis582270d2011-08-17 18:19:00 -0700763bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800764 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800765 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800766 return authenticateSurfaceTextureLocked(bufferProducer);
767}
768
769bool SurfaceFlinger::authenticateSurfaceTextureLocked(
770 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800771 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800772 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800773}
774
Brian Anderson6b376712017-04-04 10:51:39 -0700775status_t SurfaceFlinger::getSupportedFrameTimestamps(
776 std::vector<FrameEvent>* outSupported) const {
777 *outSupported = {
778 FrameEvent::REQUESTED_PRESENT,
779 FrameEvent::ACQUIRE,
780 FrameEvent::LATCH,
781 FrameEvent::FIRST_REFRESH_START,
782 FrameEvent::LAST_REFRESH_START,
783 FrameEvent::GPU_COMPOSITION_DONE,
784 FrameEvent::DEQUEUE_READY,
785 FrameEvent::RELEASE,
786 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700787 ConditionalLock _l(mStateLock,
788 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700789 if (!getHwComposer().hasCapability(
790 HWC2::Capability::PresentFenceIsNotReliable)) {
791 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
792 }
793 return NO_ERROR;
794}
795
Dominik Laskowski22488f62019-03-28 09:53:04 -0700796status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
797 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700798 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700799 return BAD_VALUE;
800 }
801
Dominik Laskowski22488f62019-03-28 09:53:04 -0700802 Mutex::Autolock lock(mStateLock);
803
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800804 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700805 if (!displayId) {
806 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700807 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700808
Mathias Agopian8b736f12012-08-13 17:54:26 -0700809 // TODO: Not sure if display density should handled by SF any longer
810 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700811 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700812 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700813 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800814 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700815 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700816 }
817 return density;
818 }
819 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700820 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700821 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700822 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700823 return getDensityFromProperty("ro.sf.lcd_density"); }
824 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700825
Dan Stoza7f7da322014-05-02 15:26:25 -0700826 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700827
Dominik Laskowski075d3172018-05-24 15:50:06 -0700828 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700829 DisplayInfo info = DisplayInfo();
830
Dan Stoza9e56aa02015-11-02 13:00:03 -0800831 float xdpi = hwConfig->getDpiX();
832 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700833
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700834 info.w = hwConfig->getWidth();
835 info.h = hwConfig->getHeight();
836 // Default display viewport to display width and height
837 info.viewportW = info.w;
838 info.viewportH = info.h;
839
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800840 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700841 // The density of the device is provided by a build property
842 float density = Density::getBuildDensity() / 160.0f;
843 if (density == 0) {
844 // the build doesn't provide a density -- this is wrong!
845 // use xdpi instead
846 ALOGE("ro.sf.lcd_density must be defined as a build property");
847 density = xdpi / 160.0f;
848 }
849 if (Density::getEmuDensity()) {
850 // if "qemu.sf.lcd_density" is specified, it overrides everything
851 xdpi = ydpi = density = Density::getEmuDensity();
852 density /= 160.0f;
853 }
854 info.density = density;
855
856 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700857 const auto display = getDefaultDisplayDeviceLocked();
858 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700859
860 // This is for screenrecord
861 const Rect viewport = display->getViewport();
862 if (viewport.isValid()) {
863 info.viewportW = uint32_t(viewport.getWidth());
864 info.viewportH = uint32_t(viewport.getHeight());
865 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700866 } else {
867 // TODO: where should this value come from?
868 static const int TV_DENSITY = 213;
869 info.density = TV_DENSITY / 160.0f;
870 info.orientation = 0;
871 }
872
Dan Stoza7f7da322014-05-02 15:26:25 -0700873 info.xdpi = xdpi;
874 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800875 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ady Abraham796beb02019-04-11 15:23:07 -0700876 const auto refreshRateType = mRefreshRateConfigs.getRefreshRateType(hwConfig->getId());
877 const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
878 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800879
Andy McFadden91b2ca82014-06-13 14:04:23 -0700880 // This is how far in advance a buffer must be queued for
881 // presentation at a given time. If you want a buffer to appear
882 // on the screen at time N, you must submit the buffer before
883 // (N - presentationDeadline).
884 //
885 // Normally it's one full refresh period (to give SF a chance to
886 // latch the buffer), but this can be reduced by configuring a
887 // DispSync offset. Any additional delays introduced by the hardware
888 // composer or panel must be accounted for here.
889 //
890 // We add an additional 1ms to allow for processing time and
891 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700892 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700893
894 // All non-virtual displays are currently considered secure.
895 info.secure = true;
896
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800897 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700898 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800899 std::swap(info.w, info.h);
900 }
901
Michael Wright28f24d02016-07-12 13:30:53 -0700902 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700903 }
904
Dan Stoza7f7da322014-05-02 15:26:25 -0700905 return NO_ERROR;
906}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700907
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700908status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
909 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700910 return BAD_VALUE;
911 }
912
Ana Krulecc2870422019-01-29 19:00:58 -0800913 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700914 return NO_ERROR;
915}
916
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700917int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
918 const auto display = getDisplayDevice(displayToken);
919 if (!display) {
920 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800921 return BAD_VALUE;
922 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700923
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700924 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700925}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700926
Ady Abraham03b02dd2019-03-21 15:40:11 -0700927void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800928 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800929
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800930 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800931 // config twice. However event generation config might have changed so we need to update it
932 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800933 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700934 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
935 mDesiredActiveConfig = info;
936 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800937
938 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800939 // This will trigger HWC refresh without resetting the idle timer.
940 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700941 // Start receiving vsync samples now, so that we can detect a period
942 // switch.
943 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
944 mPhaseOffsets->setRefreshRateType(info.type);
945 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
946 mVsyncModulator.onRefreshRateChangeInitiated();
947 mVsyncModulator.setPhaseOffsets(early, gl, late);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800948 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800949 mDesiredActiveConfigChanged = true;
950 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700951
952 if (mRefreshRateOverlay) {
953 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
954 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800955}
956
957status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
958 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800959
960 std::vector<int32_t> allowedConfig;
961 allowedConfig.push_back(mode);
962
963 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800964}
965
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800966void SurfaceFlinger::setActiveConfigInternal() {
967 ATRACE_CALL();
968
Dominik Laskowski22488f62019-03-28 09:53:04 -0700969 const auto display = getDefaultDisplayDeviceLocked();
970 if (!display) {
971 return;
972 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800973
Dominik Laskowski22488f62019-03-28 09:53:04 -0700974 std::lock_guard<std::mutex> lock(mActiveConfigLock);
975 mRefreshRateStats.setConfigMode(mUpcomingActiveConfig.configId);
976
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800977 display->setActiveConfig(mUpcomingActiveConfig.configId);
978
Ana Krulecc2870422019-01-29 19:00:58 -0800979 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Alec Mouri754c98a2019-03-18 18:53:42 -0700980 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Alec Mouri1c9e82b2019-03-07 12:24:05 -0800981 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
982 mVsyncModulator.setPhaseOffsets(early, gl, late);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800983 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700984
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800985 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -0800986 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
987 mUpcomingActiveConfig.configId);
988 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800989}
990
Dominik Laskowski22488f62019-03-28 09:53:04 -0700991bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -0800992 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800993 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -0700994 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800995 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -0700996 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800997 return true;
998 }
999
1000 // We received the present fence from the HWC, so we assume it successfully updated
1001 // the config, hence we update SF.
1002 mCheckPendingFence = false;
1003 setActiveConfigInternal();
1004 }
1005
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001006 // Store the local variable to release the lock.
1007 ActiveConfigInfo desiredActiveConfig;
1008 {
1009 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001010 if (!mDesiredActiveConfigChanged) {
1011 return false;
1012 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001013 desiredActiveConfig = mDesiredActiveConfig;
1014 }
1015
Dominik Laskowski22488f62019-03-28 09:53:04 -07001016 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001017 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1018 // display is not valid or we are already in the requested mode
1019 // on both cases there is nothing left to do
1020 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham6398a0a2019-04-18 19:30:44 -07001021 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001022 mDesiredActiveConfigChanged = false;
1023 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
1024 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001025 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001026
Ady Abraham838de062019-02-04 10:24:03 -08001027 // Desired active config was set, it is different than the config currently in use, however
1028 // allowed configs might have change by the time we process the refresh.
1029 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001030 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham838de062019-02-04 10:24:03 -08001031 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Alec Mouriecf2e0f2019-03-26 13:26:17 -07001032 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
Ady Abraham838de062019-02-04 10:24:03 -08001033 mDesiredActiveConfig.configId = display->getActiveConfig();
Ady Abraham6398a0a2019-04-18 19:30:44 -07001034 mDesiredActiveConfigChanged = false;
1035 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ady Abraham838de062019-02-04 10:24:03 -08001036 return false;
1037 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001038 mUpcomingActiveConfig = desiredActiveConfig;
1039 const auto displayId = display->getId();
1040 LOG_ALWAYS_FATAL_IF(!displayId);
1041
1042 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1043 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1044
1045 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -08001046 mCheckPendingFence = true;
Ady Abraham8532d012019-05-08 14:50:56 -07001047 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001048 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001049}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001050
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001051status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1052 Vector<ColorMode>* outColorModes) {
1053 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001054 return BAD_VALUE;
1055 }
1056
Peiyong Lina52f0292018-03-14 17:26:31 -07001057 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001058 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001059 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001060 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1061
1062 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1063 if (!displayId) {
1064 return NAME_NOT_FOUND;
1065 }
1066
Dominik Laskowski075d3172018-05-24 15:50:06 -07001067 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001068 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001069 }
Michael Wright28f24d02016-07-12 13:30:53 -07001070 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001071
1072 // If it's built-in display and the configuration claims it's not wide color capable,
1073 // filter out all wide color modes. The typical reason why this happens is that the
1074 // hardware is not good enough to support GPU composition of wide color, and thus the
1075 // OEMs choose to disable this capability.
1076 if (isInternalDisplay && !hasWideColorDisplay) {
1077 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1078 isWideColorMode);
1079 } else {
1080 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1081 }
Michael Wright28f24d02016-07-12 13:30:53 -07001082
1083 return NO_ERROR;
1084}
1085
Daniel Solomon42d04562019-01-20 21:03:19 -08001086status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1087 ui::DisplayPrimaries &primaries) {
1088 if (!displayToken) {
1089 return BAD_VALUE;
1090 }
1091
1092 // Currently we only support this API for a single internal display.
1093 if (getInternalDisplayToken() != displayToken) {
1094 return BAD_VALUE;
1095 }
1096
1097 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1098 return NO_ERROR;
1099}
1100
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001101ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1102 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001103 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001104 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001105 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001106}
1107
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001108status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001109 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001110 Vector<ColorMode> modes;
1111 getDisplayColorModes(displayToken, &modes);
1112 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1113 if (mode < ColorMode::NATIVE || !exists) {
1114 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1115 decodeColorMode(mode).c_str(), mode, displayToken.get());
1116 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001117 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001118 const auto display = getDisplayDevice(displayToken);
1119 if (!display) {
1120 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1121 decodeColorMode(mode).c_str(), mode, displayToken.get());
1122 } else if (display->isVirtual()) {
1123 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1124 decodeColorMode(mode).c_str(), mode);
1125 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001126 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1127 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001128 }
1129 }));
1130
Michael Wright28f24d02016-07-12 13:30:53 -07001131 return NO_ERROR;
1132}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001133
Svetoslavd85084b2014-03-20 10:28:31 -07001134status_t SurfaceFlinger::clearAnimationFrameStats() {
1135 Mutex::Autolock _l(mStateLock);
1136 mAnimFrameTracker.clearStats();
1137 return NO_ERROR;
1138}
1139
1140status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1141 Mutex::Autolock _l(mStateLock);
1142 mAnimFrameTracker.getStats(outStats);
1143 return NO_ERROR;
1144}
1145
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001146status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1147 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001148 Mutex::Autolock _l(mStateLock);
1149
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001150 const auto display = getDisplayDeviceLocked(displayToken);
1151 if (!display) {
1152 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001153 return BAD_VALUE;
1154 }
1155
Peiyong Linfb069302018-04-25 14:34:31 -07001156 // At this point the DisplayDeivce should already be set up,
1157 // meaning the luminance information is already queried from
1158 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001159 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001160 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1161 capabilities.getDesiredMaxLuminance(),
1162 capabilities.getDesiredMaxAverageLuminance(),
1163 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001164
1165 return NO_ERROR;
1166}
1167
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001168status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1169 ui::PixelFormat* outFormat,
1170 ui::Dataspace* outDataspace,
1171 uint8_t* outComponentMask) const {
1172 if (!outFormat || !outDataspace || !outComponentMask) {
1173 return BAD_VALUE;
1174 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001175 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001176 if (!display || !display->getId()) {
1177 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1178 return BAD_VALUE;
1179 }
1180 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1181 outDataspace, outComponentMask);
1182}
1183
Kevin DuBois74e53772018-11-19 10:52:38 -08001184status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1185 bool enable, uint8_t componentMask,
1186 uint64_t maxFrames) const {
1187 const auto display = getDisplayDevice(displayToken);
1188 if (!display || !display->getId()) {
1189 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1190 return BAD_VALUE;
1191 }
1192
1193 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1194 componentMask, maxFrames);
1195}
1196
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001197status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1198 uint64_t maxFrames, uint64_t timestamp,
1199 DisplayedFrameStats* outStats) const {
1200 const auto display = getDisplayDevice(displayToken);
1201 if (!display || !display->getId()) {
1202 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1203 return BAD_VALUE;
1204 }
1205
1206 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1207 outStats);
1208}
1209
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001210status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1211 if (!outSupported) {
1212 return BAD_VALUE;
1213 }
1214 *outSupported = getRenderEngine().supportsProtectedContent();
1215 return NO_ERROR;
1216}
1217
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001218status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1219 bool* outIsWideColorDisplay) const {
1220 if (!displayToken || !outIsWideColorDisplay) {
1221 return BAD_VALUE;
1222 }
1223 Mutex::Autolock _l(mStateLock);
1224 const auto display = getDisplayDeviceLocked(displayToken);
1225 if (!display) {
1226 return BAD_VALUE;
1227 }
Peiyong Linff84a152019-05-17 18:36:19 -07001228
1229 // Use hasWideColorDisplay to override built-in display.
1230 const auto displayId = display->getId();
1231 if (displayId && displayId == getInternalDisplayIdLocked()) {
1232 *outIsWideColorDisplay = hasWideColorDisplay;
1233 return NO_ERROR;
1234 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001235 *outIsWideColorDisplay = display->hasWideColorGamut();
1236 return NO_ERROR;
1237}
1238
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001239status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001240 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001241 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001242
Chia-I Wu90f669f2017-10-05 14:24:41 -07001243 if (mInjectVSyncs == enable) {
1244 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001245 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001246
Ana Krulecc2870422019-01-29 19:00:58 -08001247 auto resyncCallback =
1248 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001249
Ady Abraham46e2f3e2019-03-18 16:40:15 -07001250 // TODO(b/128863962): Part of the Injector should be refactored, so that it
Ana Krulec98b5b242018-08-10 15:03:23 -07001251 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001252 if (enable) {
1253 ALOGV("VSync Injections enabled");
1254 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001255 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001256 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001257 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001258 impl::EventThread::InterceptVSyncsCallback(),
1259 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001260 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001261 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001262 } else {
1263 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001264 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1265 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001266 }
1267
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001268 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001269 }));
1270
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001271 return NO_ERROR;
1272}
1273
1274status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001275 Mutex::Autolock _l(mStateLock);
1276
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001277 if (!mInjectVSyncs) {
1278 ALOGE("VSync Injections not enabled");
1279 return BAD_VALUE;
1280 }
1281 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1282 ALOGV("Injecting VSync inside SurfaceFlinger");
1283 mVSyncInjector->onInjectSyncEvent(when);
1284 }
1285 return NO_ERROR;
1286}
1287
Vishnu Nairb123f472020-06-22 11:52:39 -07001288status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers)
Lloyd Pique755e3192018-01-31 16:46:15 -08001289 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001290 outLayers->clear();
Vishnu Nairb123f472020-06-22 11:52:39 -07001291 postMessageSync(new LambdaMessage([&]() {
1292 mDrawingState.traverseInZOrder([&](Layer* layer) {
1293 outLayers->push_back(layer->getLayerDebugInfo());
1294 });
Kalle Raitaa099a242017-01-11 11:17:29 -08001295
Vishnu Nairb123f472020-06-22 11:52:39 -07001296 }));
Kalle Raitaa099a242017-01-11 11:17:29 -08001297 return NO_ERROR;
1298}
1299
Peiyong Linc6780972018-10-28 15:24:08 -07001300status_t SurfaceFlinger::getCompositionPreference(
1301 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1302 Dataspace* outWideColorGamutDataspace,
1303 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001304 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001305 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001306 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001307 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001308 return NO_ERROR;
1309}
1310
Dan Stozaec460082018-12-17 15:35:09 -08001311status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1312 const sp<IBinder>& stopLayerHandle,
1313 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001314 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001315 return BAD_VALUE;
1316 }
1317 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001318 return NO_ERROR;
1319}
1320
Dan Stozaec460082018-12-17 15:35:09 -08001321status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001322 if (!listener) {
1323 return BAD_VALUE;
1324 }
Dan Stozaec460082018-12-17 15:35:09 -08001325 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001326 return NO_ERROR;
1327}
Dan Gittik57e63c52019-01-18 16:37:54 +00001328
1329status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1330 bool* outSupport) const {
1331 if (!displayToken || !outSupport) {
1332 return BAD_VALUE;
1333 }
1334 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1335 if (!displayId) {
1336 return NAME_NOT_FOUND;
1337 }
1338 *outSupport =
1339 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1340 return NO_ERROR;
1341}
1342
1343status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1344 float brightness) const {
1345 if (!displayToken) {
1346 return BAD_VALUE;
1347 }
1348 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1349 if (!displayId) {
1350 return NAME_NOT_FOUND;
1351 }
1352 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1353}
1354
Ady Abraham8532d012019-05-08 14:50:56 -07001355status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1356 PowerHint powerHint = static_cast<PowerHint>(hintId);
1357
1358 if (powerHint == PowerHint::INTERACTION) {
1359 mScheduler->notifyTouchEvent();
1360 }
1361
1362 return NO_ERROR;
1363}
1364
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001365// ----------------------------------------------------------------------------
1366
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001367sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1368 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulecc2870422019-01-29 19:00:58 -08001369 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001370 Mutex::Autolock lock(mStateLock);
1371 return getVsyncPeriod();
1372 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001373
Ana Krulecc2870422019-01-29 19:00:58 -08001374 const auto& handle =
1375 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001376
Ana Krulecc2870422019-01-29 19:00:58 -08001377 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Mathias Agopianbb641242010-05-18 17:06:55 -07001378}
1379
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001380// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001381
1382void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001383 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001384}
1385
1386void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001387 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001388 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001389}
1390
1391void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001392 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001393 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001394}
1395
1396void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001397 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001398 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001399}
1400
1401status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001402 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001403 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001404}
1405
1406status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001407 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001408 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001409 if (res == NO_ERROR) {
1410 msg->wait();
1411 }
1412 return res;
1413}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001414
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001415void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001416 do {
1417 waitForEvent();
1418 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001419}
1420
Dominik Laskowski83b88212018-12-11 13:34:06 -08001421nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001422 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001423 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1424 return 0;
1425 }
1426
1427 const auto config = getHwComposer().getActiveConfig(*displayId);
1428 return config ? config->getVsyncPeriod() : 0;
1429}
1430
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001431void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1432 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001433 ATRACE_NAME("SF onVsync");
1434
Steven Thomas3cfac282017-02-06 12:29:30 -08001435 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001436 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001437 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001438 return;
1439 }
1440
Dominik Laskowski075d3172018-05-24 15:50:06 -07001441 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001442 return;
1443 }
1444
Dominik Laskowski075d3172018-05-24 15:50:06 -07001445 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001446 // For now, we don't do anything with external display vsyncs.
1447 return;
1448 }
1449
Alec Mouri754c98a2019-03-18 18:53:42 -07001450 bool periodChanged = false;
1451 mScheduler->addResyncSample(timestamp, &periodChanged);
1452 if (periodChanged) {
1453 mVsyncModulator.onRefreshRateChangeDetected();
1454 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001455}
1456
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001457void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001458 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1459 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001460}
1461
Dominik Laskowski22488f62019-03-28 09:53:04 -07001462bool SurfaceFlinger::isDisplayConfigAllowed(int32_t configId) {
1463 return mAllowedDisplayConfigs.empty() || mAllowedDisplayConfigs.count(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001464}
1465
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001466void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001467 const auto display = getDefaultDisplayDeviceLocked();
1468 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001469 return;
1470 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001471 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001472
Ana Krulec7d1d6832018-12-27 11:10:09 -08001473 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowski22488f62019-03-28 09:53:04 -07001474 const auto& refreshRateConfig = mRefreshRateConfigs.getRefreshRate(refreshRate);
Alec Mouri0a1cc962019-03-14 12:33:02 -07001475 if (!refreshRateConfig) {
1476 ALOGV("Skipping refresh rate change request for unsupported rate.");
Ady Abraham1902d072019-03-01 17:18:59 -08001477 return;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001478 }
Ady Abraham1902d072019-03-01 17:18:59 -08001479
Alec Mouri0a1cc962019-03-14 12:33:02 -07001480 const int desiredConfigId = refreshRateConfig->configId;
1481
Dominik Laskowski22488f62019-03-28 09:53:04 -07001482 if (!isDisplayConfigAllowed(desiredConfigId)) {
Ady Abraham1902d072019-03-01 17:18:59 -08001483 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1484 return;
1485 }
1486
Dominik Laskowski22488f62019-03-28 09:53:04 -07001487 setDesiredActiveConfig({refreshRate, desiredConfigId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001488}
1489
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001490void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001491 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001492 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001493 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001494
Lloyd Piqueba04e622017-12-14 17:11:26 -08001495 // Ignore events that do not have the right sequenceId.
1496 if (sequenceId != getBE().mComposerSequenceId) {
1497 return;
1498 }
1499
Steven Thomasb02664d2017-07-26 18:48:28 -07001500 // Only lock if we're not on the main thread. This function is normally
1501 // called on a hwbinder thread, but for the primary display it's called on
1502 // the main thread with the state lock already held, so don't attempt to
1503 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001504 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001505
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001506 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001507
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001508 if (std::this_thread::get_id() == mMainThreadId) {
1509 // Process all pending hot plug events immediately if we are on the main thread.
1510 processDisplayHotplugEventsLocked();
1511 }
1512
Lloyd Piqueba04e622017-12-14 17:11:26 -08001513 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001514}
1515
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001516void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001517 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001518 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001519 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001520 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001521 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001522}
1523
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001524void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001525 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001526 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001527 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001528 getHwComposer().setVsyncEnabled(*displayId,
1529 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1530 }
Mathias Agopian86303202012-07-24 22:46:10 -07001531}
1532
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001533// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001534void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001535 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001536 // Clear the drawing state so that the logic inside of
1537 // handleTransactionLocked will fire. It will determine the delta between
1538 // mCurrentState and mDrawingState and re-apply all changes when we make the
1539 // transition.
1540 mDrawingState.displays.clear();
1541 mDisplays.clear();
1542}
1543
Steven Thomas050b2c82017-03-06 11:45:16 -08001544void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001545 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001546 if (!mVrFlinger)
1547 return;
1548 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001549 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001550 return;
1551 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001552
Lloyd Pique441d5042018-10-18 16:49:51 -07001553 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001554 ALOGE("Vr flinger is only supported for remote hardware composer"
1555 " service connections. Ignoring request to transition to vr"
1556 " flinger.");
1557 mVrFlingerRequestsDisplay = false;
1558 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001559 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001560
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001561 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001562
Steven Thomas0123ac62018-07-12 11:32:34 -07001563 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001564 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001565
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001566 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001567
1568 // Clear out all the output layers from the composition engine for all
1569 // displays before destroying the hardware composer interface. This ensures
1570 // any HWC layers are destroyed through that interface before it becomes
1571 // invalid.
1572 for (const auto& [token, displayDevice] : mDisplays) {
1573 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1574 compositionengine::Output::OutputLayers());
1575 }
1576
Steven Thomas0123ac62018-07-12 11:32:34 -07001577 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1578 // called below. Clear the reference now so we don't accidentally use it
1579 // later.
1580 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001581
Steven Thomasb02664d2017-07-26 18:48:28 -07001582 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001583 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001584 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001585
Steven Thomasb02664d2017-07-26 18:48:28 -07001586 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001587 // Delete the current instance before creating the new one
1588 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1589 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1590 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1591 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001592
Lloyd Pique441d5042018-10-18 16:49:51 -07001593 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001594 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001595
1596 if (vrFlingerRequestsDisplay) {
1597 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001598 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001599
1600 mVisibleRegionsDirty = true;
1601 invalidateHwcGeometry();
1602
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001603 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001604 display = getDefaultDisplayDeviceLocked();
1605 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001606 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001607
Steven Thomasb02664d2017-07-26 18:48:28 -07001608 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001609 const nsecs_t vsyncPeriod = getVsyncPeriod();
1610 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001611
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001612 // The present fences returned from vr_hwc are not an accurate
1613 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001614 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001615
Steven Thomasb02664d2017-07-26 18:48:28 -07001616 // Use phase of 0 since phase is not known.
1617 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001618 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001619 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001620
Ana Krulecc2870422019-01-29 19:00:58 -08001621 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001622
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001623 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001624 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001625}
1626
Ady Abrahambe0f9482019-04-24 15:41:53 -07001627bool SurfaceFlinger::previousFrameMissed() NO_THREAD_SAFETY_ANALYSIS {
1628 // We are storing the last 2 present fences. If sf's phase offset is to be
1629 // woken up before the actual vsync but targeting the next vsync, we need to check
1630 // fence N-2
1631 const sp<Fence>& fence =
1632 mVsyncModulator.getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
1633 ? mPreviousPresentFences[0]
1634 : mPreviousPresentFences[1];
1635
1636 return fence != Fence::NO_FENCE && (fence->getStatus() == Fence::Status::Unsignaled);
1637}
1638
Dominik Laskowski22488f62019-03-28 09:53:04 -07001639void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001640 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001641 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001642 case MessageQueue::INVALIDATE: {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001643 bool frameMissed = previousFrameMissed();
Alec Mouricc0fc602019-02-26 21:45:19 -08001644 bool hwcFrameMissed = mHadDeviceComposition && frameMissed;
1645 bool gpuFrameMissed = mHadClientComposition && frameMissed;
1646 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
1647 ATRACE_INT("HwcFrameMissed", static_cast<int>(hwcFrameMissed));
1648 ATRACE_INT("GpuFrameMissed", static_cast<int>(gpuFrameMissed));
1649 if (frameMissed) {
1650 mFrameMissedCount++;
1651 mTimeStats->incrementMissedFrames();
1652 }
1653
Alec Mouri40189b02019-03-05 15:07:54 -08001654 if (hwcFrameMissed) {
1655 mHwcFrameMissedCount++;
1656 }
1657
1658 if (gpuFrameMissed) {
1659 mGpuFrameMissedCount++;
1660 }
1661
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001662 if (mUseSmart90ForVideo) {
1663 // This call is made each time SF wakes up and creates a new frame. It is part
1664 // of video detection feature.
Ady Abraham09bd3922019-04-08 10:44:56 -07001665 mScheduler->updateFpsBasedOnContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001666 }
1667
Ady Abrahamb838aed2019-02-12 15:30:16 -08001668 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001669 break;
1670 }
1671
Ady Abrahamadb9a992019-09-19 21:21:55 +00001672 if (frameMissed && mPropagateBackpressure) {
1673 if ((hwcFrameMissed && !gpuFrameMissed) ||
1674 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001675 signalLayerUpdate();
1676 break;
1677 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001678 }
Dan Stoza50182882016-07-08 12:02:20 -07001679
Steven Thomas050b2c82017-03-06 11:45:16 -08001680 // Now that we're going to make it to the handleMessageTransaction()
1681 // call below it's safe to call updateVrFlinger(), which will
1682 // potentially trigger a display handoff.
1683 updateVrFlinger();
1684
Dan Stoza6b9454d2014-11-07 16:00:59 -08001685 bool refreshNeeded = handleMessageTransaction();
1686 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001687
1688 updateCursorAsync();
1689 updateInputFlinger();
1690
Dan Stoza58784442014-12-02 16:58:17 -08001691 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001692 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001693 // Signal a refresh if a transaction modified the window state,
1694 // a new buffer was latched, or if HWC has requested a full
1695 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001696 signalRefresh();
1697 }
1698 break;
1699 }
1700 case MessageQueue::REFRESH: {
1701 handleMessageRefresh();
1702 break;
1703 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001704 }
1705}
1706
Dan Stoza6b9454d2014-11-07 16:00:59 -08001707bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001708 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001709 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001710
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001711 bool flushedATransaction = flushTransactionQueues();
1712
1713 bool runHandleTransaction = transactionFlags &&
1714 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1715
1716 if (runHandleTransaction) {
1717 handleTransaction(eTransactionMask);
1718 } else {
1719 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001720 }
1721
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001722 if (transactionFlushNeeded()) {
1723 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001724 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001725
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001726 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001727}
1728
Mathias Agopian4fec8732012-06-29 14:12:52 -07001729void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001730 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001731
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001732 mRefreshPending = false;
1733
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001734 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001735 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001736 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001737 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001738 for (const auto& [token, display] : mDisplays) {
1739 beginFrame(display);
1740 prepareFrame(display);
1741 doDebugFlashRegions(display, repaintEverything);
1742 doComposition(display, repaintEverything);
1743 }
1744
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001745 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001746
1747 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001748 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001749
Dan Stozabfbffeb2016-07-21 14:49:33 -07001750 mHadClientComposition = false;
Alec Mouricc0fc602019-02-26 21:45:19 -08001751 mHadDeviceComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001752 for (const auto& [token, displayDevice] : mDisplays) {
1753 auto display = displayDevice->getCompositionDisplay();
1754 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001755 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001756 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Alec Mouricc0fc602019-02-26 21:45:19 -08001757 mHadDeviceComposition =
1758 mHadDeviceComposition || getHwComposer().hasDeviceComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001759 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001760
Jorim Jaggi90535212018-05-23 23:44:06 +02001761 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001762
David Sodman7e4ae112018-02-09 15:02:28 -08001763 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001764}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001765
David Sodmanfa9b2af2017-12-24 13:28:59 -08001766
1767bool SurfaceFlinger::handleMessageInvalidate() {
1768 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001769 bool refreshNeeded = handlePageFlip();
1770
Vishnu Nair4351ad52019-02-11 14:13:02 -08001771 if (mVisibleRegionsDirty) {
1772 computeLayerBounds();
Nataniel Borges2b796da2019-02-15 13:32:18 -08001773 if (mTracingEnabled) {
1774 mTracing.notify("visibleRegionsDirty");
1775 }
Vishnu Nair4351ad52019-02-11 14:13:02 -08001776 }
1777
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001778 for (auto& layer : mLayersPendingRefresh) {
1779 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001780 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001781 invalidateLayerStack(layer, visibleReg);
1782 }
1783 mLayersPendingRefresh.clear();
1784 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001785}
1786
David Sodman79bba0e2018-08-05 18:07:49 -07001787void SurfaceFlinger::calculateWorkingSet() {
1788 ATRACE_CALL();
1789 ALOGV(__FUNCTION__);
1790
David Sodman79bba0e2018-08-05 18:07:49 -07001791 // build the h/w work list
1792 if (CC_UNLIKELY(mGeometryInvalid)) {
1793 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001794 for (const auto& [token, displayDevice] : mDisplays) {
1795 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001796
Lloyd Piquea83776c2019-01-29 18:42:32 -08001797 uint32_t zOrder = 0;
David Sodman79bba0e2018-08-05 18:07:49 -07001798
Lloyd Piquea83776c2019-01-29 18:42:32 -08001799 for (auto& layer : display->getOutputLayersOrderedByZ()) {
1800 auto& compositionState = layer->editState();
1801 compositionState.forceClientComposition = false;
1802 if (!compositionState.hwc || mDebugDisableHWC || mDebugRegion) {
1803 compositionState.forceClientComposition = true;
David Sodman79bba0e2018-08-05 18:07:49 -07001804 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001805
Lloyd Piquea83776c2019-01-29 18:42:32 -08001806 // The output Z order is set here based on a simple counter.
1807 compositionState.z = zOrder++;
1808
1809 // Update the display independent composition state. This goes
1810 // to the general composition layer state structure.
1811 // TODO: Do this once per compositionengine::CompositionLayer.
1812 layer->getLayerFE().latchCompositionState(layer->getLayer().editState().frontEnd,
1813 true);
1814
1815 // Recalculate the geometry state of the output layer.
1816 layer->updateCompositionState(true);
1817
1818 // Write the updated geometry state to the HWC
1819 layer->writeStateToHWC(true);
David Sodman79bba0e2018-08-05 18:07:49 -07001820 }
1821 }
1822 }
1823
1824 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001825 for (const auto& [token, displayDevice] : mDisplays) {
1826 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001827 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001828 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001829 continue;
1830 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001831 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001832
1833 if (mDrawingState.colorMatrixChanged) {
1834 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001835 }
Peiyong Linc502cb72019-03-01 15:00:23 -08001836 Dataspace targetDataspace = Dataspace::UNKNOWN;
1837 if (useColorManagement) {
1838 ColorMode colorMode;
1839 RenderIntent renderIntent;
1840 pickColorMode(displayDevice, &colorMode, &targetDataspace, &renderIntent);
1841 display->setColorMode(colorMode, targetDataspace, renderIntent);
1842 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001843 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001844 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001845 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001846 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1847 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001848 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001849 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001850 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1851 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001852 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001853 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001854 }
1855
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001856 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001857 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001858 }
1859
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001860 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001861 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001862 layer->setCompositionType(displayDevice,
1863 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001864 continue;
1865 }
1866
Lloyd Pique32cbe282018-10-19 13:09:22 -07001867 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001868 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Peiyong Lin34ea5b92019-03-15 18:40:15 -07001869 displayDevice->getSupportedPerFrameMetadata(),
1870 isHdrColorMode(displayState.colorMode) ? Dataspace::UNKNOWN
1871 : targetDataspace);
David Sodman79bba0e2018-08-05 18:07:49 -07001872 }
1873 }
1874
1875 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001876
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001877 for (const auto& [token, displayDevice] : mDisplays) {
1878 auto display = displayDevice->getCompositionDisplay();
1879 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Lloyd Pique0b785d82018-12-04 17:25:27 -08001880 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1881 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1882 layer->getCompositionType(displayDevice));
David Sodmanba340492018-08-05 21:51:33 -07001883 }
1884 }
David Sodman79bba0e2018-08-05 18:07:49 -07001885}
1886
Lloyd Pique32cbe282018-10-19 13:09:22 -07001887void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1888 bool repaintEverything) {
1889 auto display = displayDevice->getCompositionDisplay();
1890 const auto& displayState = display->getState();
1891
Mathias Agopiancd60f992012-08-16 16:28:27 -07001892 // is debugging enabled
1893 if (CC_LIKELY(!mDebugRegion))
1894 return;
1895
Lloyd Pique32cbe282018-10-19 13:09:22 -07001896 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001897 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001898 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001899 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001900 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001901 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001902 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001903
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001904 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001905 }
1906 }
1907
Lloyd Pique32cbe282018-10-19 13:09:22 -07001908 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001909
1910 if (mDebugRegion > 1) {
1911 usleep(mDebugRegion * 1000);
1912 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001913
Lloyd Pique32cbe282018-10-19 13:09:22 -07001914 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001915}
1916
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001917void SurfaceFlinger::logLayerStats() {
1918 ATRACE_CALL();
1919 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001920 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001921 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001922 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001923 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001924 }
1925 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001926
1927 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001928 }
1929}
1930
David Sodman2b406362017-12-15 13:33:47 -08001931void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001932{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001933 ATRACE_CALL();
1934 ALOGV("preComposition");
1935
David Sodman2b406362017-12-15 13:33:47 -08001936 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1937
Mathias Agopiancd60f992012-08-16 16:28:27 -07001938 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001939 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001940 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001941 needExtraInvalidate = true;
1942 }
Robert Carr2047fae2016-11-28 14:09:09 -08001943 });
1944
Mathias Agopiancd60f992012-08-16 16:28:27 -07001945 if (needExtraInvalidate) {
1946 signalLayerUpdate();
1947 }
1948}
1949
Ana Krulece588e312018-09-18 12:32:24 -07001950void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1951 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001952 // Update queue of past composite+present times and determine the
1953 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001954 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001955 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001956 while (!getBE().mCompositePresentTimes.empty()) {
1957 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001958 // Cached values should have been updated before calling this method,
1959 // which helps avoid duplicate syscalls.
1960 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1961 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1962 break;
1963 }
1964 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001965 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001966 }
1967
1968 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001969 while (getBE().mCompositePresentTimes.size() > 16) {
1970 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001971 }
1972
Ana Krulece588e312018-09-18 12:32:24 -07001973 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001974}
1975
Ana Krulece588e312018-09-18 12:32:24 -07001976void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1977 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001978 // Integer division and modulo round toward 0 not -inf, so we need to
1979 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001980 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1981 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1982 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001983
Ana Krulec757f63a2019-01-25 10:46:18 -08001984 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001985 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001986 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001987 }
1988
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001989 // Snap the latency to a value that removes scheduling jitter from the
1990 // composition and present times, which often have >1ms of jitter.
1991 // Reducing jitter is important if an app attempts to extrapolate
1992 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001993 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001994 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001995 nsecs_t bias = stats.vsyncPeriod / 2;
1996 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1997 nsecs_t snappedCompositeToPresentLatency =
1998 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001999
David Sodman99974d22017-11-28 12:04:33 -08002000 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002001 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2002 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002003 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002004}
2005
David Sodman2b406362017-12-15 13:33:47 -08002006void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002007{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002008 ATRACE_CALL();
2009 ALOGV("postComposition");
2010
Brian Anderson3546a3f2016-07-14 11:51:14 -07002011 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002012 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002013 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002014 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002015 }
2016
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002017 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002018 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002019
David Sodman73beded2017-11-15 11:56:06 -08002020 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002021 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002022 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002023 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002024 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2025 ->getRenderSurface()
2026 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002027 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002028 } else {
2029 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2030 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002031
David Sodman73beded2017-11-15 11:56:06 -08002032 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002033 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2034 mPreviousPresentFences[0] = displayDevice
2035 ? getHwComposer().getPresentFence(*displayDevice->getId())
2036 : Fence::NO_FENCE;
2037 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002038 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002039
Ana Krulece588e312018-09-18 12:32:24 -07002040 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002041 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002042
David Sodman2b406362017-12-15 13:33:47 -08002043 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002044 // when we started doing work for this frame, but that should be okay
2045 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002046 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002047 CompositorTiming compositorTiming;
2048 {
David Sodman99974d22017-11-28 12:04:33 -08002049 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2050 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002051 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002052
Robert Carr2047fae2016-11-28 14:09:09 -08002053 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002054 bool frameLatched =
2055 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2056 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002057 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002058 recordBufferingStats(layer->getName().string(),
2059 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002060 }
Robert Carr2047fae2016-11-28 14:09:09 -08002061 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002062
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002063 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002064 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002065 }
2066
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002067 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002068 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2069 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002070 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002071 }
2072 }
2073
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002074 if (mAnimCompositionPending) {
2075 mAnimCompositionPending = false;
2076
Brian Anderson4e606e32017-03-16 15:34:57 -07002077 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002078 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002079 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002080 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002081 // The HWC doesn't support present fences, so use the refresh
2082 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002083 const nsecs_t presentTime =
2084 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002085 mAnimFrameTracker.setActualPresentTime(presentTime);
2086 }
2087 mAnimFrameTracker.advanceFrame();
2088 }
Dan Stozab90cf072015-03-05 11:05:59 -08002089
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002090 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002091 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002092 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002093 }
2094
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002095 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002096
Lloyd Pique32cbe282018-10-19 13:09:22 -07002097 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2098 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002099 return;
2100 }
2101
2102 nsecs_t currentTime = systemTime();
2103 if (mHasPoweredOff) {
2104 mHasPoweredOff = false;
2105 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002106 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002107 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002108 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2109 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002110 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002111 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002112 }
David Sodman4a36e932017-11-07 14:29:47 -08002113 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002114 }
David Sodman4a36e932017-11-07 14:29:47 -08002115 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002116
2117 {
2118 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002119 if (mTexturePool.size() < mTexturePoolSize) {
2120 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002121 const size_t offset = mTexturePool.size();
2122 mTexturePool.resize(mTexturePoolSize);
2123 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2124 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002125 } else if (mTexturePool.size() > mTexturePoolSize) {
2126 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2127 const size_t offset = mTexturePoolSize;
2128 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2129 mTexturePool.resize(mTexturePoolSize);
2130 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002131 }
2132 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002133
Ady Abrahambe0f9482019-04-24 15:41:53 -07002134 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallf384e052019-06-12 13:25:07 -07002135
2136 // Lock the mStateLock in case SurfaceFlinger is in the middle of applying a transaction.
2137 // If we do not lock here, a callback could be sent without all of its SurfaceControls and
2138 // metrics.
2139 {
2140 Mutex::Autolock _l(mStateLock);
2141 mTransactionCompletedThread.sendCallbacks();
2142 }
Ady Abraham8164d482019-01-11 14:47:59 -08002143
Kevin DuBois413287f2019-02-25 08:46:47 -08002144 if (mLumaSampling && mRegionSamplingThread) {
2145 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002146 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002147
2148 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2149 // side-effect of getTotalSize(), so we check that again here
2150 if (ATRACE_ENABLED()) {
2151 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2152 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002153}
2154
Vishnu Nair4351ad52019-02-11 14:13:02 -08002155void SurfaceFlinger::computeLayerBounds() {
2156 for (const auto& pair : mDisplays) {
2157 const auto& displayDevice = pair.second;
2158 const auto display = displayDevice->getCompositionDisplay();
2159 for (const auto& layer : mDrawingState.layersSortedByZ) {
2160 // only consider the layers on the given layer stack
2161 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002162 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002163 }
2164
2165 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2166 }
2167 }
2168}
2169
Mathias Agopiancd60f992012-08-16 16:28:27 -07002170void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002171 ATRACE_CALL();
2172 ALOGV("rebuildLayerStacks");
2173
Mathias Agopiancd60f992012-08-16 16:28:27 -07002174 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002175 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002176 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002177 mVisibleRegionsDirty = false;
2178 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002179
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002180 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002181 const auto& displayDevice = pair.second;
2182 auto display = displayDevice->getCompositionDisplay();
2183 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002184 Region opaqueRegion;
2185 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002186 compositionengine::Output::OutputLayers layersSortedByZ;
2187 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002188 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002189 const ui::Transform& tr = displayState.transform;
2190 const Rect bounds = displayState.bounds;
2191 if (displayState.isEnabled) {
2192 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002193
Jeff Sharkey76488112017-02-27 14:15:18 -07002194 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002195 auto compositionLayer = layer->getCompositionLayer();
2196 if (compositionLayer == nullptr) {
2197 return;
2198 }
2199
Lloyd Pique32cbe282018-10-19 13:09:22 -07002200 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002201 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2202 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2203
Lloyd Pique07e33212018-12-18 16:33:37 -08002204 bool needsOutputLayer = false;
2205
Lloyd Piqueef36b002019-01-23 17:52:04 -08002206 if (display->belongsInOutput(layer->getLayerStack(),
2207 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002208 Region drawRegion(tr.transform(
2209 layer->visibleNonTransparentRegion));
2210 drawRegion.andSelf(bounds);
2211 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002212 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002213 }
Chia-I Wu83806892017-11-16 10:50:20 -08002214 }
2215
Lloyd Pique07e33212018-12-18 16:33:37 -08002216 if (needsOutputLayer) {
2217 layersSortedByZ.emplace_back(
2218 display->getOrCreateOutputLayer(displayId, compositionLayer,
2219 layerFE));
2220 deprecated_layersSortedByZ.add(layer);
2221
2222 auto& outputLayerState = layersSortedByZ.back()->editState();
2223 outputLayerState.visibleRegion =
2224 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2225 } else if (displayId) {
2226 // For layers that are being removed from a HWC display,
2227 // and that have queued frames, add them to a a list of
2228 // released layers so we can properly set a fence.
2229 bool hasExistingOutputLayer =
2230 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2231 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2232 mLayersWithQueuedFrames.cend(),
2233 layer) != mLayersWithQueuedFrames.cend();
2234
2235 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002236 layersNeedingFences.add(layer);
2237 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002238 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002239 });
2240 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002241
2242 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2243
2244 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002245 displayDevice->setLayersNeedingFences(layersNeedingFences);
2246
2247 Region undefinedRegion{bounds};
2248 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2249
2250 display->editState().undefinedRegion = undefinedRegion;
2251 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002252 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002253 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002254}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002255
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002256// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002257// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002258// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002259// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002260// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002261// The returned HDR data space is one of
2262// - Dataspace::UNKNOWN
2263// - Dataspace::BT2020_HLG
2264// - Dataspace::BT2020_PQ
Peiyong Lin03912882019-04-16 15:34:46 -07002265Dataspace SurfaceFlinger::getBestDataspace(const sp<DisplayDevice>& display,
2266 Dataspace* outHdrDataSpace,
2267 bool* outIsHdrClientComposition) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002268 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002269 *outHdrDataSpace = Dataspace::UNKNOWN;
2270
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002271 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002272 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002273 case Dataspace::V0_SCRGB:
2274 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002275 case Dataspace::BT2020:
2276 case Dataspace::BT2020_ITU:
2277 case Dataspace::BT2020_LINEAR:
2278 case Dataspace::DISPLAY_BT2020:
2279 bestDataSpace = Dataspace::DISPLAY_BT2020;
2280 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002281 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002282 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002283 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002284 case Dataspace::BT2020_PQ:
2285 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002286 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002287 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lin03912882019-04-16 15:34:46 -07002288 *outIsHdrClientComposition = layer->getForceClientComposition(display);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002289 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002290 case Dataspace::BT2020_HLG:
2291 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002292 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002293 // When there's mixed PQ content and HLG content, we set the HDR
2294 // data space to be BT2020_PQ and convert HLG to PQ.
2295 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2296 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002297 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002298 break;
2299 default:
2300 break;
2301 }
Romain Guy54f154a2017-10-24 21:40:32 +01002302 }
2303
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002304 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002305}
2306
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002307// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002308void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2309 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002310 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2311 *outMode = ColorMode::NATIVE;
2312 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002313 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002314 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002315 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002316
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002317 Dataspace hdrDataSpace;
Peiyong Lin03912882019-04-16 15:34:46 -07002318 bool isHdrClientComposition = false;
2319 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace, &isHdrClientComposition);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002320
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002321 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2322
Peiyong Lina3ea5592019-02-10 14:45:00 -08002323 switch (mForceColorMode) {
2324 case ColorMode::SRGB:
2325 bestDataSpace = Dataspace::V0_SRGB;
2326 break;
2327 case ColorMode::DISPLAY_P3:
2328 bestDataSpace = Dataspace::DISPLAY_P3;
2329 break;
2330 default:
2331 break;
2332 }
2333
Peiyong Lindfde5112018-06-05 10:58:41 -07002334 // respect hdrDataSpace only when there is no legacy HDR support
Peiyong Lin03912882019-04-16 15:34:46 -07002335 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
2336 !profile->hasLegacyHdrSupport(hdrDataSpace) && !isHdrClientComposition;
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002337 if (isHdr) {
2338 bestDataSpace = hdrDataSpace;
2339 }
2340
Chia-I Wu0d711262018-05-21 15:19:35 -07002341 RenderIntent intent;
2342 switch (mDisplayColorSetting) {
2343 case DisplayColorSetting::MANAGED:
2344 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002345 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002346 break;
2347 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002348 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002349 break;
2350 default: // vendor display color setting
2351 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2352 break;
2353 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002354
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002355 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002356}
2357
Lloyd Pique32cbe282018-10-19 13:09:22 -07002358void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2359 auto display = displayDevice->getCompositionDisplay();
2360 const auto& displayState = display->getState();
2361
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002362 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002363 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2364 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002365
David Sodmanfa9b2af2017-12-24 13:28:59 -08002366 // If nothing has changed (!dirty), don't recompose.
2367 // If something changed, but we don't currently have any visible layers,
2368 // and didn't when we last did a composition, then skip it this time.
2369 // The second rule does two things:
2370 // - When all layers are removed from a display, we'll emit one black
2371 // frame, then nothing more until we get new layers.
2372 // - When a display is created with a private layer stack, we won't
2373 // emit any black frames until a layer is added to the layer stack.
2374 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002375
Dominik Laskowski075d3172018-05-24 15:50:06 -07002376 const char flagPrefix[] = {'-', '+'};
2377 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002378 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2379 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2380 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2381 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002382
Lloyd Pique31cb2942018-10-19 17:23:03 -07002383 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002384
David Sodmanfa9b2af2017-12-24 13:28:59 -08002385 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002386 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002387 }
2388}
2389
Lloyd Pique32cbe282018-10-19 13:09:22 -07002390void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2391 auto display = displayDevice->getCompositionDisplay();
2392 const auto& displayState = display->getState();
2393
2394 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002395 return;
David Sodman2b406362017-12-15 13:33:47 -08002396 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002397
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002398 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002399 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002400 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002401}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002402
Lloyd Pique32cbe282018-10-19 13:09:22 -07002403void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002404 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002405 ALOGV("doComposition");
2406
Lloyd Pique32cbe282018-10-19 13:09:22 -07002407 auto display = displayDevice->getCompositionDisplay();
2408 const auto& displayState = display->getState();
2409
2410 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002411 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002412 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002413
David Sodmanfa9b2af2017-12-24 13:28:59 -08002414 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002415 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002416
Lloyd Pique32cbe282018-10-19 13:09:22 -07002417 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002418 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002419 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002420 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002421}
2422
David Sodmanfa9b2af2017-12-24 13:28:59 -08002423void SurfaceFlinger::postFrame()
2424{
2425 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002426 const auto display = getDefaultDisplayDeviceLocked();
2427 if (display && getHwComposer().isConnected(*display->getId())) {
2428 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002429 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2430 logFrameStats();
2431 }
2432 }
2433}
2434
Lloyd Pique32cbe282018-10-19 13:09:22 -07002435void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002436 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002437 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002438
Lloyd Pique32cbe282018-10-19 13:09:22 -07002439 auto display = displayDevice->getCompositionDisplay();
2440 const auto& displayState = display->getState();
2441 const auto displayId = display->getId();
2442
Lloyd Pique32cbe282018-10-19 13:09:22 -07002443 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002444 if (displayId) {
2445 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002446 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002447 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002448 for (auto& layer : display->getOutputLayersOrderedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002449 sp<Fence> releaseFence = Fence::NO_FENCE;
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002450 bool usedClientComposition = true;
David Sodman15094112018-10-11 09:39:37 -07002451
Chia-I Wu7b549592017-11-15 09:14:57 -08002452 // The layer buffer from the previous frame (if any) is released
2453 // by HWC only when the release fence from this frame (if any) is
2454 // signaled. Always get the release fence from HWC first.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002455 if (layer->getState().hwc) {
2456 const auto& hwcState = *layer->getState().hwc;
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002457 releaseFence =
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002458 getHwComposer().getLayerReleaseFence(*displayId, hwcState.hwcLayer.get());
2459 usedClientComposition =
2460 hwcState.hwcCompositionType == Hwc2::IComposerClient::Composition::CLIENT;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002461 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002462
2463 // If the layer was client composited in the previous frame, we
2464 // need to merge with the previous client target acquire fence.
2465 // Since we do not track that, always merge with the current
2466 // client target acquire fence when it is available, even though
2467 // this is suboptimal.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002468 if (usedClientComposition) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002469 releaseFence =
2470 Fence::merge("LayerRelease", releaseFence,
2471 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002472 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002473
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002474 layer->getLayerFE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002475 }
Chia-I Wu83806892017-11-16 10:50:20 -08002476
2477 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002478 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002479 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002480 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002481 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002482 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002483 for (auto& layer : displayDevice->getLayersNeedingFences()) {
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002484 layer->getCompositionLayer()->getLayerFE()->onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002485 }
2486 }
2487
Dominik Laskowski075d3172018-05-24 15:50:06 -07002488 if (displayId) {
2489 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002490 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002491 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002492}
2493
Mathias Agopian87baae12012-07-31 12:38:26 -07002494void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002495{
Mathias Agopian841cde52012-03-01 15:44:37 -08002496 ATRACE_CALL();
2497
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002498 // here we keep a copy of the drawing state (that is the state that's
2499 // going to be overwritten by handleTransactionLocked()) outside of
2500 // mStateLock so that the side-effects of the State assignment
2501 // don't happen with mStateLock held (which can cause deadlocks).
2502 State drawingState(mDrawingState);
2503
Mathias Agopianca4d3602011-05-19 15:38:14 -07002504 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002505 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002506
Mathias Agopianca4d3602011-05-19 15:38:14 -07002507 // Here we're guaranteed that some transaction flags are set
2508 // so we can call handleTransactionLocked() unconditionally.
2509 // We call getTransactionFlags(), which will also clear the flags,
2510 // with mStateLock held to guarantee that mCurrentState won't change
2511 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002512
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002513 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002514 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002515 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002516
Mathias Agopianca4d3602011-05-19 15:38:14 -07002517 mDebugInTransaction = 0;
2518 invalidateHwcGeometry();
2519 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002520}
2521
Lloyd Piqueba04e622017-12-14 17:11:26 -08002522void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2523 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002524 const std::optional<DisplayIdentificationInfo> info =
2525 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002526
Dominik Laskowski075d3172018-05-24 15:50:06 -07002527 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002528 continue;
2529 }
2530
Lloyd Piqueba04e622017-12-14 17:11:26 -08002531 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002532 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002533 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002534 mPhysicalDisplayTokens[info->id] = new BBinder();
2535 DisplayDeviceState state;
2536 state.displayId = info->id;
2537 state.isSecure = true; // All physical displays are currently considered secure.
2538 state.displayName = info->name;
2539 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2540 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002541 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002542 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002543 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002544
Dominik Laskowski075d3172018-05-24 15:50:06 -07002545 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2546 if (index >= 0) {
2547 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2548 mInterceptor->saveDisplayDeletion(state.sequenceId);
2549 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002550 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002551 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002552 }
2553
2554 processDisplayChangesLocked();
2555 }
2556
2557 mPendingHotplugEvents.clear();
2558}
2559
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002560void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002561 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2562 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002563}
2564
Lloyd Pique99d3da52018-01-22 17:48:03 -08002565sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002566 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002567 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002568 const sp<IGraphicBufferProducer>& producer) {
2569 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002570 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002571 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002572 creationArgs.isSecure = state.isSecure;
2573 creationArgs.displaySurface = dispSurface;
2574 creationArgs.hasWideColorGamut = false;
2575 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002576
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002577 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002578 creationArgs.isPrimary = isInternalDisplay;
2579
2580 if (useColorManagement && displayId) {
2581 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002582 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002583 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002584 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002585 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002586
Dominik Laskowski7e045462018-05-30 13:02:02 -07002587 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002588 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002589 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002590 }
tangrobin6753a022018-08-10 10:58:54 +08002591 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002592
Dominik Laskowski075d3172018-05-24 15:50:06 -07002593 if (displayId) {
2594 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002595 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002596 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002597 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002598
Lloyd Pique90c115d2018-09-18 21:39:42 -07002599 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002600 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002601 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002602
Lloyd Pique99d3da52018-01-22 17:48:03 -08002603 // Make sure that composition can never be stalled by a virtual display
2604 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002605 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002606 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002607 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2608 }
2609
Dominik Laskowski075d3172018-05-24 15:50:06 -07002610 creationArgs.displayInstallOrientation =
2611 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002612
Lloyd Pique99d3da52018-01-22 17:48:03 -08002613 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002614 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002615
Lloyd Pique90c115d2018-09-18 21:39:42 -07002616 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002617
2618 if (maxFrameBufferAcquiredBuffers >= 3) {
2619 nativeWindowSurface->preallocateBuffers();
2620 }
2621
2622 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002623 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002624 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002625 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002626 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002627 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002628 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2629 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002630 if (!state.isVirtual()) {
2631 LOG_ALWAYS_FATAL_IF(!displayId);
2632 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002633 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002634
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002635 display->setLayerStack(state.layerStack);
2636 display->setProjection(state.orientation, state.viewport, state.frame);
2637 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002638
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002639 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002640}
2641
Lloyd Pique347200f2017-12-14 17:00:15 -08002642void SurfaceFlinger::processDisplayChangesLocked() {
2643 // here we take advantage of Vector's copy-on-write semantics to
2644 // improve performance by skipping the transaction entirely when
2645 // know that the lists are identical
2646 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2647 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2648 if (!curr.isIdenticalTo(draw)) {
2649 mVisibleRegionsDirty = true;
2650 const size_t cc = curr.size();
2651 size_t dc = draw.size();
2652
2653 // find the displays that were removed
2654 // (ie: in drawing state but not in current state)
2655 // also handle displays that changed
2656 // (ie: displays that are in both lists)
2657 for (size_t i = 0; i < dc;) {
2658 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2659 if (j < 0) {
2660 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002661 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002662 // Save display ID before disconnecting.
2663 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002664 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002665
2666 if (!display->isVirtual()) {
2667 LOG_ALWAYS_FATAL_IF(!displayId);
2668 dispatchDisplayHotplugEvent(displayId->value, false);
2669 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002670 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002671
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002672 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002673 } else {
2674 // this display is in both lists. see if something changed.
2675 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002676 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002677 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2678 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2679 if (state_binder != draw_binder) {
2680 // changing the surface is like destroying and
2681 // recreating the DisplayDevice, so we just remove it
2682 // from the drawing state, so that it get re-added
2683 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002684 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002685 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002686 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002687 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002688 mDrawingState.displays.removeItemsAt(i);
2689 dc--;
2690 // at this point we must loop to the next item
2691 continue;
2692 }
2693
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002694 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002695 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002696 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002697 }
2698 if ((state.orientation != draw[i].orientation) ||
2699 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002700 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002701 }
2702 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002703 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002704 }
2705 }
2706 }
2707 ++i;
2708 }
2709
2710 // find displays that were added
2711 // (ie: in current state but not in drawing state)
2712 for (size_t i = 0; i < cc; i++) {
2713 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2714 const DisplayDeviceState& state(curr[i]);
2715
Lloyd Pique542307f2018-10-19 13:24:08 -07002716 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002717 sp<IGraphicBufferProducer> producer;
2718 sp<IGraphicBufferProducer> bqProducer;
2719 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002720 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002721
Dominik Laskowski075d3172018-05-24 15:50:06 -07002722 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002723 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002724 // Virtual displays without a surface are dormant:
2725 // they have external state (layer stack, projection,
2726 // etc.) but no internal state (i.e. a DisplayDevice).
2727 if (state.surface != nullptr) {
2728 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002729 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002730 int width = 0;
2731 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2732 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2733 int height = 0;
2734 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2735 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2736 int intFormat = 0;
2737 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2738 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002739 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002740
Dominik Laskowski075d3172018-05-24 15:50:06 -07002741 displayId =
2742 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002743 }
2744
2745 // TODO: Plumb requested format back up to consumer
2746
2747 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002748 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002749 bqProducer, bqConsumer,
2750 state.displayName);
2751
2752 dispSurface = vds;
2753 producer = vds;
2754 }
2755 } else {
2756 ALOGE_IF(state.surface != nullptr,
2757 "adding a supported display, but rendering "
2758 "surface is provided (%p), ignoring it",
2759 state.surface.get());
2760
Dominik Laskowski075d3172018-05-24 15:50:06 -07002761 displayId = state.displayId;
2762 LOG_ALWAYS_FATAL_IF(!displayId);
2763 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002764 producer = bqProducer;
2765 }
2766
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002767 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002768 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002769 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002770 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002771 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002772 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002773 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002774 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002775 }
2776 }
2777 }
2778 }
2779 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002780
2781 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002782}
2783
Mathias Agopian87baae12012-07-31 12:38:26 -07002784void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002785{
Dan Stoza7dde5992015-05-22 09:51:44 -07002786 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002787 mCurrentState.traverseInZOrder([](Layer* layer) {
2788 layer->notifyAvailableFrames();
2789 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002790
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002791 /*
2792 * Traversal of the children
2793 * (perform the transaction for each of them if needed)
2794 */
2795
Marissa Wall06255332019-03-27 13:48:27 -07002796 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002797 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002798 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002799 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002800
2801 const uint32_t flags = layer->doTransaction(0);
2802 if (flags & Layer::eVisibleRegion)
2803 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002804
2805 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002806 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002807 }
Robert Carr2047fae2016-11-28 14:09:09 -08002808 });
Marissa Wall06255332019-03-27 13:48:27 -07002809 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002810 }
2811
2812 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002813 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002814 */
2815
Mathias Agopiane57f2922012-08-09 16:29:12 -07002816 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002817 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002818 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002819 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002820
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002821 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002822 // The transform hint might have changed for some layers
2823 // (either because a display has changed, or because a layer
2824 // as changed).
2825 //
2826 // Walk through all the layers in currentLayers,
2827 // and update their transform hint.
2828 //
2829 // If a layer is visible only on a single display, then that
2830 // display is used to calculate the hint, otherwise we use the
2831 // default display.
2832 //
2833 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2834 // the hint is set before we acquire a buffer from the surface texture.
2835 //
2836 // NOTE: layer transactions have taken place already, so we use their
2837 // drawing state. However, SurfaceFlinger's own transaction has not
2838 // happened yet, so we must use the current state layer list
2839 // (soon to become the drawing state list).
2840 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002841 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002842 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002843 bool first = true;
2844 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002845 // NOTE: we rely on the fact that layers are sorted by
2846 // layerStack first (so we don't have to traverse the list
2847 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002848 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002849 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002850 currentlayerStack = layerStack;
2851 // figure out if this layerstack is mirrored
2852 // (more than one display) if so, pick the default display,
2853 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002854 hintDisplay = nullptr;
2855 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002856 if (display->getCompositionDisplay()
2857 ->belongsInOutput(layer->getLayerStack(),
2858 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002859 if (hintDisplay) {
2860 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002861 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002862 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002863 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002864 }
2865 }
2866 }
2867 }
Chet Haase91d25932013-04-11 15:24:55 -07002868
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002869 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002870 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2871 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002872
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002873 // could be null when this layer is using a layerStack
2874 // that is not visible on any display. Also can occur at
2875 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002876 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002877 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002878
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002879 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002880 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002881 if (hintDisplay) {
2882 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002883 }
Robert Carr2047fae2016-11-28 14:09:09 -08002884
2885 first = false;
2886 });
Mathias Agopian84300952012-11-21 16:02:13 -08002887 }
2888
2889
Mathias Agopian3559b072012-08-15 13:46:03 -07002890 /*
2891 * Perform our own transaction if needed
2892 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002893
2894 if (mLayersAdded) {
2895 mLayersAdded = false;
2896 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002897 mVisibleRegionsDirty = true;
2898 }
2899
2900 // some layers might have been removed, so
2901 // we need to update the regions they're exposing.
2902 if (mLayersRemoved) {
2903 mLayersRemoved = false;
2904 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002905 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002906 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002907 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002908 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002909 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002910 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002911 }
Robert Carr2047fae2016-11-28 14:09:09 -08002912 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002913 }
2914
Vishnu Nairec0ab382019-02-13 15:32:56 -08002915 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002916 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002917}
2918
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002919void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002920 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002921 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002922 return;
2923 }
2924
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002925 if (mVisibleRegionsDirty || mInputInfoChanged) {
2926 mInputInfoChanged = false;
2927 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002928 } else if (mInputWindowCommands.syncInputWindows) {
2929 // If the caller requested to sync input windows, but there are no
2930 // changes to input windows, notify immediately.
2931 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002932 }
2933
2934 executeInputWindowCommands();
2935}
2936
2937void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002938 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002939
2940 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2941 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002942 // When calculating the screen bounds we ignore the transparent region since it may
2943 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002944 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002945 }
2946 });
chaviw291d88a2019-02-14 10:33:58 -08002947
2948 mInputFlinger->setInputWindows(inputHandles,
2949 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2950 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002951}
2952
Vishnu Nairec0ab382019-02-13 15:32:56 -08002953void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002954 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002955 mPendingInputWindowCommands.clear();
2956}
2957
chaviwfbe5d9c2018-12-26 12:23:37 -08002958void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08002959 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2960 if (transferTouchFocusCommand.fromToken != nullptr &&
2961 transferTouchFocusCommand.toToken != nullptr &&
2962 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2963 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2964 transferTouchFocusCommand.toToken);
2965 }
2966 }
2967
2968 mInputWindowCommands.clear();
2969}
2970
Riley Andrews03414a12014-07-01 14:22:59 -07002971void SurfaceFlinger::updateCursorAsync()
2972{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002973 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002974 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002975 continue;
2976 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002977
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002978 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2979 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002980 }
2981 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002982}
2983
chaviw61626f22018-11-15 16:26:27 -08002984void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2985 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08002986 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08002987 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08002988 }
2989 layer->releasePendingBuffer(systemTime());
2990}
2991
Mathias Agopian4fec8732012-06-29 14:12:52 -07002992void SurfaceFlinger::commitTransaction()
2993{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002994 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002995 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002996 for (const auto& l : mLayersPendingRemoval) {
2997 recordBufferingStats(l->getName().string(),
2998 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002999
Lloyd Pique07e33212018-12-18 16:33:37 -08003000 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07003001 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003002 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003003 }
chaviw74d90ad2019-04-26 14:45:26 -07003004
3005 // If the layer has been removed and has no parent, then it will not be reachable
3006 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3007 // ensure we can copy its current to drawing state.
3008 if (!l->getParent()) {
3009 mOffscreenLayers.emplace(l.get());
3010 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003011 }
3012 mLayersPendingRemoval.clear();
3013 }
3014
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003015 // If this transaction is part of a window animation then the next frame
3016 // we composite should be considered an animation as well.
3017 mAnimCompositionPending = mAnimTransactionPending;
3018
Nataniel Borges2b796da2019-02-15 13:32:18 -08003019 withTracingLock([&]() {
3020 mDrawingState = mCurrentState;
3021 // clear the "changed" flags in current state
3022 mCurrentState.colorMatrixChanged = false;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003023
chaviw74d90ad2019-04-26 14:45:26 -07003024 mDrawingState.traverseInZOrder([&](Layer* layer) {
3025 layer->commitChildList();
3026
3027 // If the layer can be reached when traversing mDrawingState, then the layer is no
3028 // longer offscreen. Remove the layer from the offscreenLayer set.
3029 if (mOffscreenLayers.count(layer)) {
3030 mOffscreenLayers.erase(layer);
3031 }
3032 });
3033
3034 commitOffscreenLayers();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003035 });
Nataniel Borges2b796da2019-02-15 13:32:18 -08003036
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003037 mTransactionPending = false;
3038 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003039 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003040}
3041
Nataniel Borges2b796da2019-02-15 13:32:18 -08003042void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
3043 if (mTracingEnabledChanged) {
3044 mTracingEnabled = mTracing.isEnabled();
3045 mTracingEnabledChanged = false;
3046 }
3047
3048 // Synchronize with Tracing thread
3049 std::unique_lock<std::mutex> lock;
3050 if (mTracingEnabled) {
3051 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
3052 }
3053
3054 lockedOperation();
3055
3056 // Synchronize with Tracing thread
3057 if (mTracingEnabled) {
3058 lock.unlock();
3059 }
3060}
3061
chaviw74d90ad2019-04-26 14:45:26 -07003062void SurfaceFlinger::commitOffscreenLayers() {
3063 for (Layer* offscreenLayer : mOffscreenLayers) {
3064 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
3065 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3066 if (!trFlags) return;
3067
3068 layer->doTransaction(0);
3069 layer->commitChildList();
3070 });
3071 }
3072}
3073
Lloyd Pique32cbe282018-10-19 13:09:22 -07003074void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003075 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003076 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003077 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003078
Lloyd Pique32cbe282018-10-19 13:09:22 -07003079 auto display = displayDevice->getCompositionDisplay();
3080
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003081 Region aboveOpaqueLayers;
3082 Region aboveCoveredLayers;
3083 Region dirty;
3084
Mathias Agopian87baae12012-07-31 12:38:26 -07003085 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003086
Robert Carr2047fae2016-11-28 14:09:09 -08003087 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003088 // start with the whole surface at its current location
3089 const Layer::State& s(layer->getDrawingState());
3090
Jesse Hall01e29052013-02-19 16:13:35 -08003091 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003092 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003093 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003094 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003095
Mathias Agopianab028732010-03-16 16:41:46 -07003096 /*
3097 * opaqueRegion: area of a surface that is fully opaque.
3098 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003099 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003100
3101 /*
3102 * visibleRegion: area of a surface that is visible on screen
3103 * and not fully transparent. This is essentially the layer's
3104 * footprint minus the opaque regions above it.
3105 * Areas covered by a translucent surface are considered visible.
3106 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003107 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003108
3109 /*
3110 * coveredRegion: area of a surface that is covered by all
3111 * visible regions above it (which includes the translucent areas).
3112 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003113 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003114
Jesse Halla8026d22012-09-25 13:25:04 -07003115 /*
3116 * transparentRegion: area of a surface that is hinted to be completely
3117 * transparent. This is only used to tell when the layer has no visible
3118 * non-transparent regions and can be removed from the layer list. It
3119 * does not affect the visibleRegion of this layer or any layers
3120 * beneath it. The hint may not be correct if apps don't respect the
3121 * SurfaceView restrictions (which, sadly, some don't).
3122 */
3123 Region transparentRegion;
3124
Mathias Agopianab028732010-03-16 16:41:46 -07003125
3126 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003127 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003128 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003129 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003130
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003131 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003132 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003133 if (!visibleRegion.isEmpty()) {
3134 // Remove the transparent area from the visible region
3135 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003136 if (tr.preserveRects()) {
3137 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003138 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003139 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003140 // transformation too complex, can't do the
3141 // transparent region optimization.
3142 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003143 }
Mathias Agopianab028732010-03-16 16:41:46 -07003144 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003145
Mathias Agopianab028732010-03-16 16:41:46 -07003146 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003147 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003148 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003149 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003150 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003151 // the opaque region is the layer's footprint
3152 opaqueRegion = visibleRegion;
3153 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003154 }
3155 }
3156
Robert Carre5f4f692018-01-12 13:12:28 -08003157 if (visibleRegion.isEmpty()) {
3158 layer->clearVisibilityRegions();
3159 return;
3160 }
3161
Mathias Agopianab028732010-03-16 16:41:46 -07003162 // Clip the covered region to the visible region
3163 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3164
3165 // Update aboveCoveredLayers for next (lower) layer
3166 aboveCoveredLayers.orSelf(visibleRegion);
3167
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003168 // subtract the opaque region covered by the layers above us
3169 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003170
3171 // compute this layer's dirty region
3172 if (layer->contentDirty) {
3173 // we need to invalidate the whole region
3174 dirty = visibleRegion;
3175 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003176 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003177 layer->contentDirty = false;
3178 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003179 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003180 * the exposed region consists of two components:
3181 * 1) what's VISIBLE now and was COVERED before
3182 * 2) what's EXPOSED now less what was EXPOSED before
3183 *
3184 * note that (1) is conservative, we start with the whole
3185 * visible region but only keep what used to be covered by
3186 * something -- which mean it may have been exposed.
3187 *
3188 * (2) handles areas that were not covered by anything but got
3189 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003190 */
Mathias Agopianab028732010-03-16 16:41:46 -07003191 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003192 const Region oldVisibleRegion = layer->visibleRegion;
3193 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003194 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3195 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003196 }
3197 dirty.subtractSelf(aboveOpaqueLayers);
3198
3199 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003200 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003201
Mathias Agopianab028732010-03-16 16:41:46 -07003202 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003203 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003204
Jesse Halla8026d22012-09-25 13:25:04 -07003205 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003206 layer->setVisibleRegion(visibleRegion);
3207 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003208 layer->setVisibleNonTransparentRegion(
3209 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003210 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003211
Mathias Agopian87baae12012-07-31 12:38:26 -07003212 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003213}
3214
Chia-I Wuab0c3192017-08-01 11:29:00 -07003215void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003216 for (const auto& [token, displayDevice] : mDisplays) {
3217 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003218 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003219 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003220 }
3221 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003222}
3223
Dan Stoza6b9454d2014-11-07 16:00:59 -08003224bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003225{
Ady Abraham09bd3922019-04-08 10:44:56 -07003226 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003227 ALOGV("handlePageFlip");
3228
Brian Andersond6927fb2016-07-23 23:37:30 -07003229 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003230
Mathias Agopian4fec8732012-06-29 14:12:52 -07003231 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003232 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003233 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003234
3235 // Store the set of layers that need updates. This set must not change as
3236 // buffers are being latched, as this could result in a deadlock.
3237 // Example: Two producers share the same command stream and:
3238 // 1.) Layer 0 is latched
3239 // 2.) Layer 0 gets a new frame
3240 // 2.) Layer 1 gets a new frame
3241 // 3.) Layer 1 is latched.
3242 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3243 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003244 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003245 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003246 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003247 nsecs_t expectedPresentTime;
Ana Krulecc2870422019-01-29 19:00:58 -08003248 expectedPresentTime = mScheduler->expectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003249 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003250 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003251 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003252 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003253 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003254 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003255 } else {
3256 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003257 }
Robert Carr2047fae2016-11-28 14:09:09 -08003258 });
3259
Lloyd Piquef2c79392018-12-20 16:23:33 -08003260 if (!mLayersWithQueuedFrames.empty()) {
3261 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3262 // writes to Layer current state. See also b/119481871
3263 Mutex::Autolock lock(mStateLock);
3264
3265 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003266 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003267 mLayersPendingRefresh.push_back(layer);
3268 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003269 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003270 if (layer->isBufferLatched()) {
3271 newDataLatched = true;
3272 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003273 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003274 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003275
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003276 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003277
3278 // If we will need to wake up at some time in the future to deal with a
3279 // queued frame that shouldn't be displayed during this vsync period, wake
3280 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003281 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003282 signalLayerUpdate();
3283 }
3284
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003285 // enter boot animation on first buffer latch
3286 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3287 ALOGI("Enter boot animation");
3288 mBootStage = BootStage::BOOTANIMATION;
3289 }
3290
Dan Stoza6b9454d2014-11-07 16:00:59 -08003291 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003292 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003293}
3294
Mathias Agopianad456f92011-01-13 17:53:01 -08003295void SurfaceFlinger::invalidateHwcGeometry()
3296{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003297 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003298}
3299
Lloyd Pique32cbe282018-10-19 13:09:22 -07003300void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003301 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003302 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003303 // We only need to actually compose the display if:
3304 // 1) It is being handled by hardware composer, which may need this to
3305 // keep its virtual display state machine in sync, or
3306 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003307 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003308 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003309 return;
3310 }
3311
Dan Stoza9e56aa02015-11-02 13:00:03 -08003312 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003313 base::unique_fd readyFence;
3314 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003315
3316 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003317 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003318}
3319
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003320bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3321 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003322 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003323 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003324
Lloyd Pique32cbe282018-10-19 13:09:22 -07003325 auto display = displayDevice->getCompositionDisplay();
3326 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003327 const auto displayId = display->getId();
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003328 auto& renderEngine = getRenderEngine();
Peiyong Lin548d4fa2019-04-02 18:14:44 -07003329 const bool supportProtectedContent = renderEngine.supportsProtectedContent();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003330
3331 const Region bounds(displayState.bounds);
3332 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003333 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003334 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003335
Chia-I Wu8e50e692018-05-04 10:12:37 -07003336 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003337
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003338 renderengine::DisplaySettings clientCompositionDisplay;
3339 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3340 sp<GraphicBuffer> buf;
Alec Mouri6338c9d2019-02-07 16:57:51 -08003341 base::unique_fd fd;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003342
Dan Stoza9e56aa02015-11-02 13:00:03 -08003343 if (hasClientComposition) {
3344 ALOGV("hasClientComposition");
3345
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003346 if (displayDevice->isPrimary() && supportProtectedContent) {
3347 bool needsProtected = false;
3348 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3349 // If the layer is a protected layer, mark protected context is needed.
3350 if (layer->isProtected()) {
3351 needsProtected = true;
3352 break;
3353 }
3354 }
Peiyong Lin52010312019-05-02 14:22:16 -07003355 if (needsProtected != renderEngine.isProtected()) {
3356 renderEngine.useProtectedContext(needsProtected);
3357 }
3358 if (needsProtected != display->getRenderSurface()->isProtected() &&
3359 needsProtected == renderEngine.isProtected()) {
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003360 display->getRenderSurface()->setProtected(needsProtected);
3361 }
3362 }
3363
Alec Mouri6338c9d2019-02-07 16:57:51 -08003364 buf = display->getRenderSurface()->dequeueBuffer(&fd);
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003365
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003366 if (buf == nullptr) {
3367 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3368 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003369 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003370 return false;
3371 }
3372
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003373 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3374 clientCompositionDisplay.clip = displayState.scissor;
3375 const ui::Transform& displayTransform = displayState.transform;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07003376 clientCompositionDisplay.globalTransform = displayTransform.asMatrix4();
Peiyong Linb1925962019-04-01 16:37:10 -07003377 clientCompositionDisplay.orientation = displayState.orientation;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003378
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003379 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003380 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003381 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003382 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003383 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003384 clientCompositionDisplay.outputDataspace = outputDataspace;
3385 clientCompositionDisplay.maxLuminance =
3386 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003387
Lloyd Pique441d5042018-10-18 16:49:51 -07003388 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003389 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003390 getHwComposer()
3391 .hasDisplayCapability(displayId,
3392 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003393
Peiyong Lind3788632018-09-18 16:01:31 -07003394 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003395 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3396 if (applyColorMatrix) {
Alec Mouric7e8ce82019-04-02 12:28:05 -07003397 clientCompositionDisplay.colorTransform = displayState.colorTransformMat;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003398 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003399 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003400
Mathias Agopian85d751c2012-08-29 16:59:24 -07003401 /*
3402 * and then, render the layers targeted at the framebuffer
3403 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003404
Dan Stoza9e56aa02015-11-02 13:00:03 -08003405 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003406 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003407 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003408 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003409 const Region viewportRegion(displayState.viewport);
3410 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003411 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003412 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003413 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003414 switch (layer->getCompositionType(displayDevice)) {
3415 case Hwc2::IComposerClient::Composition::CURSOR:
3416 case Hwc2::IComposerClient::Composition::DEVICE:
3417 case Hwc2::IComposerClient::Composition::SIDEBAND:
3418 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003419 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003420 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003421 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003422 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003423 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003424 // never clear the very first layer since we're
3425 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003426 renderengine::LayerSettings layerSettings;
3427 Region dummyRegion;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003428 bool prepared =
3429 layer->prepareClientLayer(renderArea, clip, dummyRegion,
3430 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003431
3432 if (prepared) {
3433 layerSettings.source.buffer.buffer = nullptr;
3434 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3435 layerSettings.alpha = half(0.0);
3436 layerSettings.disableBlending = true;
3437 clientCompositionLayers.push_back(layerSettings);
3438 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003439 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003440 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003441 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003442 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003443 renderengine::LayerSettings layerSettings;
3444 bool prepared =
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003445 layer->prepareClientLayer(renderArea, clip, clearRegion,
3446 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003447 if (prepared) {
3448 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003449 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003450 break;
3451 }
3452 default:
3453 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003454 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003455 } else {
3456 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003457 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003458 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003459 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003460
Alec Mouri820c7402019-01-23 13:02:39 -08003461 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003462 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003463 clientCompositionDisplay.clearRegion = clearRegion;
Peiyong Lin74ca2f42019-01-14 19:36:57 -08003464
3465 // We boost GPU frequency here because there will be color spaces conversion
3466 // and it's expensive. We boost the GPU frequency so that GPU composition can
3467 // finish in time. We must reset GPU frequency afterwards, because high frequency
3468 // consumes extra battery.
3469 const bool expensiveRenderingExpected =
3470 clientCompositionDisplay.outputDataspace == Dataspace::DISPLAY_P3;
3471 if (expensiveRenderingExpected && displayId) {
3472 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, true);
3473 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003474 if (!debugRegion.isEmpty()) {
3475 Region::const_iterator it = debugRegion.begin();
3476 Region::const_iterator end = debugRegion.end();
3477 while (it != end) {
3478 const Rect& rect = *it++;
3479 renderengine::LayerSettings layerSettings;
3480 layerSettings.source.buffer.buffer = nullptr;
3481 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3482 layerSettings.geometry.boundaries = rect.toFloatRect();
3483 layerSettings.alpha = half(1.0);
3484 clientCompositionLayers.push_back(layerSettings);
3485 }
3486 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003487 renderEngine.drawLayers(clientCompositionDisplay, clientCompositionLayers,
Alec Mourife0d72b2019-03-21 14:05:56 -07003488 buf->getNativeBuffer(), /*useFramebufferCache=*/true, std::move(fd),
3489 readyFence);
Peiyong Lin8ec87f82019-04-05 11:30:51 -07003490 } else if (displayId) {
3491 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, false);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003492 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003493 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003494}
3495
Chia-I Wu28e3a252018-09-07 12:05:02 -07003496void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003497 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003498 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003499}
3500
Robert Carrc0df3122019-04-11 13:18:21 -07003501status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3502 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3503 const sp<IBinder>& parentHandle,
3504 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003505 // add this layer to the current state list
3506 {
3507 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003508 sp<Layer> parent;
3509 if (parentHandle != nullptr) {
3510 parent = fromHandle(parentHandle);
3511 if (parent == nullptr) {
3512 return NAME_NOT_FOUND;
3513 }
3514 } else {
3515 parent = parentLayer;
3516 }
3517
Robert Carr1f0a16a2016-10-24 16:27:39 -07003518 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003519 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3520 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003521 return NO_MEMORY;
3522 }
Robert Carrc0df3122019-04-11 13:18:21 -07003523
3524 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3525
Robert Carrb89ea9d2018-12-10 13:01:14 -08003526 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003527 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003528 } else if (parent == nullptr) {
3529 lbc->onRemovedFromCurrentState();
3530 } else if (parent->isRemovedFromCurrentState()) {
3531 parent->addChild(lbc);
3532 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003533 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003534 parent->addChild(lbc);
3535 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003536
Yiwei Zhang243b3782018-05-15 17:40:04 -07003537 if (gbc != nullptr) {
3538 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3539 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3540 mMaxGraphicBufferProducerListSize,
3541 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3542 mGraphicBufferProducerList.size(),
3543 mMaxGraphicBufferProducerListSize, mNumLayers);
3544 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003545 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003546 }
3547
Mathias Agopian96f08192010-06-02 23:28:45 -07003548 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003549 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003550
Dan Stoza7d89d062015-04-30 13:29:25 -07003551 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003552}
3553
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003554uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003555 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003556}
3557
Mathias Agopian3f844832013-08-07 21:24:32 -07003558uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003559 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003560}
3561
Mathias Agopian3f844832013-08-07 21:24:32 -07003562uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003563 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003564}
3565
3566uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003567 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003568 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003569 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003570 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003571 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003572 }
3573 return old;
3574}
3575
Marissa Wall713b63f2018-10-17 15:42:43 -07003576bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003577 // to prevent onHandleDestroyed from being called while the lock is held,
3578 // we must keep a copy of the transactions (specifically the composer
3579 // states) around outside the scope of the lock
3580 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003581 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003582 {
3583 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003584
Valerie Haufce31b82019-04-30 16:41:14 -07003585 auto it = mTransactionQueues.begin();
3586 while (it != mTransactionQueues.end()) {
3587 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003588
Valerie Haufce31b82019-04-30 16:41:14 -07003589 while (!transactionQueue.empty()) {
3590 const auto& transaction = transactionQueue.front();
3591 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
3592 transaction.states)) {
3593 setTransactionFlags(eTransactionFlushNeeded);
3594 break;
3595 }
3596 transactions.push_back(transaction);
3597 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3598 mPendingInputWindowCommands, transaction.desiredPresentTime,
3599 transaction.buffer, transaction.callback,
3600 transaction.postTime, transaction.privileged,
3601 /*isMainThread*/ true);
3602 transactionQueue.pop();
3603 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003604 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003605
Valerie Haufce31b82019-04-30 16:41:14 -07003606 if (transactionQueue.empty()) {
3607 it = mTransactionQueues.erase(it);
3608 mTransactionCV.broadcast();
3609 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003610 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003611 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003612 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003613 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003614 return flushedATransaction;
3615}
3616
3617bool SurfaceFlinger::transactionFlushNeeded() {
3618 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003619}
3620
chaviwca27f252018-02-06 16:46:39 -08003621bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3622 for (const ComposerState& state : states) {
3623 // Here we need to check that the interface we're given is indeed
3624 // one of our own. A malicious client could give us a nullptr
3625 // IInterface, or one of its own or even one of our own but a
3626 // different type. All these situations would cause us to crash.
3627 if (state.client == nullptr) {
3628 return true;
3629 }
3630
3631 sp<IBinder> binder = IInterface::asBinder(state.client);
3632 if (binder == nullptr) {
3633 return true;
3634 }
3635
3636 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3637 return true;
3638 }
3639 }
3640 return false;
3641}
3642
Marissa Wall17b4e452018-12-26 16:32:34 -08003643bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3644 const Vector<ComposerState>& states) {
Ana Krulecc2870422019-01-29 19:00:58 -08003645 nsecs_t expectedPresentTime = mScheduler->expectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003646 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3647 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3648 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3649 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3650 return false;
3651 }
3652
Marissa Wall713b63f2018-10-17 15:42:43 -07003653 for (const ComposerState& state : states) {
3654 const layer_state_t& s = state.state;
3655 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3656 continue;
3657 }
3658 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003659 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003660 }
3661 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003662 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003663}
3664
3665void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3666 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003667 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003668 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003669 int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003670 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003671 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003672 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003673
Valerie Haubc6ddb12019-03-08 11:10:15 -08003674 const int64_t postTime = systemTime();
3675
Robert Carr14167e02019-02-13 13:50:55 -08003676 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3677
Mathias Agopian698c0872011-06-28 19:09:31 -07003678 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003679
chaviwca27f252018-02-06 16:46:39 -08003680 if (containsAnyInvalidClientState(states)) {
3681 return;
3682 }
3683
Marissa Wall713b63f2018-10-17 15:42:43 -07003684 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003685 auto itr = mTransactionQueues.find(applyToken);
3686 // if this is an animation frame, wait until prior animation frame has
3687 // been applied by SF
3688 if (flags & eAnimation) {
3689 while (itr != mTransactionQueues.end()) {
3690 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3691 if (CC_UNLIKELY(err != NO_ERROR)) {
3692 ALOGW_IF(err == TIMED_OUT,
3693 "setTransactionState timed out "
3694 "waiting for animation frame to apply");
3695 break;
3696 }
3697 itr = mTransactionQueues.find(applyToken);
3698 }
3699 }
3700 if (itr != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003701 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003702 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003703 uncacheBuffer, listenerCallbacks, postTime,
3704 privileged);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003705 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003706 return;
3707 }
3708
Valerie Haubc6ddb12019-03-08 11:10:15 -08003709 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003710 uncacheBuffer, listenerCallbacks, postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003711}
3712
3713void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003714 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003715 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003716 const int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003717 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003718 const std::vector<ListenerCallbacks>& listenerCallbacks,
Marissa Wall78b72202019-03-15 14:58:34 -07003719 const int64_t postTime, bool privileged,
3720 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003721 uint32_t transactionFlags = 0;
3722
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003723 if (flags & eAnimation) {
3724 // For window updates that are part of an animation we must wait for
3725 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003726 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003727 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003728 if (CC_UNLIKELY(err != NO_ERROR)) {
3729 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003730 // caller after a few seconds.
3731 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3732 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003733 mAnimTransactionPending = false;
3734 break;
3735 }
3736 }
3737 }
3738
chaviwca27f252018-02-06 16:46:39 -08003739 for (const DisplayState& display : displays) {
3740 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003741 }
3742
Marissa Walld600d572019-03-26 15:38:50 -07003743 // In case the client has sent a Transaction that should receive callbacks but without any
3744 // SurfaceControls that should be included in the callback, send the listener and callbackIds
3745 // to the callback thread so it can send an empty callback
3746 if (!listenerCallbacks.empty()) {
3747 mTransactionCompletedThread.run();
3748 }
3749 for (const auto& [listener, callbackIds] : listenerCallbacks) {
3750 mTransactionCompletedThread.addCallback(listener, callbackIds);
3751 }
3752
Marissa Walle2ffb422018-10-12 11:33:52 -07003753 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003754 for (const ComposerState& state : states) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07003755 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, listenerCallbacks,
3756 postTime, privileged);
3757 }
3758
Marissa Walle2ffb422018-10-12 11:33:52 -07003759 // If the state doesn't require a traversal and there are callbacks, send them now
Marissa Wallb0022cc2019-04-16 14:19:55 -07003760 if (!(clientStateFlags & eTraversalNeeded) && !listenerCallbacks.empty()) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003761 mTransactionCompletedThread.sendCallbacks();
3762 }
3763 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003764
chaviw273171b2018-12-26 11:46:30 -08003765 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3766
Marissa Wall947d34e2019-03-29 14:03:53 -07003767 if (uncacheBuffer.isValid()) {
3768 ClientCache::getInstance().erase(uncacheBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003769 }
3770
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003771 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3772 // anyway. This can be used as a flush mechanism for previous async transactions.
3773 // Empty animation transaction can be used to simulate back-pressure, so also force a
3774 // transaction for empty animation transactions.
3775 if (transactionFlags == 0 &&
3776 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003777 transactionFlags = eTransactionNeeded;
3778 }
3779
Marissa Wall06255332019-03-27 13:48:27 -07003780 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3781 // so we don't have to wake up again next frame to preform an uneeded traversal.
3782 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3783 transactionFlags = transactionFlags & (~eTraversalNeeded);
3784 mTraversalNeededMainThread = true;
3785 }
3786
Mathias Agopian386aa982011-11-07 21:58:03 -08003787 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003788 if (mInterceptor->isEnabled()) {
3789 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003790 }
Irvel468051e2016-06-13 16:44:44 -07003791
Mathias Agopian386aa982011-11-07 21:58:03 -08003792 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003793 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3794 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003795 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003796
3797 // if this is a synchronous transaction, wait for it to take effect
3798 // before returning.
3799 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003800 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003801 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003802 if (flags & eAnimation) {
3803 mAnimTransactionPending = true;
3804 }
chaviw4fe36852019-04-15 16:25:49 -07003805 if (mPendingInputWindowCommands.syncInputWindows) {
3806 mPendingSyncInputWindows = true;
3807 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003808
3809 // applyTransactionState can be called by either the main SF thread or by
3810 // another process through setTransactionState. While a given process may wish
3811 // to wait on synchronous transactions, the main SF thread should never
3812 // be blocked. Therefore, we only wait if isMainThread is false.
3813 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003814 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3815 if (CC_UNLIKELY(err != NO_ERROR)) {
3816 // just in case something goes wrong in SF, return to the
3817 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003818 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3819 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003820 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003821 break;
3822 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003823 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003824 }
3825}
3826
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003827uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3828 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3829 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003830
Mathias Agopiane57f2922012-08-09 16:29:12 -07003831 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003832 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3833
3834 const uint32_t what = s.what;
3835 if (what & DisplayState::eSurfaceChanged) {
3836 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3837 state.surface = s.surface;
3838 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003839 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003840 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003841 if (what & DisplayState::eLayerStackChanged) {
3842 if (state.layerStack != s.layerStack) {
3843 state.layerStack = s.layerStack;
3844 flags |= eDisplayTransactionNeeded;
3845 }
3846 }
3847 if (what & DisplayState::eDisplayProjectionChanged) {
3848 if (state.orientation != s.orientation) {
3849 state.orientation = s.orientation;
3850 flags |= eDisplayTransactionNeeded;
3851 }
3852 if (state.frame != s.frame) {
3853 state.frame = s.frame;
3854 flags |= eDisplayTransactionNeeded;
3855 }
3856 if (state.viewport != s.viewport) {
3857 state.viewport = s.viewport;
3858 flags |= eDisplayTransactionNeeded;
3859 }
3860 }
3861 if (what & DisplayState::eDisplaySizeChanged) {
3862 if (state.width != s.width) {
3863 state.width = s.width;
3864 flags |= eDisplayTransactionNeeded;
3865 }
3866 if (state.height != s.height) {
3867 state.height = s.height;
3868 flags |= eDisplayTransactionNeeded;
3869 }
3870 }
3871
Mathias Agopiane57f2922012-08-09 16:29:12 -07003872 return flags;
3873}
3874
Robert Carr14167e02019-02-13 13:50:55 -08003875bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003876 IPCThreadState* ipc = IPCThreadState::self();
3877 const int pid = ipc->getCallingPid();
3878 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003879 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003880 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003881 return false;
3882 }
3883 return true;
3884}
3885
Marissa Wall3dad52d2019-03-22 14:03:19 -07003886uint32_t SurfaceFlinger::setClientStateLocked(
3887 const ComposerState& composerState, int64_t desiredPresentTime,
3888 const std::vector<ListenerCallbacks>& listenerCallbacks, int64_t postTime,
3889 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003890 const layer_state_t& s = composerState.state;
3891 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3892
Mathias Agopian13127d82013-03-05 17:47:11 -08003893 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003894 if (layer == nullptr) {
3895 return 0;
3896 }
3897
chaviw8b3871a2017-11-01 17:41:01 -07003898 uint32_t flags = 0;
3899
Garfield Tan8a3083e2018-12-03 13:21:07 -08003900 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003901 bool geometryAppliesWithResize =
3902 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003903
3904 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3905 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003906 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003907 layer->pushPendingState();
3908 }
3909
chaviw8b3871a2017-11-01 17:41:01 -07003910 if (what & layer_state_t::ePositionChanged) {
3911 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3912 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003913 }
chaviw8b3871a2017-11-01 17:41:01 -07003914 }
3915 if (what & layer_state_t::eLayerChanged) {
3916 // NOTE: index needs to be calculated before we update the state
3917 const auto& p = layer->getParent();
3918 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003919 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003920 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003921 mCurrentState.layersSortedByZ.removeAt(idx);
3922 mCurrentState.layersSortedByZ.add(layer);
3923 // we need traversal (state changed)
3924 // AND transaction (list changed)
3925 flags |= eTransactionNeeded|eTraversalNeeded;
3926 }
chaviw8b3871a2017-11-01 17:41:01 -07003927 } else {
3928 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003929 flags |= eTransactionNeeded|eTraversalNeeded;
3930 }
3931 }
chaviw8b3871a2017-11-01 17:41:01 -07003932 }
3933 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003934 // NOTE: index needs to be calculated before we update the state
3935 const auto& p = layer->getParent();
3936 if (p == nullptr) {
3937 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3938 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3939 mCurrentState.layersSortedByZ.removeAt(idx);
3940 mCurrentState.layersSortedByZ.add(layer);
3941 // we need traversal (state changed)
3942 // AND transaction (list changed)
3943 flags |= eTransactionNeeded|eTraversalNeeded;
3944 }
3945 } else {
3946 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3947 flags |= eTransactionNeeded|eTraversalNeeded;
3948 }
chaviw8b3871a2017-11-01 17:41:01 -07003949 }
3950 }
3951 if (what & layer_state_t::eSizeChanged) {
3952 if (layer->setSize(s.w, s.h)) {
3953 flags |= eTraversalNeeded;
3954 }
3955 }
3956 if (what & layer_state_t::eAlphaChanged) {
3957 if (layer->setAlpha(s.alpha))
3958 flags |= eTraversalNeeded;
3959 }
3960 if (what & layer_state_t::eColorChanged) {
3961 if (layer->setColor(s.color))
3962 flags |= eTraversalNeeded;
3963 }
Peiyong Lind3788632018-09-18 16:01:31 -07003964 if (what & layer_state_t::eColorTransformChanged) {
3965 if (layer->setColorTransform(s.colorTransform)) {
3966 flags |= eTraversalNeeded;
3967 }
3968 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003969 if (what & layer_state_t::eBackgroundColorChanged) {
3970 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3971 flags |= eTraversalNeeded;
3972 }
3973 }
chaviw8b3871a2017-11-01 17:41:01 -07003974 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003975 // TODO: b/109894387
3976 //
3977 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3978 // rotation. To see the problem observe that if we have a square parent, and a child
3979 // of the same size, then we rotate the child 45 degrees around it's center, the child
3980 // must now be cropped to a non rectangular 8 sided region.
3981 //
3982 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3983 // private API, and the WindowManager only uses rotation in one case, which is on a top
3984 // level layer in which cropping is not an issue.
3985 //
3986 // However given that abuse of rotation matrices could lead to surfaces extending outside
3987 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3988 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3989 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003990 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003991 flags |= eTraversalNeeded;
3992 }
3993 if (what & layer_state_t::eTransparentRegionChanged) {
3994 if (layer->setTransparentRegionHint(s.transparentRegion))
3995 flags |= eTraversalNeeded;
3996 }
3997 if (what & layer_state_t::eFlagsChanged) {
3998 if (layer->setFlags(s.flags, s.mask))
3999 flags |= eTraversalNeeded;
4000 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004001 if (what & layer_state_t::eCropChanged_legacy) {
4002 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07004003 flags |= eTraversalNeeded;
4004 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004005 if (what & layer_state_t::eCornerRadiusChanged) {
4006 if (layer->setCornerRadius(s.cornerRadius))
4007 flags |= eTraversalNeeded;
4008 }
chaviw8b3871a2017-11-01 17:41:01 -07004009 if (what & layer_state_t::eLayerStackChanged) {
4010 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4011 // We only allow setting layer stacks for top level layers,
4012 // everything else inherits layer stack from its parent.
4013 if (layer->hasParent()) {
4014 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
4015 layer->getName().string());
4016 } else if (idx < 0) {
4017 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
4018 "that also does not appear in the top level layer list. Something"
4019 " has gone wrong.", layer->getName().string());
4020 } else if (layer->setLayerStack(s.layerStack)) {
4021 mCurrentState.layersSortedByZ.removeAt(idx);
4022 mCurrentState.layersSortedByZ.add(layer);
4023 // we need traversal (state changed)
4024 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07004025 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07004026 }
4027 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004028 if (what & layer_state_t::eDeferTransaction_legacy) {
4029 if (s.barrierHandle_legacy != nullptr) {
4030 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
4031 } else if (s.barrierGbp_legacy != nullptr) {
4032 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07004033 if (authenticateSurfaceTextureLocked(gbp)) {
4034 const auto& otherLayer =
4035 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07004036 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07004037 } else {
4038 ALOGE("Attempt to defer transaction to to an"
4039 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08004040 }
4041 }
chaviw8b3871a2017-11-01 17:41:01 -07004042 // We don't trigger a traversal here because if no other state is
4043 // changed, we don't want this to cause any more work
4044 }
4045 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08004046 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07004047 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08004048 if (!hadParent) {
4049 mCurrentState.layersSortedByZ.remove(layer);
4050 }
chaviw8b3871a2017-11-01 17:41:01 -07004051 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08004052 }
chaviw8b3871a2017-11-01 17:41:01 -07004053 }
4054 if (what & layer_state_t::eReparentChildren) {
4055 if (layer->reparentChildren(s.reparentHandle)) {
4056 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07004057 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004058 }
chaviw8b3871a2017-11-01 17:41:01 -07004059 if (what & layer_state_t::eDetachChildren) {
4060 layer->detachChildren();
4061 }
4062 if (what & layer_state_t::eOverrideScalingModeChanged) {
4063 layer->setOverrideScalingMode(s.overrideScalingMode);
4064 // We don't trigger a traversal here because if no other state is
4065 // changed, we don't want this to cause any more work
4066 }
Marissa Wall61c58622018-07-18 10:12:20 -07004067 if (what & layer_state_t::eTransformChanged) {
4068 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4069 }
4070 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4071 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4072 flags |= eTraversalNeeded;
4073 }
4074 if (what & layer_state_t::eCropChanged) {
4075 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4076 }
Marissa Wall861616d2018-10-22 12:52:23 -07004077 if (what & layer_state_t::eFrameChanged) {
4078 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
4079 }
Marissa Wall61c58622018-07-18 10:12:20 -07004080 if (what & layer_state_t::eAcquireFenceChanged) {
4081 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4082 }
4083 if (what & layer_state_t::eDataspaceChanged) {
4084 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4085 }
4086 if (what & layer_state_t::eHdrMetadataChanged) {
4087 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4088 }
4089 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4090 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4091 }
4092 if (what & layer_state_t::eApiChanged) {
4093 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4094 }
4095 if (what & layer_state_t::eSidebandStreamChanged) {
4096 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4097 }
Robert Carr720e5062018-07-30 17:45:14 -07004098 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08004099 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004100 layer->setInputInfo(s.inputInfo);
4101 flags |= eTraversalNeeded;
4102 } else {
4103 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4104 }
Robert Carr720e5062018-07-30 17:45:14 -07004105 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004106 if (what & layer_state_t::eMetadataChanged) {
4107 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4108 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004109 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4110 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4111 flags |= eTraversalNeeded;
4112 }
4113 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004114 std::vector<sp<CallbackHandle>> callbackHandles;
Marissa Wall3dad52d2019-03-22 14:03:19 -07004115 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!listenerCallbacks.empty())) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07004116 for (const auto& [listener, callbackIds] : listenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07004117 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4118 }
4119 }
Marissa Wall78b72202019-03-15 14:58:34 -07004120 bool bufferChanged = what & layer_state_t::eBufferChanged;
4121 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
4122 sp<GraphicBuffer> buffer;
4123 if (bufferChanged && cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004124 ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004125 buffer = s.buffer;
4126 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004127 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004128 } else if (bufferChanged) {
4129 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08004130 }
Marissa Wall78b72202019-03-15 14:58:34 -07004131 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004132 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08004133 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08004134 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004135 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004136 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4137 // Do not put anything that updates layer state or modifies flags after
4138 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004139 return flags;
4140}
4141
chaviw273171b2018-12-26 11:46:30 -08004142uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4143 uint32_t flags = 0;
4144 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4145 flags |= eTraversalNeeded;
4146 }
4147
chaviwa911b102019-02-14 10:18:33 -08004148 if (inputWindowCommands.syncInputWindows) {
4149 flags |= eTraversalNeeded;
4150 }
4151
Vishnu Nairec0ab382019-02-13 15:32:56 -08004152 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004153 return flags;
4154}
4155
Marissa Wall2d814fb2019-04-09 18:52:57 +00004156status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4157 uint32_t h, PixelFormat format, uint32_t flags,
4158 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07004159 sp<IGraphicBufferProducer>* gbp,
4160 const sp<IBinder>& parentHandle,
4161 const sp<Layer>& parentLayer) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004162 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004163 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004164 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004165 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004166 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004167
Robert Carrc0df3122019-04-11 13:18:21 -07004168 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4169 "Expected only one of parentLayer or parentHandle to be non-null. "
4170 "Programmer error?");
4171
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004172 status_t result = NO_ERROR;
4173
4174 sp<Layer> layer;
4175
Cody Northropbc755282017-03-31 12:00:08 -06004176 String8 uniqueName = getUniqueLayerName(name);
4177
Evan Roskya1f1e152019-01-24 16:17:46 -08004178 bool primaryDisplayOnly = false;
4179
4180 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4181 // TODO b/64227542
4182 if (metadata.has(METADATA_WINDOW_TYPE)) {
4183 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4184 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07004185 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08004186 primaryDisplayOnly = true;
4187 }
4188 }
4189
Mathias Agopian3165cc22012-08-08 19:42:09 -07004190 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004191 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Evan Roskya1f1e152019-01-24 16:17:46 -08004192 result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata),
4193 format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004194
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004195 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004196 case ISurfaceComposerClient::eFXSurfaceBufferState:
Evan Roskya1f1e152019-01-24 16:17:46 -08004197 result = createBufferStateLayer(client, uniqueName, w, h, flags, std::move(metadata),
4198 handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07004199 break;
chaviw13fdc492017-06-27 12:40:18 -07004200 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004201 // check if buffer size is set for color layer.
4202 if (w > 0 || h > 0) {
4203 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4204 int(w), int(h));
4205 return BAD_VALUE;
4206 }
4207
Evan Roskya1f1e152019-01-24 16:17:46 -08004208 result = createColorLayer(client, uniqueName, w, h, flags, std::move(metadata), handle,
4209 &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004210 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004211 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004212 // check if buffer size is set for container layer.
4213 if (w > 0 || h > 0) {
4214 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4215 int(w), int(h));
4216 return BAD_VALUE;
4217 }
Evan Roskya1f1e152019-01-24 16:17:46 -08004218 result = createContainerLayer(client, uniqueName, w, h, flags, std::move(metadata),
4219 handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004220 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004221 default:
4222 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004223 break;
4224 }
4225
Dan Stoza7d89d062015-04-30 13:29:25 -07004226 if (result != NO_ERROR) {
4227 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004228 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004229
Evan Roskya1f1e152019-01-24 16:17:46 -08004230 if (primaryDisplayOnly) {
4231 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07004232 }
4233
Robert Carrb89ea9d2018-12-10 13:01:14 -08004234 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07004235 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
4236 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004237 if (result != NO_ERROR) {
4238 return result;
4239 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004240 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004241
4242 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004243 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004244}
4245
Cody Northropbc755282017-03-31 12:00:08 -06004246String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4247{
4248 bool matchFound = true;
4249 uint32_t dupeCounter = 0;
4250
4251 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4252 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4253
Dan Stoza436ccf32018-06-21 12:10:12 -07004254 // Grab the state lock since we're accessing mCurrentState
4255 Mutex::Autolock lock(mStateLock);
4256
Cody Northropbc755282017-03-31 12:00:08 -06004257 // Loop over layers until we're sure there is no matching name
4258 while (matchFound) {
4259 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004260 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004261 if (layer->getName() == uniqueName) {
4262 matchFound = true;
4263 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4264 }
4265 });
4266 }
4267
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004268 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4269 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004270
4271 return uniqueName;
4272}
4273
Marissa Wallfd668622018-05-10 10:21:13 -07004274status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4275 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004276 LayerMetadata metadata, PixelFormat& format,
4277 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004278 sp<IGraphicBufferProducer>* gbp,
4279 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004280 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004281 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004282 case PIXEL_FORMAT_TRANSPARENT:
4283 case PIXEL_FORMAT_TRANSLUCENT:
4284 format = PIXEL_FORMAT_RGBA_8888;
4285 break;
4286 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004287 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004288 break;
4289 }
4290
Evan Roskya1f1e152019-01-24 16:17:46 -08004291 sp<BufferQueueLayer> layer = getFactory().createBufferQueueLayer(
4292 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wallfd668622018-05-10 10:21:13 -07004293 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004294 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004295 *handle = layer->getHandle();
4296 *gbp = layer->getProducer();
4297 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004298 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004299
Marissa Wallfd668622018-05-10 10:21:13 -07004300 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004301 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004302}
4303
Marissa Wall61c58622018-07-18 10:12:20 -07004304status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4305 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004306 LayerMetadata metadata, sp<IBinder>* handle,
4307 sp<Layer>* outLayer) {
4308 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(
4309 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wall61c58622018-07-18 10:12:20 -07004310 *handle = layer->getHandle();
4311 *outLayer = layer;
4312
4313 return NO_ERROR;
4314}
4315
Evan Roskya1f1e152019-01-24 16:17:46 -08004316status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, uint32_t w,
4317 uint32_t h, uint32_t flags, LayerMetadata metadata,
4318 sp<IBinder>* handle, sp<Layer>* outLayer) {
4319 *outLayer = getFactory().createColorLayer(
4320 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004321 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004322 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004323}
4324
Evan Roskya1f1e152019-01-24 16:17:46 -08004325status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name,
4326 uint32_t w, uint32_t h, uint32_t flags,
4327 LayerMetadata metadata, sp<IBinder>* handle,
4328 sp<Layer>* outLayer) {
4329 *outLayer = getFactory().createContainerLayer(
4330 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004331 *handle = (*outLayer)->getHandle();
4332 return NO_ERROR;
4333}
4334
4335
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004336void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004337 mLayersPendingRemoval.add(layer);
4338 mLayersRemoved = true;
4339 setTransactionFlags(eTransactionNeeded);
4340}
4341
Robert Carr695d5282018-12-18 15:27:58 -08004342void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004343{
Robert Carr2e102c92018-10-23 12:11:15 -07004344 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004345 // If a layer has a parent, we allow it to out-live it's handle
4346 // with the idea that the parent holds a reference and will eventually
4347 // be cleaned up. However no one cleans up the top-level so we do so
4348 // here.
4349 if (layer->getParent() == nullptr) {
4350 mCurrentState.layersSortedByZ.remove(layer);
4351 }
4352 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004353
4354 auto it = mLayersByLocalBinderToken.begin();
4355 while (it != mLayersByLocalBinderToken.end()) {
4356 if (it->second == layer) {
4357 it = mLayersByLocalBinderToken.erase(it);
4358 } else {
4359 it++;
4360 }
4361 }
4362
Robert Carr695d5282018-12-18 15:27:58 -08004363 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004364}
4365
Mathias Agopianb60314a2012-04-10 22:09:54 -07004366// ---------------------------------------------------------------------------
4367
Andy McFadden13a082e2012-08-24 10:16:42 -07004368void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004369 const auto display = getDefaultDisplayDeviceLocked();
4370 if (!display) return;
4371
4372 const sp<IBinder> token = display->getDisplayToken().promote();
4373 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004374
Jesse Hall01e29052013-02-19 16:13:35 -08004375 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004376 Vector<ComposerState> state;
4377 Vector<DisplayState> displays;
4378 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004379 d.what = DisplayState::eDisplayProjectionChanged |
4380 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004381 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004382 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004383 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004384 d.frame.makeInvalid();
4385 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004386 d.width = 0;
4387 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004388 displays.add(d);
Marissa Wall3dad52d2019-03-22 14:03:19 -07004389 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004390
Dominik Laskowskie9774092018-12-11 10:04:24 -08004391 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004392
Dominik Laskowski83b88212018-12-11 13:34:06 -08004393 const nsecs_t vsyncPeriod = getVsyncPeriod();
4394 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004395
Brian Andersond0010582017-03-07 13:20:31 -08004396 // Use phase of 0 since phase is not known.
4397 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004398 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004399 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004400}
4401
4402void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004403 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004404 postMessageAsync(
4405 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004406}
4407
Dominik Laskowskie9774092018-12-11 10:04:24 -08004408void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004409 if (display->isVirtual()) {
4410 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004411 return;
4412 }
4413
Dominik Laskowski075d3172018-05-24 15:50:06 -07004414 const auto displayId = display->getId();
4415 LOG_ALWAYS_FATAL_IF(!displayId);
4416
Dominik Laskowski34157762018-10-31 13:07:19 -07004417 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004418
4419 int currentMode = display->getPowerMode();
4420 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004421 return;
4422 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004423
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004424 display->setPowerMode(mode);
4425
Lloyd Pique4dccc412018-01-22 17:21:36 -08004426 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004427 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004428 }
4429
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004430 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004431 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004432 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004433 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004434 mScheduler->onScreenAcquired(mAppConnectionHandle);
4435 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004436 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004437
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004438 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004439 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004440 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004441
4442 struct sched_param param = {0};
4443 param.sched_priority = 1;
4444 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4445 ALOGW("Couldn't set SCHED_FIFO on display on");
4446 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004447 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004448 // Turn off the display
4449 struct sched_param param = {0};
4450 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4451 ALOGW("Couldn't set SCHED_OTHER on display off");
4452 }
4453
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004454 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004455 mScheduler->disableHardwareVsync(true);
4456 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004457 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004458
Dominik Laskowski075d3172018-05-24 15:50:06 -07004459 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004460 mVisibleRegionsDirty = true;
4461 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004462 } else if (mode == HWC_POWER_MODE_DOZE ||
4463 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004464 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004465 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004466 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004467 mScheduler->onScreenAcquired(mAppConnectionHandle);
4468 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004469 }
4470 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4471 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004472 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004473 mScheduler->disableHardwareVsync(true);
4474 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004475 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004476 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004477 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004478 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004479 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004480 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004481
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004482 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004483 mTimeStats->setPowerMode(mode);
Dominik Laskowski22488f62019-03-28 09:53:04 -07004484 mRefreshRateStats.setPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004485 }
4486
Dominik Laskowski34157762018-10-31 13:07:19 -07004487 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004488}
4489
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004490void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004491 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004492 const auto display = getDisplayDevice(displayToken);
4493 if (!display) {
4494 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4495 displayToken.get());
4496 } else if (display->isVirtual()) {
4497 ALOGW("Attempt to set power mode %d for virtual display", mode);
4498 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004499 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004500 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004501 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004502}
4503
4504// ---------------------------------------------------------------------------
4505
Dominik Laskowskic2867142019-01-21 11:33:38 -08004506status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4507 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004508 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004509
Mathias Agopianbd115332013-04-18 16:41:04 -07004510 IPCThreadState* ipc = IPCThreadState::self();
4511 const int pid = ipc->getCallingPid();
4512 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004513
Mathias Agopianbd115332013-04-18 16:41:04 -07004514 if ((uid != AID_SHELL) &&
4515 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004516 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4517 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004518 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004519 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004520 // (this would indicate SF is stuck, but we want to be able to
4521 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004522 status_t err = mStateLock.timedLock(s2ns(1));
4523 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004524 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004525 StringAppendF(&result,
4526 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4527 "(no locks held)\n",
4528 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004529 }
4530
Dominik Laskowskic2867142019-01-21 11:33:38 -08004531 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004532
Dominik Laskowskic2867142019-01-21 11:33:38 -08004533 static const std::unordered_map<std::string, Dumper> dumpers = {
4534 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4535 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4536 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004537 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004538 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004539 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004540 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4541 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004542 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4543 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4544 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4545 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4546 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4547 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004548 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004549 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4550 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004551
Dominik Laskowskic2867142019-01-21 11:33:38 -08004552 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004553
Dominik Laskowskic2867142019-01-21 11:33:38 -08004554 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4555 (it->second)(args, asProto, result);
4556 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004557 if (asProto) {
4558 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4559 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4560 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004561 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004562 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004563 }
4564
Mathias Agopian9795c422009-08-26 16:36:26 -07004565 if (locked) {
4566 mStateLock.unlock();
4567 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004568 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004569 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004570 return NO_ERROR;
4571}
4572
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004573status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4574 if (asProto && mTracing.isEnabled()) {
4575 mTracing.writeToFileAsync();
4576 }
4577
4578 return doDump(fd, DumpArgs(), asProto);
4579}
4580
Dominik Laskowskic2867142019-01-21 11:33:38 -08004581void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004582 mCurrentState.traverseInZOrder(
4583 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004584}
4585
Dominik Laskowskic2867142019-01-21 11:33:38 -08004586void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004587 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004588
Dominik Laskowskic2867142019-01-21 11:33:38 -08004589 if (args.size() > 1) {
4590 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004591 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004592 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004593 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004594 }
Robert Carr2047fae2016-11-28 14:09:09 -08004595 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004596 } else {
4597 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004598 }
4599}
4600
Dominik Laskowskic2867142019-01-21 11:33:38 -08004601void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004602 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004603 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004604 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004605 }
Robert Carr2047fae2016-11-28 14:09:09 -08004606 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004607
Svetoslavd85084b2014-03-20 10:28:31 -07004608 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004609}
4610
Dominik Laskowskic2867142019-01-21 11:33:38 -08004611void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4612 mTimeStats->parseArgs(asProto, args, result);
4613}
4614
Jamie Gennis6547ff42013-07-16 20:12:42 -07004615// This should only be called from the main thread. Otherwise it would need
4616// the lock and should use mCurrentState rather than mDrawingState.
4617void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004618 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004619 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004620 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004621
4622 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4623}
4624
Yiwei Zhang5434a782018-12-05 18:06:32 -08004625void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004626 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004627
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004628 if (isLayerTripleBufferingDisabled())
4629 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004630
Yiwei Zhang5434a782018-12-05 18:06:32 -08004631 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4632 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4633 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4634 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4635 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4636 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004637 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004638}
4639
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004640void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004641 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004642 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004643 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004644 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004645
Ady Abraham97d04232019-03-05 19:48:12 -08004646 StringAppendF(&result, "Scheduler enabled.");
Ana Krulecba13ab32019-02-20 14:14:12 -08004647 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4648 mUseSmart90ForVideo ? "on" : "off");
Ana Krulecc2870422019-01-29 19:00:58 -08004649 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004650}
4651
Yiwei Zhang5434a782018-12-05 18:06:32 -08004652void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4653 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004654 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4655 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004656 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004657 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004658 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004659 }
David Sodman4a36e932017-11-07 14:29:47 -08004660 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004661 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004662 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004663 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4664 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004665}
4666
Dan Stozae77c7662016-05-13 11:37:28 -07004667void SurfaceFlinger::recordBufferingStats(const char* layerName,
4668 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004669 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4670 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004671 for (const auto& segment : history) {
4672 if (!segment.usedThirdBuffer) {
4673 stats.twoBufferTime += segment.totalTime;
4674 }
4675 if (segment.occupancyAverage < 1.0f) {
4676 stats.doubleBufferedTime += segment.totalTime;
4677 } else if (segment.occupancyAverage < 2.0f) {
4678 stats.tripleBufferedTime += segment.totalTime;
4679 }
4680 ++stats.numSegments;
4681 stats.totalTime += segment.totalTime;
4682 }
4683}
4684
Yiwei Zhang5434a782018-12-05 18:06:32 -08004685void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4686 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004687
4688 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4689 const size_t count = currentLayers.size();
4690 for (size_t i=0 ; i<count ; i++) {
4691 currentLayers[i]->dumpFrameEvents(result);
4692 }
4693}
4694
Yiwei Zhang5434a782018-12-05 18:06:32 -08004695void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004696 result.append("Buffering stats:\n");
4697 result.append(" [Layer name] <Active time> <Two buffer> "
4698 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004699 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004700 typedef std::tuple<std::string, float, float, float> BufferTuple;
4701 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004702 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004703 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004704 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004705 if (stats.numSegments == 0) {
4706 continue;
4707 }
4708 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4709 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4710 stats.totalTime;
4711 float doubleBufferRatio = static_cast<float>(
4712 stats.doubleBufferedTime) / stats.totalTime;
4713 float tripleBufferRatio = static_cast<float>(
4714 stats.tripleBufferedTime) / stats.totalTime;
4715 sorted.insert({activeTime, {name, twoBufferRatio,
4716 doubleBufferRatio, tripleBufferRatio}});
4717 }
4718 for (const auto& sortedPair : sorted) {
4719 float activeTime = sortedPair.first;
4720 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004721 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4722 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004723 }
4724 result.append("\n");
4725}
4726
Yiwei Zhang5434a782018-12-05 18:06:32 -08004727void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004728 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004729 const auto displayId = display->getId();
4730 if (!displayId) {
4731 continue;
4732 }
4733 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004734 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004735 continue;
4736 }
4737
Yiwei Zhang5434a782018-12-05 18:06:32 -08004738 StringAppendF(&result,
4739 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4740 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004741 uint8_t port;
4742 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004743 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004744 result.append("no identification data\n");
4745 continue;
4746 }
4747
4748 if (!isEdid(data)) {
4749 result.append("unknown identification data: ");
4750 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004751 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004752 }
4753 result.append("\n");
4754 continue;
4755 }
4756
4757 const auto edid = parseEdid(data);
4758 if (!edid) {
4759 result.append("invalid EDID: ");
4760 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004761 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004762 }
4763 result.append("\n");
4764 continue;
4765 }
4766
Yiwei Zhang5434a782018-12-05 18:06:32 -08004767 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004768 result.append(edid->displayName.data(), edid->displayName.length());
4769 result.append("\"\n");
4770 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004771}
4772
Yiwei Zhang5434a782018-12-05 18:06:32 -08004773void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004774 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004775 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4776 StringAppendF(&result, "DisplayColorSetting: %s\n",
4777 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004778
4779 // TODO: print out if wide-color mode is active or not
4780
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004781 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004782 const auto displayId = display->getId();
4783 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004784 continue;
4785 }
4786
Yiwei Zhang5434a782018-12-05 18:06:32 -08004787 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004788 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004789 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004790 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004791 }
4792
Lloyd Pique32cbe282018-10-19 13:09:22 -07004793 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004794 StringAppendF(&result, " Current color mode: %s (%d)\n",
4795 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004796 }
4797 result.append("\n");
4798}
4799
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004800LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet,
4801 uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004802 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004803 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4804 const State& state = useDrawing ? mDrawingState : mCurrentState;
4805 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004806 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004807 layer->writeToProto(layerProto, stateSet, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004808 });
4809
4810 return layersProto;
4811}
4812
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004813LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4814 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004815 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004816
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004817 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004818 resolution->set_w(displayDevice->getWidth());
4819 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004820
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004821 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004822 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004823
Lloyd Pique32cbe282018-10-19 13:09:22 -07004824 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4825 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4826 layersProto.set_global_transform(displayState.orientation);
4827
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004828 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004829 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004830 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004831 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004832 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004833 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004834 }
4835 });
4836
4837 return layersProto;
4838}
4839
Dominik Laskowskic2867142019-01-21 11:33:38 -08004840void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4841 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004842 Colorizer colorizer(colorize);
4843
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004844 // figure out if we're stuck somewhere
4845 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004846 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004847 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4848
4849 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004850 * Dump library configuration.
4851 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004852
4853 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004854 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004855 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004856 appendSfConfigString(result);
4857 appendUiConfigString(result);
4858 appendGuiConfigString(result);
4859 result.append("\n");
4860
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004861 result.append("\nDisplay identification data:\n");
4862 dumpDisplayIdentificationData(result);
4863
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004864 result.append("\nWide-Color information:\n");
4865 dumpWideColorInfo(result);
4866
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004867 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004868 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004869 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004870 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004871 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004872
Andy McFadden41d67d72014-04-25 16:58:34 -07004873 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004874 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004875 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004876 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004877 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004878
Dan Stozab90cf072015-03-05 11:05:59 -08004879 dumpStaticScreenStats(result);
4880 result.append("\n");
4881
Alec Mouri40189b02019-03-05 15:07:54 -08004882 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4883 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4884 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004885
Dan Stozae77c7662016-05-13 11:37:28 -07004886 dumpBufferingStats(result);
4887
Andy McFadden4803b742012-09-24 19:07:20 -07004888 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004889 * Dump the visible layer list
4890 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004891 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004892 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4893 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4894 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004895 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004896
Chia-I Wu2f884132018-09-13 15:17:58 -07004897 {
4898 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4899 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004900 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004901 result.append("\n");
4902 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004903
Lloyd Pique207def92019-02-28 16:09:52 -08004904 {
4905 StringAppendF(&result, "Composition layers\n");
4906 mDrawingState.traverseInZOrder([&](Layer* layer) {
4907 auto compositionLayer = layer->getCompositionLayer();
4908 if (compositionLayer) compositionLayer->dump(result);
4909 });
4910 }
4911
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004912 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004913 * Dump Display state
4914 */
4915
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004916 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004917 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004918 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004919 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004920 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004921 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004922 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004923
4924 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004925 * Dump SurfaceFlinger global state
4926 */
4927
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004928 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004929 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004930 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004931
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004932 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004933
Dominik Laskowski075d3172018-05-24 15:50:06 -07004934 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004935 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4936 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004937 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4938 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004939 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004940 StringAppendF(&result,
4941 " transaction-flags : %08x\n"
4942 " gpu_to_cpu_unsupported : %d\n",
4943 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004944
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004945 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004946 displayId && getHwComposer().isConnected(*displayId)) {
4947 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004948 StringAppendF(&result,
4949 " refresh-rate : %f fps\n"
4950 " x-dpi : %f\n"
4951 " y-dpi : %f\n",
4952 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4953 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004954 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004955
Yiwei Zhang5434a782018-12-05 18:06:32 -08004956 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004957
Dan Stozae22aec72016-08-01 13:20:59 -07004958 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004959 * Tracing state
4960 */
4961 mTracing.dump(result);
4962 result.append("\n");
4963
4964 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004965 * HWC layer minidump
4966 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004967 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004968 const auto displayId = display->getId();
4969 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004970 continue;
4971 }
4972
Yiwei Zhang5434a782018-12-05 18:06:32 -08004973 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004974 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004975 const sp<DisplayDevice> displayDevice = display;
4976 mCurrentState.traverseInZOrder(
4977 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004978 result.append("\n");
4979 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004980
4981 /*
4982 * Dump HWComposer state
4983 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004984 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004985 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004986 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004987 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004988 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004989 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004990
4991 /*
4992 * Dump gralloc state
4993 */
4994 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4995 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004996
4997 /*
4998 * Dump VrFlinger state if in use.
4999 */
5000 if (mVrFlingerRequestsDisplay && mVrFlinger) {
5001 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08005002 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005003 result.append("\n");
5004 }
Ana Krulecb43429d2019-01-09 14:28:51 -08005005
5006 /**
5007 * Scheduler dump state.
5008 */
Ana Krulecc2870422019-01-29 19:00:58 -08005009 result.append("\nScheduler state:\n");
5010 result.append(mScheduler->doDump() + "\n");
Ana Krulecfefd6ae2019-02-13 17:53:08 -08005011 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
Dominik Laskowski22488f62019-03-28 09:53:04 -07005012 result.append(mRefreshRateStats.doDump() + "\n");
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07005013
5014 result.append(mTimeStats->miniDump());
5015 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005016}
5017
Dominik Laskowski075d3172018-05-24 15:50:06 -07005018const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07005019 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005020 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07005021 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005022 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07005023 }
5024 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005025
Dominik Laskowski34157762018-10-31 13:07:19 -07005026 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005027 static const Vector<sp<Layer>> empty;
5028 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07005029}
5030
Chia-I Wu28f320b2018-05-03 11:02:56 -07005031void SurfaceFlinger::updateColorMatrixLocked() {
5032 mat4 colorMatrix;
5033 if (mGlobalSaturationFactor != 1.0f) {
5034 // Rec.709 luma coefficients
5035 float3 luminance{0.213f, 0.715f, 0.072f};
5036 luminance *= 1.0f - mGlobalSaturationFactor;
5037 mat4 saturationMatrix = mat4(
5038 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
5039 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
5040 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
5041 vec4{0.0f, 0.0f, 0.0f, 1.0f}
5042 );
5043 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
5044 } else {
5045 colorMatrix = mClientColorMatrix * mDaltonizer();
5046 }
5047
5048 if (mCurrentState.colorMatrix != colorMatrix) {
5049 mCurrentState.colorMatrix = colorMatrix;
5050 mCurrentState.colorMatrixChanged = true;
5051 setTransactionFlags(eTransactionNeeded);
5052 }
5053}
5054
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005055status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005056#pragma clang diagnostic push
5057#pragma clang diagnostic error "-Wswitch-enum"
5058 switch (static_cast<ISurfaceComposerTag>(code)) {
5059 // These methods should at minimum make sure that the client requested
5060 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005061 case BOOT_FINISHED:
5062 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005063 case CREATE_DISPLAY:
5064 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005065 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005066 case GET_ANIMATION_FRAME_STATS:
5067 case GET_HDR_CAPABILITIES:
5068 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08005069 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005070 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005071 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005072 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005073 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005074 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005075 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07005076 case GET_DISPLAYED_CONTENT_SAMPLE:
5077 case NOTIFY_POWER_HINT: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005078 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5079 IPCThreadState* ipc = IPCThreadState::self();
5080 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5081 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005082 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005083 }
Robert Carr1db73f62016-12-21 12:58:51 -08005084 return OK;
5085 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005086 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005087 IPCThreadState* ipc = IPCThreadState::self();
5088 const int pid = ipc->getCallingPid();
5089 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005090 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5091 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005092 return PERMISSION_DENIED;
5093 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005094 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005095 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005096 // Used by apps to hook Choreographer to SurfaceFlinger.
5097 case CREATE_DISPLAY_EVENT_CONNECTION:
5098 // The following calls are currently used by clients that do not
5099 // request necessary permissions. However, they do not expose any secret
5100 // information, so it is OK to pass them.
5101 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07005102 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005103 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005104 case GET_PHYSICAL_DISPLAY_IDS:
5105 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005106 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005107 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005108 case GET_DISPLAY_CONFIGS:
5109 case GET_DISPLAY_STATS:
5110 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5111 // Calling setTransactionState is safe, because you need to have been
5112 // granted a reference to Client* and Handle* to do anything with it.
5113 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005114 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005115 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005116 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005117 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00005118 case IS_WIDE_COLOR_DISPLAY:
5119 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5120 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005121 return OK;
5122 }
5123 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08005124 case CAPTURE_SCREEN:
5125 case ADD_REGION_SAMPLING_LISTENER:
5126 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005127 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005128 IPCThreadState* ipc = IPCThreadState::self();
5129 const int pid = ipc->getCallingPid();
5130 const int uid = ipc->getCallingUid();
5131 if ((uid != AID_GRAPHICS) &&
5132 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5133 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5134 return PERMISSION_DENIED;
5135 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005136 return OK;
5137 }
5138 // The following codes are deprecated and should never be allowed to access SF.
5139 case CONNECT_DISPLAY_UNUSED:
5140 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5141 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5142 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005143 }
chaviw93df2ea2019-04-30 16:45:12 -07005144 case CAPTURE_SCREEN_BY_ID: {
5145 IPCThreadState* ipc = IPCThreadState::self();
5146 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07005147 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07005148 return OK;
5149 }
5150 return PERMISSION_DENIED;
5151 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005152 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005153
5154 // These codes are used for the IBinder protocol to either interrogate the recipient
5155 // side of the transaction for its canonical interface descriptor or to dump its state.
5156 // We let them pass by default.
5157 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5158 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5159 code == IBinder::SYSPROPS_TRANSACTION) {
5160 return OK;
5161 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005162 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005163 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07005164 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005165 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5166 return OK;
5167 }
5168 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5169 return PERMISSION_DENIED;
5170#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005171}
5172
Ana Krulec13be8ad2018-08-21 02:43:56 +00005173status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5174 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005175 status_t credentialCheck = CheckTransactCodeCredentials(code);
5176 if (credentialCheck != OK) {
5177 return credentialCheck;
5178 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005179
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005180 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5181 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005182 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005183 IPCThreadState* ipc = IPCThreadState::self();
5184 const int uid = ipc->getCallingUid();
5185 if (CC_UNLIKELY(uid != AID_SYSTEM
5186 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005187 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005188 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005189 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005190 return PERMISSION_DENIED;
5191 }
5192 int n;
5193 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005194 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005195 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005196 return NO_ERROR;
5197 case 1002: // SHOW_UPDATES
5198 n = data.readInt32();
5199 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005200 invalidateHwcGeometry();
5201 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005202 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005203 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005204 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005205 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005206 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005207 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005208 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005209 setTransactionFlags(
5210 eTransactionNeeded|
5211 eDisplayTransactionNeeded|
5212 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005213 return NO_ERROR;
5214 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005215 case 1006:{ // send empty update
5216 signalRefresh();
5217 return NO_ERROR;
5218 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005219 case 1008: // toggle use of hw composer
5220 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005221 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07005222 invalidateHwcGeometry();
5223 repaintEverything();
5224 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005225 case 1009: // toggle use of transform hint
5226 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005227 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07005228 invalidateHwcGeometry();
5229 repaintEverything();
5230 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005231 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005232 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005233 reply->writeInt32(0);
5234 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005235 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005236 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005237 return NO_ERROR;
5238 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005239 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005240 if (!display) {
5241 return NAME_NOT_FOUND;
5242 }
5243
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005244 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005245 return NO_ERROR;
5246 }
5247 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005248 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005249 // daltonize
5250 n = data.readInt32();
5251 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005252 case 1:
5253 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5254 break;
5255 case 2:
5256 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5257 break;
5258 case 3:
5259 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5260 break;
5261 default:
5262 mDaltonizer.setType(ColorBlindnessType::None);
5263 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005264 }
5265 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005266 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005267 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005268 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005269 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005270
5271 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005272 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005273 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005274 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005275 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005276 // apply a color matrix
5277 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005278 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005279 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005280 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005281 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005282 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005283 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005284 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005285 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005286 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005287 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005288
5289 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5290 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005291 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005292 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5293 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5294 }
5295
Chia-I Wu28f320b2018-05-03 11:02:56 -07005296 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005297 return NO_ERROR;
5298 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005299 // This is an experimental interface
5300 // Needs to be shifted to proper binder interface when we productize
5301 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005302 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005303 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005304 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005305 return NO_ERROR;
5306 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005307 case 1017: {
5308 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005309 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005310 return NO_ERROR;
5311 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005312 case 1018: { // Modify Choreographer's phase offset
5313 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005314 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005315 return NO_ERROR;
5316 }
5317 case 1019: { // Modify SurfaceFlinger's phase offset
5318 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005319 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005320 return NO_ERROR;
5321 }
Irvel468051e2016-06-13 16:44:44 -07005322 case 1020: { // Layer updates interceptor
5323 n = data.readInt32();
5324 if (n) {
5325 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005326 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005327 }
5328 else{
5329 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005330 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005331 }
5332 return NO_ERROR;
5333 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005334 case 1021: { // Disable HWC virtual displays
5335 n = data.readInt32();
5336 mUseHwcVirtualDisplays = !n;
5337 return NO_ERROR;
5338 }
Romain Guy0147a172017-06-01 13:53:56 -07005339 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005340 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005341 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005342
Chia-I Wu28f320b2018-05-03 11:02:56 -07005343 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005344 return NO_ERROR;
5345 }
Romain Guy54f154a2017-10-24 21:40:32 +01005346 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005347 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005348 invalidateHwcGeometry();
5349 repaintEverything();
5350 return NO_ERROR;
5351 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005352 // Deprecate, use 1030 to check whether the device is color managed.
5353 case 1024: {
5354 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005355 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005356 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005357 n = data.readInt32();
5358 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005359 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005360 Mutex::Autolock lock(mStateLock);
5361 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005362 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005363 reply->writeInt32(NO_ERROR);
5364 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005365 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005366 bool writeFile = false;
5367 {
5368 Mutex::Autolock lock(mStateLock);
5369 mTracingEnabledChanged = true;
5370 writeFile = mTracing.disable();
5371 }
5372
5373 if (writeFile) {
5374 reply->writeInt32(mTracing.writeToFile());
5375 } else {
5376 reply->writeInt32(NO_ERROR);
5377 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005378 }
5379 return NO_ERROR;
5380 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005381 case 1026: { // Get layer tracing status
5382 reply->writeBool(mTracing.isEnabled());
5383 return NO_ERROR;
5384 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005385 // Is a DisplayColorSetting supported?
5386 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005387 const auto display = getDefaultDisplayDevice();
5388 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005389 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005390 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005391
5392 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5393 switch (setting) {
5394 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005395 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005396 break;
5397 case DisplayColorSetting::UNMANAGED:
5398 reply->writeBool(true);
5399 break;
5400 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005401 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005402 break;
5403 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005404 reply->writeBool(
5405 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005406 break;
5407 }
5408 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005409 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005410 // Is VrFlinger active?
5411 case 1028: {
5412 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005413 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005414 return NO_ERROR;
5415 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005416 // Set buffer size for SF tracing (value in KB)
5417 case 1029: {
5418 n = data.readInt32();
5419 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5420 ALOGW("Invalid buffer size: %d KB", n);
5421 reply->writeInt32(BAD_VALUE);
5422 return BAD_VALUE;
5423 }
5424
5425 ALOGD("Updating trace buffer to %d KB", n);
5426 mTracing.setBufferSize(n * 1024);
5427 reply->writeInt32(NO_ERROR);
5428 return NO_ERROR;
5429 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005430 // Is device color managed?
5431 case 1030: {
5432 reply->writeBool(useColorManagement);
5433 return NO_ERROR;
5434 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005435 // Override default composition data space
5436 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5437 // && adb shell stop zygote && adb shell start zygote
5438 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5439 // adb shell stop zygote && adb shell start zygote
5440 case 1031: {
5441 Mutex::Autolock _l(mStateLock);
5442 n = data.readInt32();
5443 if (n) {
5444 n = data.readInt32();
5445 if (n) {
5446 Dataspace dataspace = static_cast<Dataspace>(n);
5447 if (!validateCompositionDataspace(dataspace)) {
5448 return BAD_VALUE;
5449 }
5450 mDefaultCompositionDataspace = dataspace;
5451 }
5452 n = data.readInt32();
5453 if (n) {
5454 Dataspace dataspace = static_cast<Dataspace>(n);
5455 if (!validateCompositionDataspace(dataspace)) {
5456 return BAD_VALUE;
5457 }
5458 mWideColorGamutCompositionDataspace = dataspace;
5459 }
5460 } else {
5461 // restore composition data space.
5462 mDefaultCompositionDataspace = defaultCompositionDataspace;
5463 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5464 }
5465 return NO_ERROR;
5466 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005467 // Set trace flags
5468 case 1033: {
5469 n = data.readUint32();
5470 ALOGD("Updating trace flags to 0x%x", n);
5471 mTracing.setTraceFlags(n);
5472 reply->writeInt32(NO_ERROR);
5473 return NO_ERROR;
5474 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005475 case 1034: {
5476 // TODO(b/129297325): expose this via developer menu option
5477 n = data.readInt32();
5478 if (n && !mRefreshRateOverlay) {
Ady Abrahamfed164b2019-05-10 17:12:54 -07005479 RefreshRateType type;
5480 {
5481 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5482 type = mDesiredActiveConfig.type;
5483 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005484 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abrahamfed164b2019-05-10 17:12:54 -07005485 mRefreshRateOverlay->changeRefreshRate(type);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005486 } else if (!n) {
5487 mRefreshRateOverlay.reset();
5488 }
5489 return NO_ERROR;
5490 }
Ady Abraham34392f72019-04-10 11:29:27 -07005491 case 1035: {
5492 n = data.readInt32();
5493 mDebugDisplayConfigSetByBackdoor = false;
5494 if (n >= 0) {
5495 const auto displayToken = getInternalDisplayToken();
5496 status_t result = setAllowedDisplayConfigs(displayToken, {n});
5497 if (result != NO_ERROR) {
5498 return result;
5499 }
5500 mDebugDisplayConfigSetByBackdoor = true;
5501 }
5502 return NO_ERROR;
5503 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005504 }
5505 }
5506 return err;
5507}
5508
Steven Thomas6d8110b2017-08-31 18:24:21 -07005509void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005510 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005511 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005512}
5513
Ana Krulec7d1d6832018-12-27 11:10:09 -08005514void SurfaceFlinger::repaintEverythingForHWC() {
5515 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07005516 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005517}
5518
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005519// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5520class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005521public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005522 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5523 ~WindowDisconnector() {
5524 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005525 }
5526
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005527private:
5528 ANativeWindow* mWindow;
5529 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005530};
5531
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005532status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005533 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
5534 const Dataspace reqDataspace,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005535 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005536 uint32_t reqWidth, uint32_t reqHeight,
5537 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08005538 ISurfaceComposer::Rotation rotation,
5539 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005540 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005541
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005542 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005543
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005544 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5545
Chia-I Wu20261cb2018-08-23 12:55:44 -07005546 sp<DisplayDevice> display;
5547 {
5548 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005549
Chia-I Wu20261cb2018-08-23 12:55:44 -07005550 display = getDisplayDeviceLocked(displayToken);
5551 if (!display) return BAD_VALUE;
5552
Chia-I Wucb023152018-08-28 12:57:23 -07005553 // set the requested width/height to the logical display viewport size
5554 // by default
5555 if (reqWidth == 0 || reqHeight == 0) {
5556 reqWidth = uint32_t(display->getViewport().width());
5557 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005558 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005559 }
5560
Peiyong Lin0e003c92018-09-17 11:09:51 -07005561 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005562 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005563
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005564 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5565 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005566 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005567 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005568}
5569
chaviw93df2ea2019-04-30 16:45:12 -07005570static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5571 switch (colorMode) {
5572 case ColorMode::DISPLAY_P3:
5573 case ColorMode::BT2100_PQ:
5574 case ColorMode::BT2100_HLG:
5575 case ColorMode::DISPLAY_BT2020:
5576 return Dataspace::DISPLAY_P3;
5577 default:
5578 return Dataspace::V0_SRGB;
5579 }
5580}
5581
5582const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5583 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5584 if (displayToken) {
5585 return getDisplayDeviceLocked(displayToken);
5586 }
5587 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5588 // may not have a displayId.
5589 for (const auto& [token, display] : mDisplays) {
5590 if (display->getLayerStack() == displayOrLayerStack) {
5591 return display;
5592 }
5593 }
5594 return nullptr;
5595}
5596
5597status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5598 sp<GraphicBuffer>* outBuffer) {
5599 sp<DisplayDevice> display;
5600 uint32_t width;
5601 uint32_t height;
5602 ui::Transform::orientation_flags captureOrientation;
5603 {
5604 Mutex::Autolock _l(mStateLock);
5605 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5606 if (!display) {
5607 return BAD_VALUE;
5608 }
5609
5610 width = uint32_t(display->getViewport().width());
5611 height = uint32_t(display->getViewport().height());
5612
5613 captureOrientation = fromSurfaceComposerRotation(
5614 static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
Alec Mouri21fab752019-06-20 14:12:17 -07005615 if (captureOrientation == ui::Transform::orientation_flags::ROT_90) {
5616 captureOrientation = ui::Transform::orientation_flags::ROT_270;
5617 } else if (captureOrientation == ui::Transform::orientation_flags::ROT_270) {
5618 captureOrientation = ui::Transform::orientation_flags::ROT_90;
5619 }
chaviw93df2ea2019-04-30 16:45:12 -07005620 *outDataspace =
5621 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5622 }
5623
5624 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5625 false /* captureSecureLayers */);
5626
5627 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5628 std::placeholders::_1);
5629 bool ignored = false;
5630 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5631 false /* useIdentityTransform */,
5632 ignored /* outCapturedSecureLayers */);
5633}
5634
Robert Carr866455f2019-04-02 16:28:26 -07005635status_t SurfaceFlinger::captureLayers(
5636 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5637 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5638 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5639 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005640 ATRACE_CALL();
5641
5642 class LayerRenderArea : public RenderArea {
5643 public:
Robert Carr578038f2018-03-09 12:25:24 -08005644 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005645 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5646 bool childrenOnly)
5647 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005648 mLayer(layer),
5649 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005650 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005651 mFlinger(flinger),
5652 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005653 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005654 Rect getBounds() const override {
5655 const Layer::State& layerState(mLayer->getDrawingState());
5656 return mLayer->getBufferSize(layerState);
5657 }
Marissa Wall61c58622018-07-18 10:12:20 -07005658 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005659 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005660 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005661 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005662 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005663 }
chaviwa76b2712017-09-20 12:02:26 -07005664 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005665 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005666 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005667 Rect getSourceCrop() const override {
5668 if (mCrop.isEmpty()) {
5669 return getBounds();
5670 } else {
5671 return mCrop;
5672 }
5673 }
Robert Carr578038f2018-03-09 12:25:24 -08005674 class ReparentForDrawing {
5675 public:
5676 const sp<Layer>& oldParent;
5677 const sp<Layer>& newParent;
5678
Vishnu Nair4351ad52019-02-11 14:13:02 -08005679 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5680 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005681 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005682 // Compute and cache the bounds for the new parent layer.
5683 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005684 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005685 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005686 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005687 };
5688
5689 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005690 const Rect sourceCrop = getSourceCrop();
5691 // no need to check rotation because there is none
5692 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5693 sourceCrop.height() != getReqHeight();
5694
Robert Carr578038f2018-03-09 12:25:24 -08005695 if (!mChildrenOnly) {
5696 mTransform = mLayer->getTransform().inverse();
5697 drawLayers();
5698 } else {
5699 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005700 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005701 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
Evan Roskya1f1e152019-01-24 16:17:46 -08005702 bounds.getWidth(), bounds.getHeight(), 0,
5703 LayerMetadata()));
Robert Carr578038f2018-03-09 12:25:24 -08005704
Vishnu Nair4351ad52019-02-11 14:13:02 -08005705 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005706 drawLayers();
5707 }
5708 }
chaviwa76b2712017-09-20 12:02:26 -07005709
chaviwa76b2712017-09-20 12:02:26 -07005710 private:
chaviw7206d492017-11-10 16:16:12 -08005711 const sp<Layer> mLayer;
5712 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005713
5714 // In the "childrenOnly" case we reparent the children to a screenshot
5715 // layer which has no properties set and which does not draw.
5716 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005717 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005718 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005719
5720 SurfaceFlinger* mFlinger;
5721 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005722 };
5723
Robert Carrc0df3122019-04-11 13:18:21 -07005724 int reqWidth = 0;
5725 int reqHeight = 0;
5726 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005727 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005728 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
chaviw7206d492017-11-10 16:16:12 -08005729
Robert Carrc0df3122019-04-11 13:18:21 -07005730 {
5731 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005732
Robert Carrc0df3122019-04-11 13:18:21 -07005733 parent = fromHandle(layerHandleBinder);
5734 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5735 ALOGE("captureLayers called with an invalid or removed parent");
5736 return NAME_NOT_FOUND;
5737 }
5738
5739 const int uid = IPCThreadState::self()->getCallingUid();
5740 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5741 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5742 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5743 return PERMISSION_DENIED;
5744 }
5745
5746 if (sourceCrop.width() <= 0) {
5747 crop.left = 0;
5748 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
5749 }
5750
5751 if (sourceCrop.height() <= 0) {
5752 crop.top = 0;
5753 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
5754 }
5755 reqWidth = crop.width() * frameScale;
5756 reqHeight = crop.height() * frameScale;
5757
5758 for (const auto& handle : excludeHandles) {
5759 sp<Layer> excludeLayer = fromHandle(handle);
5760 if (excludeLayer != nullptr) {
5761 excludeLayers.emplace(excludeLayer);
5762 } else {
5763 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5764 return NAME_NOT_FOUND;
5765 }
5766 }
5767 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005768
Chia-I Wu20261cb2018-08-23 12:55:44 -07005769 // really small crop or frameScale
5770 if (reqWidth <= 0) {
5771 reqWidth = 1;
5772 }
5773 if (reqHeight <= 0) {
5774 reqHeight = 1;
5775 }
5776
Robert Carr866455f2019-04-02 16:28:26 -07005777 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
5778 auto traverseLayers = [parent, childrenOnly,
5779 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005780 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5781 if (!layer->isVisible()) {
5782 return;
Robert Carr578038f2018-03-09 12:25:24 -08005783 } else if (childrenOnly && layer == parent.get()) {
5784 return;
chaviwa76b2712017-09-20 12:02:26 -07005785 }
Robert Carr866455f2019-04-02 16:28:26 -07005786
5787 sp<Layer> p = layer;
5788 while (p != nullptr) {
5789 if (excludeLayers.count(p) != 0) {
5790 return;
5791 }
5792 p = p->getParent();
5793 }
5794
chaviwa76b2712017-09-20 12:02:26 -07005795 visitor(layer);
5796 });
5797 };
Robert Carr108b2c72019-04-02 16:32:58 -07005798
5799 bool outCapturedSecureLayers = false;
5800 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5801 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005802}
5803
5804status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5805 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005806 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005807 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005808 bool useIdentityTransform,
5809 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005810 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005811
Peiyong Lin0e003c92018-09-17 11:09:51 -07005812 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005813 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5814 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005815 *outBuffer =
5816 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5817 static_cast<android_pixel_format>(reqPixelFormat), 1,
5818 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005819
Robert Carr108b2c72019-04-02 16:32:58 -07005820 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5821 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005822}
5823
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005824status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5825 TraverseLayersFunction traverseLayers,
5826 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005827 bool useIdentityTransform,
5828 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005829 // This mutex protects syncFd and captureResult for communication of the return values from the
5830 // main thread back to this Binder thread
5831 std::mutex captureMutex;
5832 std::condition_variable captureCondition;
5833 std::unique_lock<std::mutex> captureLock(captureMutex);
5834 int syncFd = -1;
5835 std::optional<status_t> captureResult;
5836
Robert Carr03480e22018-01-04 16:02:06 -08005837 const int uid = IPCThreadState::self()->getCallingUid();
5838 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5839
Dominik Laskowski8c001672018-05-30 16:52:06 -07005840 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005841 // If there is a refresh pending, bug out early and tell the binder thread to try again
5842 // after the refresh.
5843 if (mRefreshPending) {
5844 ATRACE_NAME("Skipping screenshot for now");
5845 std::unique_lock<std::mutex> captureLock(captureMutex);
5846 captureResult = std::make_optional<status_t>(EAGAIN);
5847 captureCondition.notify_one();
5848 return;
5849 }
5850
5851 status_t result = NO_ERROR;
5852 int fd = -1;
5853 {
5854 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005855 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005856 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005857 useIdentityTransform, forSystem, &fd,
5858 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005859 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005860 }
5861
5862 {
5863 std::unique_lock<std::mutex> captureLock(captureMutex);
5864 syncFd = fd;
5865 captureResult = std::make_optional<status_t>(result);
5866 captureCondition.notify_one();
5867 }
5868 });
5869
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005870 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005871 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005872 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005873 while (*captureResult == EAGAIN) {
5874 captureResult.reset();
5875 result = postMessageAsync(message);
5876 if (result != NO_ERROR) {
5877 return result;
5878 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005879 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005880 }
5881 result = *captureResult;
5882 }
5883
5884 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005885 sync_wait(syncFd, -1);
5886 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005887 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005888
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005889 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005890}
5891
chaviwa76b2712017-09-20 12:02:26 -07005892void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005893 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005894 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5895 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005896 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005897
chaviwa76b2712017-09-20 12:02:26 -07005898 const auto reqWidth = renderArea.getReqWidth();
5899 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005900 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005901 const auto transform = renderArea.getTransform();
5902 const auto sourceCrop = renderArea.getSourceCrop();
Dan Stozac1879002014-05-22 15:59:05 -07005903
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005904 renderengine::DisplaySettings clientCompositionDisplay;
5905 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005906
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005907 // assume that bounds are never offset, and that they are the same as the
5908 // buffer bounds.
5909 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005910 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005911 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005912
5913 // Now take into account the rotation flag. We append a transform that
5914 // rotates the layer stack about the origin, then translate by buffer
5915 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005916 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005917 int displacementX = 0;
5918 int displacementY = 0;
5919 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5920 switch (rotation) {
5921 case ui::Transform::ROT_90:
5922 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005923 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005924 break;
5925 case ui::Transform::ROT_180:
5926 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005927 displacementY = renderArea.getBounds().getWidth();
5928 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005929 break;
5930 case ui::Transform::ROT_270:
5931 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005932 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005933 break;
5934 default:
5935 break;
5936 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005937
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005938 // We need to transform the clipping window into the right spot.
5939 // First, rotate the clipping rectangle by the rotation hint to get the
5940 // right orientation
5941 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5942 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5943 const vec4 rotClipTL = rotMatrix * clipTL;
5944 const vec4 rotClipBR = rotMatrix * clipBR;
5945 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5946 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5947 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5948 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5949
5950 // Now reposition the clipping rectangle with the displacement vector
5951 // computed above.
5952 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005953 clientCompositionDisplay.clip =
5954 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5955 newClipRight + displacementX, newClipBottom + displacementY);
5956
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005957 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005958 clientCompositionDisplay.globalTransform =
5959 clipTransform * clientCompositionDisplay.globalTransform;
5960
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005961 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5962 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005963
chaviw50da5042018-04-09 13:49:37 -07005964 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005965
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005966 renderengine::LayerSettings fillLayer;
5967 fillLayer.source.buffer.buffer = nullptr;
5968 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5969 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5970 fillLayer.alpha = half(alpha);
5971 clientCompositionLayers.push_back(fillLayer);
5972
5973 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005974 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005975 renderengine::LayerSettings layerSettings;
5976 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005977 false, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005978 if (prepared) {
5979 clientCompositionLayers.push_back(layerSettings);
5980 }
chaviwa76b2712017-09-20 12:02:26 -07005981 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005982
5983 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005984 // Use an empty fence for the buffer fence, since we just created the buffer so
5985 // there is no need for synchronization with the GPU.
5986 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005987 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005988 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005989 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005990 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005991
5992 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005993}
5994
chaviwa76b2712017-09-20 12:02:26 -07005995status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5996 TraverseLayersFunction traverseLayers,
5997 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005998 bool useIdentityTransform, bool forSystem,
5999 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006000 ATRACE_CALL();
6001
chaviwa76b2712017-09-20 12:02:26 -07006002 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07006003 outCapturedSecureLayers =
6004 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07006005 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08006006
Robert Carr03480e22018-01-04 16:02:06 -08006007 // We allow the system server to take screenshots of secure layers for
6008 // use in situations like the Screen-rotation animation and place
6009 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07006010 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08006011 ALOGW("FB is protected: PERMISSION_DENIED");
6012 return PERMISSION_DENIED;
6013 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006014 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006015 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07006016}
6017
chaviw95ef3c42019-02-14 10:55:09 -08006018void SurfaceFlinger::setInputWindowsFinished() {
6019 Mutex::Autolock _l(mStateLock);
6020
6021 mPendingSyncInputWindows = false;
6022 mTransactionCV.broadcast();
6023}
chaviw5f21a5e2019-02-14 10:00:34 -08006024
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07006025// ---------------------------------------------------------------------------
6026
Dan Stoza412903f2017-04-27 13:42:17 -07006027void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
6028 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006029}
6030
Dan Stoza412903f2017-04-27 13:42:17 -07006031void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
6032 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006033}
6034
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006035void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07006036 const LayerVector::Visitor& visitor) {
6037 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07006038 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07006039 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006040 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07006041 continue;
6042 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08006043 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07006044 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006045 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01006046 return;
6047 }
chaviwa76b2712017-09-20 12:02:26 -07006048 if (!layer->isVisible()) {
6049 return;
6050 }
6051 visitor(layer);
6052 });
6053 }
6054}
6055
Dominik Laskowski22488f62019-03-28 09:53:04 -07006056void SurfaceFlinger::setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
6057 const std::vector<int32_t>& allowedConfigs) {
6058 if (!display->isPrimary()) {
Ady Abraham838de062019-02-04 10:24:03 -08006059 return;
6060 }
6061
6062 ALOGV("Updating allowed configs");
Dominik Laskowski22488f62019-03-28 09:53:04 -07006063 mAllowedDisplayConfigs = DisplayConfigs(allowedConfigs.begin(), allowedConfigs.end());
Ady Abraham838de062019-02-04 10:24:03 -08006064
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006065 // Set the highest allowed config by iterating backwards on available refresh rates
Dominik Laskowski22488f62019-03-28 09:53:04 -07006066 const auto& refreshRates = mRefreshRateConfigs.getRefreshRates();
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006067 for (auto iter = refreshRates.crbegin(); iter != refreshRates.crend(); ++iter) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07006068 if (iter->second && isDisplayConfigAllowed(iter->second->configId)) {
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006069 ALOGV("switching to config %d", iter->second->configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -07006070 setDesiredActiveConfig(
6071 {iter->first, iter->second->configId, Scheduler::ConfigEvent::Changed});
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006072 break;
Ady Abraham97d04232019-03-05 19:48:12 -08006073 }
6074 }
Ady Abraham838de062019-02-04 10:24:03 -08006075}
6076
Dominik Laskowski22488f62019-03-28 09:53:04 -07006077status_t SurfaceFlinger::setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abraham838de062019-02-04 10:24:03 -08006078 const std::vector<int32_t>& allowedConfigs) {
6079 ATRACE_CALL();
6080
Dominik Laskowski22488f62019-03-28 09:53:04 -07006081 if (!displayToken || allowedConfigs.empty()) {
Ady Abraham838de062019-02-04 10:24:03 -08006082 return BAD_VALUE;
6083 }
6084
Ady Abraham34392f72019-04-10 11:29:27 -07006085 if (mDebugDisplayConfigSetByBackdoor) {
6086 // ignore this request as config is overridden by backdoor
6087 return NO_ERROR;
6088 }
6089
Ady Abraham838de062019-02-04 10:24:03 -08006090 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski22488f62019-03-28 09:53:04 -07006091 const auto display = getDisplayDeviceLocked(displayToken);
6092 if (!display) {
6093 ALOGE("Attempt to set allowed display configs for invalid display token %p",
6094 displayToken.get());
6095 } else if (display->isVirtual()) {
6096 ALOGW("Attempt to set allowed display configs for virtual display");
6097 } else {
6098 setAllowedDisplayConfigsInternal(display, allowedConfigs);
6099 }
Ady Abraham838de062019-02-04 10:24:03 -08006100 }));
Dominik Laskowski22488f62019-03-28 09:53:04 -07006101
Ady Abraham838de062019-02-04 10:24:03 -08006102 return NO_ERROR;
6103}
6104
Dominik Laskowski22488f62019-03-28 09:53:04 -07006105status_t SurfaceFlinger::getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006106 std::vector<int32_t>* outAllowedConfigs) {
6107 ATRACE_CALL();
6108
Dominik Laskowski22488f62019-03-28 09:53:04 -07006109 if (!displayToken || !outAllowedConfigs) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006110 return BAD_VALUE;
6111 }
6112
Dominik Laskowski22488f62019-03-28 09:53:04 -07006113 Mutex::Autolock lock(mStateLock);
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006114
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006115 const auto display = getDisplayDeviceLocked(displayToken);
6116 if (!display) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006117 return NAME_NOT_FOUND;
6118 }
6119
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006120 if (display->isPrimary()) {
6121 outAllowedConfigs->assign(mAllowedDisplayConfigs.begin(), mAllowedDisplayConfigs.end());
6122 }
6123
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006124 return NO_ERROR;
6125}
6126
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006127void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006128 mFlinger->setInputWindowsFinished();
6129}
6130
Robert Carrc0df3122019-04-11 13:18:21 -07006131sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6132 BBinder *b = handle->localBinder();
6133 if (b == nullptr) {
6134 return nullptr;
6135 }
6136 auto it = mLayersByLocalBinderToken.find(b);
6137 if (it != mLayersByLocalBinderToken.end()) {
6138 return it->second.promote();
6139 }
6140 return nullptr;
6141}
6142
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006143} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006144
Mathias Agopian3f844832013-08-07 21:24:32 -07006145#if defined(__gl_h_)
6146#error "don't include gl/gl.h in this file"
6147#endif
6148
6149#if defined(__gl2_h_)
6150#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006151#endif